1bitLLM commited on
Commit
d2ae486
1 Parent(s): 0dcf07d

Upload 15 files

Browse files
added_tokens.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "</line>": 32001,
3
+ "<pad>": 32000
4
+ }
config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "1bitLLM/bitnet_b1_58-3B",
3
+ "architectures": [
4
+ "BitnetForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "bos_token_id": 1,
9
+ "eos_token_id": 2,
10
+ "hidden_act": "silu",
11
+ "hidden_size": 3200,
12
+ "initializer_range": 0.02,
13
+ "input_bits": 8,
14
+ "intermediate_size": 8640,
15
+ "max_position_embeddings": 2048,
16
+ "model_type": "llama",
17
+ "num_attention_heads": 32,
18
+ "num_hidden_layers": 26,
19
+ "num_key_value_heads": 32,
20
+ "pad_token_id": 32000,
21
+ "pretraining_tp": 1,
22
+ "rms_norm_eps": 1e-05,
23
+ "rope_scaling": null,
24
+ "rope_theta": 10000.0,
25
+ "tie_word_embeddings": true,
26
+ "torch_dtype": "float16",
27
+ "transformers_version": "4.39.0",
28
+ "use_cache": true,
29
+ "vocab_size": 32002,
30
+ "weight_bits": 1
31
+ }
configuration_bitnet.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ LLaMA model configuration"""
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
29
+
30
+
31
+ class BitnetConfig(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`BitnetModel`]. It is used to instantiate an LLaMA
34
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
35
+ defaults will yield a similar configuration to that of the LLaMA-7B.
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 32000):
43
+ Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`BitnetModel`]
45
+ hidden_size (`int`, *optional*, defaults to 4096):
46
+ Dimension of the hidden representations.
47
+ intermediate_size (`int`, *optional*, defaults to 11008):
48
+ Dimension of the MLP representations.
49
+ num_hidden_layers (`int`, *optional*, defaults to 32):
50
+ Number of hidden layers in the Transformer decoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 32):
52
+ Number of attention heads for each attention layer in the Transformer decoder.
53
+ num_key_value_heads (`int`, *optional*):
54
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
+ by meanpooling all the original heads within that group. For more details checkout [this
59
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
60
+ `num_attention_heads`.
61
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
62
+ The non-linear activation function (function or string) in the decoder.
63
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
64
+ The maximum sequence length that this model might ever be used with. Bitnet 1 supports up to 2048 tokens,
65
+ Bitnet 2 up to 4096, CodeBitnet up to 16384.
66
+ initializer_range (`float`, *optional*, defaults to 0.02):
67
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
68
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
69
+ The epsilon used by the rms normalization layers.
70
+ use_cache (`bool`, *optional*, defaults to `True`):
71
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
72
+ relevant if `config.is_decoder=True`.
73
+ pad_token_id (`int`, *optional*):
74
+ Padding token id.
75
+ bos_token_id (`int`, *optional*, defaults to 1):
76
+ Beginning of stream token id.
77
+ eos_token_id (`int`, *optional*, defaults to 2):
78
+ End of stream token id.
79
+ pretraining_tp (`int`, *optional*, defaults to 1):
80
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
81
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to understand more about it. This value is
82
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
83
+ issue](https://github.com/pytorch/pytorch/issues/76232).
84
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
85
+ Whether to tie weight embeddings
86
+ rope_theta (`float`, *optional*, defaults to 10000.0):
87
+ The base period of the RoPE embeddings.
88
+ rope_scaling (`Dict`, *optional*):
89
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
90
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
91
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
92
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
93
+ these scaling strategies behave:
94
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
95
+ experimental feature, subject to breaking API changes in future versions.
96
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
97
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
98
+ attention_dropout (`float`, *optional*, defaults to 0.0):
99
+ The dropout ratio for the attention probabilities.
100
+
101
+ ```python
102
+ >>> from transformers import BitnetModel, BitnetConfig
103
+
104
+ >>> # Initializing a LLaMA llama-7b style configuration
105
+ >>> configuration = BitnetConfig()
106
+
107
+ >>> # Initializing a model from the llama-7b style configuration
108
+ >>> model = BitnetModel(configuration)
109
+
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+
114
+ model_type = "llama"
115
+ keys_to_ignore_at_inference = ["past_key_values"]
116
+
117
+ def __init__(
118
+ self,
119
+ vocab_size=32000,
120
+ hidden_size=4096,
121
+ intermediate_size=11008,
122
+ num_hidden_layers=32,
123
+ num_attention_heads=32,
124
+ num_key_value_heads=None,
125
+ hidden_act="silu",
126
+ max_position_embeddings=2048,
127
+ initializer_range=0.02,
128
+ rms_norm_eps=1e-6,
129
+ use_cache=True,
130
+ pad_token_id=None,
131
+ bos_token_id=1,
132
+ eos_token_id=2,
133
+ pretraining_tp=1,
134
+ tie_word_embeddings=False,
135
+ rope_theta=10000.0,
136
+ rope_scaling=None,
137
+ attention_bias=False,
138
+ attention_dropout=0.0,
139
+ weight_bits=1,
140
+ input_bits=8,
141
+ **kwargs,
142
+ ):
143
+ self.vocab_size = vocab_size
144
+ self.max_position_embeddings = max_position_embeddings
145
+ self.hidden_size = hidden_size
146
+ self.intermediate_size = intermediate_size
147
+ self.num_hidden_layers = num_hidden_layers
148
+ self.num_attention_heads = num_attention_heads
149
+
150
+ # for backward compatibility
151
+ if num_key_value_heads is None:
152
+ num_key_value_heads = num_attention_heads
153
+
154
+ self.num_key_value_heads = num_key_value_heads
155
+ self.hidden_act = hidden_act
156
+ self.initializer_range = initializer_range
157
+ self.rms_norm_eps = rms_norm_eps
158
+ self.pretraining_tp = pretraining_tp
159
+ self.use_cache = use_cache
160
+ self.rope_theta = rope_theta
161
+ self.rope_scaling = rope_scaling
162
+ self._rope_scaling_validation()
163
+ self.attention_bias = attention_bias
164
+ self.attention_dropout = attention_dropout
165
+ self.weight_bits = weight_bits
166
+ self.input_bits = input_bits
167
+
168
+ super().__init__(
169
+ pad_token_id=pad_token_id,
170
+ bos_token_id=bos_token_id,
171
+ eos_token_id=eos_token_id,
172
+ tie_word_embeddings=tie_word_embeddings,
173
+ **kwargs,
174
+ )
175
+
176
+ def _rope_scaling_validation(self):
177
+ """
178
+ Validate the `rope_scaling` configuration.
179
+ """
180
+ if self.rope_scaling is None:
181
+ return
182
+
183
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
184
+ raise ValueError(
185
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
186
+ f"got {self.rope_scaling}"
187
+ )
188
+ rope_scaling_type = self.rope_scaling.get("type", None)
189
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
190
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
191
+ raise ValueError(
192
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
193
+ )
194
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
195
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
eval_ppl.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import argparse
3
+ import torch
4
+ import random
5
+
6
+ from eval_utils import get_test_dataset
7
+ from .modeling_bitnet import BitnetForCausalLM
8
+ from .tokenization_bitnet import BitnetTokenizer
9
+
10
+ from tqdm import tqdm
11
+ torch.set_grad_enabled(False)
12
+
13
+ parser = argparse.ArgumentParser()
14
+ parser.add_argument('--seed', default=0, type=int)
15
+ parser.add_argument('--hf_path', default='1bitLLM/bitnet_b1_58-3B', type=str)
16
+ parser.add_argument('--seqlen', default=2048, type=int)
17
+
18
+
19
+ def calulate_loss(model, input, loss_fct):
20
+ output = model(input,
21
+ use_cache=False,
22
+ output_hidden_states=False,
23
+ output_attentions=False)[0]
24
+ shift_logits = output[:, :-1, :].contiguous()
25
+ shift_labels = input[:, 1:]
26
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
27
+ return loss
28
+
29
+
30
+ def main(args):
31
+ datasets = ['c4', 'wikitext2']
32
+ model = BitnetForCausalLM.from_pretrained(
33
+ args.hf_path,
34
+ device_map='auto',
35
+ low_cpu_mem_usage=True,
36
+ use_flash_attention_2=True,
37
+ torch_dtype=torch.float16,
38
+ ).half()
39
+ tokenizer = BitnetTokenizer.from_pretrained(args.hf_path, use_fast=False)
40
+ loss_fct = torch.nn.CrossEntropyLoss(reduction="sum").cuda()
41
+
42
+ ppl = []
43
+ for dataset in datasets:
44
+ testdata = get_test_dataset(dataset, tokenizer, seqlen=args.seqlen)
45
+ acc_loss, count = 0.0, 0
46
+ progress = tqdm(range(len(testdata)))
47
+ for ii in progress:
48
+ input = torch.Tensor(testdata[ii]).long().cuda().view(1, -1)
49
+ loss = calulate_loss(model, input, loss_fct)
50
+ count += (input.size(-1) - 1)
51
+ acc_loss += loss.item()
52
+ progress.set_description(f"avg_loss = {acc_loss/ count / math.log(2)}")
53
+
54
+ avg_loss = acc_loss / count / math.log(2)
55
+ ppl.append(2 ** avg_loss)
56
+ print("{} PPL: {}".format(dataset, ppl[-1]))
57
+
58
+ print(ppl)
59
+ print("Avg PPL:", sum(ppl) / len(ppl))
60
+
61
+
62
+ if __name__ == '__main__':
63
+ torch.set_grad_enabled(False)
64
+ args = parser.parse_args()
65
+ random.seed(args.seed)
66
+ torch.random.manual_seed(args.seed)
67
+ main(args)
eval_task.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import argparse
4
+ import torch
5
+ import random
6
+ import glog
7
+
8
+ from lm_eval import evaluator
9
+ from eval_utils import LMEvalAdaptor
10
+ from .tokenization_bitnet import BitnetTokenizer
11
+ from .modeling_bitnet import BitnetForCausalLM
12
+
13
+
14
+ parser = argparse.ArgumentParser()
15
+ parser.add_argument('--seed', default=0, type=int)
16
+ parser.add_argument('--hf_path', default='1bitLLM/bitnet_b1_58-3B', type=str)
17
+ parser.add_argument('--batch_size', type=int, default=1, help='batch size')
18
+ parser.add_argument("--tasks", type=str)
19
+ parser.add_argument("--output_path", default=None, type=str)
20
+ parser.add_argument('--num_fewshot', type=int, default=0)
21
+ parser.add_argument('--ctx_size', default=2048, type=int)
22
+
23
+
24
+ def main(args):
25
+ model_str = args.hf_path
26
+ model = BitnetForCausalLM.from_pretrained(
27
+ args.hf_path,
28
+ device_map='auto',
29
+ low_cpu_mem_usage=True,
30
+ use_flash_attention_2=True,
31
+ torch_dtype=torch.float16,
32
+ ).half()
33
+
34
+ tokenizer = BitnetTokenizer.from_pretrained(args.hf_path, use_fast=False)
35
+ glog.info('loaded model!')
36
+
37
+ task_names = args.tasks.split(",")
38
+
39
+ lm_eval_model = LMEvalAdaptor(model_str, model, tokenizer, args.batch_size, args.ctx_size)
40
+ results = evaluator.simple_evaluate(
41
+ model=lm_eval_model,
42
+ tasks=task_names,
43
+ batch_size=args.batch_size,
44
+ no_cache=True,
45
+ num_fewshot=args.num_fewshot,
46
+ )
47
+
48
+ print(evaluator.make_table(results))
49
+
50
+ if args.output_path is not None:
51
+ os.makedirs(os.path.dirname(args.output_path), exist_ok=True)
52
+ # otherwise cannot save
53
+ results["config"]["model"] = args.hf_path
54
+ with open(args.output_path, "w") as f:
55
+ json.dump(results, f, indent=2)
56
+
57
+
58
+ if __name__ == '__main__':
59
+ torch.set_grad_enabled(False)
60
+ args = parser.parse_args()
61
+ random.seed(args.seed)
62
+ torch.random.manual_seed(args.seed)
63
+ main(args)
eval_utils.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ import numpy as np
4
+ import torch.nn.functional as F
5
+
6
+ from lm_eval.base import BaseLM
7
+ from datasets import load_dataset
8
+
9
+
10
+ def set_seed(seed):
11
+ np.random.seed(seed)
12
+ torch.random.manual_seed(seed)
13
+
14
+ def get_test_dataset(dataset_name, tokenizer, seqlen=2048):
15
+ if dataset_name == "wikitext2":
16
+ testdata = load_dataset('wikitext', 'wikitext-2-raw-v1', split='test')
17
+ testdata = "".join(testdata['text']).split('\n')
18
+ elif dataset_name == "c4":
19
+ testdata = load_dataset('allenai/c4', data_files={'validation': 'en/c4-validation.00000-of-00008.json.gz'}, split='validation')['text']
20
+ else:
21
+ raise NotImplementedError
22
+
23
+ testdata = [item for item in testdata if item != ""]
24
+ tokenized_text = [tokenizer(item, add_special_tokens=False)['input_ids'] + [tokenizer.eos_token_id] for item in testdata]
25
+
26
+ data, doc = [], [tokenizer.bos_token_id]
27
+ for sen in tokenized_text:
28
+ if len(sen) > seqlen:
29
+ continue
30
+ if len(doc) + len(sen) > seqlen:
31
+ data.append(doc)
32
+ doc = [tokenizer.bos_token_id]
33
+ doc.extend(sen)
34
+ if len(doc) > 1 and len(doc) <= seqlen:
35
+ data.append(doc)
36
+ return data
37
+
38
+
39
+ class LMEvalAdaptor(BaseLM):
40
+ def __init__(self, model_name, model, tokenizer, batch_size=1, max_length=-1):
41
+ super().__init__()
42
+
43
+ assert isinstance(batch_size, int)
44
+
45
+ self.model_name = model_name
46
+ self.model = model
47
+ self.model.eval()
48
+
49
+ self.tokenizer = tokenizer
50
+
51
+ self.vocab_size = self.tokenizer.vocab_size
52
+
53
+ self._batch_size = batch_size
54
+
55
+ self._max_length = max_length
56
+
57
+ @property
58
+ def eot_token_id(self):
59
+ # we use EOT because end of *text* is more accurate for what we're doing than end of *sentence*
60
+ return self.tokenizer.eos_token_id
61
+
62
+ @property
63
+ def max_length(self):
64
+ if self._max_length != -1:
65
+ return self._max_length
66
+ if hasattr(self.model.config, "n_ctx"):
67
+ return self.model.config.n_ctx
68
+ elif hasattr(self.model.config, "max_position_embeddings"):
69
+ return self.model.config.max_position_embeddings
70
+ elif hasattr(self.model.config, "n_positions"):
71
+ return self.model.config.n_positions
72
+ elif "bloom" in self.model_name:
73
+ return 2048
74
+ elif "llama" in self.model_name:
75
+ return 2048 # TODO: did not check this
76
+ elif "mpt" in self.model_name:
77
+ return 2048
78
+ elif "falcon" in self.model_name:
79
+ return 2048
80
+ else:
81
+ print(self.model.config)
82
+ raise NotImplementedError
83
+
84
+ @property
85
+ def max_gen_toks(self):
86
+ return 256
87
+
88
+ @property
89
+ def batch_size(self):
90
+ return self._batch_size
91
+
92
+ @property
93
+ def device(self):
94
+ return "cuda"
95
+
96
+ def tok_encode(self, string: str, add_special_tokens=True):
97
+ return self.tokenizer.encode(string, add_special_tokens=add_special_tokens)
98
+
99
+ def tok_decode(self, tokens):
100
+ return self.tokenizer.decode(tokens)
101
+
102
+ def loglikelihood(self, requests):
103
+ new_reqs = []
104
+ for context, continuation in requests:
105
+ context, continuation = context.strip(), continuation.strip()
106
+ if context == "":
107
+ # end of text as context
108
+ context_enc = [self.eot_token_id]
109
+ else:
110
+ context_enc = self.tok_encode(context, add_special_tokens=True)
111
+
112
+ continuation_enc = self.tok_encode(continuation, add_special_tokens=False)
113
+
114
+ new_reqs.append(((context, continuation), context_enc, continuation_enc))
115
+
116
+ return self._loglikelihood_tokens(new_reqs)
117
+
118
+ def _model_call(self, inps):
119
+ """
120
+ inps: a torch tensor of shape [batch, sequence]
121
+ the size of sequence may vary from call to call
122
+
123
+ returns: a torch tensor of shape [batch, sequence, vocab] with the
124
+ logits returned from the model
125
+ """
126
+ with torch.no_grad():
127
+ out = self.model(inps)[0]
128
+ return out
129
+
130
+ def _model_generate(self, context, max_length, eos_token_id):
131
+ return self.model.generate(
132
+ context, max_length=max_length, eos_token_id=eos_token_id, do_sample=False
133
+ )
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 2,
5
+ "pad_token_id": 1,
6
+ "transformers_version": "4.39.0"
7
+ }
model.safetensors.index.json ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 13297556560
4
+ },
5
+ "weight_map": {
6
+ "model.embed_tokens.weight": "model-00001-of-00003.safetensors",
7
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00003.safetensors",
8
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
9
+ "model.layers.0.mlp.ffn_layernorm.weight": "model-00001-of-00003.safetensors",
10
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
11
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
12
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
13
+ "model.layers.0.self_attn.inner_attn_ln.weight": "model-00001-of-00003.safetensors",
14
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
15
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
16
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
17
+ "model.layers.0.self_attn.rotary_emb.inv_freq": "model-00001-of-00003.safetensors",
18
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
19
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00003.safetensors",
20
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
21
+ "model.layers.1.mlp.ffn_layernorm.weight": "model-00001-of-00003.safetensors",
22
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
23
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
24
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
25
+ "model.layers.1.self_attn.inner_attn_ln.weight": "model-00001-of-00003.safetensors",
26
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
27
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
28
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
29
+ "model.layers.1.self_attn.rotary_emb.inv_freq": "model-00001-of-00003.safetensors",
30
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
31
+ "model.layers.10.input_layernorm.weight": "model-00002-of-00003.safetensors",
32
+ "model.layers.10.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
33
+ "model.layers.10.mlp.ffn_layernorm.weight": "model-00002-of-00003.safetensors",
34
+ "model.layers.10.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
35
+ "model.layers.10.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
36
+ "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
37
+ "model.layers.10.self_attn.inner_attn_ln.weight": "model-00002-of-00003.safetensors",
38
+ "model.layers.10.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
39
+ "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
40
+ "model.layers.10.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
41
+ "model.layers.10.self_attn.rotary_emb.inv_freq": "model-00002-of-00003.safetensors",
42
+ "model.layers.10.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
43
+ "model.layers.11.input_layernorm.weight": "model-00002-of-00003.safetensors",
44
+ "model.layers.11.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
45
+ "model.layers.11.mlp.ffn_layernorm.weight": "model-00002-of-00003.safetensors",
46
+ "model.layers.11.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
47
+ "model.layers.11.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
48
+ "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
49
+ "model.layers.11.self_attn.inner_attn_ln.weight": "model-00002-of-00003.safetensors",
50
+ "model.layers.11.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
51
+ "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
52
+ "model.layers.11.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
53
+ "model.layers.11.self_attn.rotary_emb.inv_freq": "model-00002-of-00003.safetensors",
54
+ "model.layers.11.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
55
+ "model.layers.12.input_layernorm.weight": "model-00002-of-00003.safetensors",
56
+ "model.layers.12.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
57
+ "model.layers.12.mlp.ffn_layernorm.weight": "model-00002-of-00003.safetensors",
58
+ "model.layers.12.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
59
+ "model.layers.12.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
60
+ "model.layers.12.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
61
+ "model.layers.12.self_attn.inner_attn_ln.weight": "model-00002-of-00003.safetensors",
62
+ "model.layers.12.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
63
+ "model.layers.12.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
64
+ "model.layers.12.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
65
+ "model.layers.12.self_attn.rotary_emb.inv_freq": "model-00002-of-00003.safetensors",
66
+ "model.layers.12.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
67
+ "model.layers.13.input_layernorm.weight": "model-00002-of-00003.safetensors",
68
+ "model.layers.13.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
69
+ "model.layers.13.mlp.ffn_layernorm.weight": "model-00002-of-00003.safetensors",
70
+ "model.layers.13.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
71
+ "model.layers.13.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
72
+ "model.layers.13.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
73
+ "model.layers.13.self_attn.inner_attn_ln.weight": "model-00002-of-00003.safetensors",
74
+ "model.layers.13.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
75
+ "model.layers.13.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
76
+ "model.layers.13.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
77
+ "model.layers.13.self_attn.rotary_emb.inv_freq": "model-00002-of-00003.safetensors",
78
+ "model.layers.13.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
79
+ "model.layers.14.input_layernorm.weight": "model-00002-of-00003.safetensors",
80
+ "model.layers.14.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
81
+ "model.layers.14.mlp.ffn_layernorm.weight": "model-00002-of-00003.safetensors",
82
+ "model.layers.14.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
83
+ "model.layers.14.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
84
+ "model.layers.14.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
85
+ "model.layers.14.self_attn.inner_attn_ln.weight": "model-00002-of-00003.safetensors",
86
+ "model.layers.14.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
87
+ "model.layers.14.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
88
+ "model.layers.14.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
89
+ "model.layers.14.self_attn.rotary_emb.inv_freq": "model-00002-of-00003.safetensors",
90
+ "model.layers.14.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
91
+ "model.layers.15.input_layernorm.weight": "model-00002-of-00003.safetensors",
92
+ "model.layers.15.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
93
+ "model.layers.15.mlp.ffn_layernorm.weight": "model-00002-of-00003.safetensors",
94
+ "model.layers.15.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
95
+ "model.layers.15.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
96
+ "model.layers.15.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
97
+ "model.layers.15.self_attn.inner_attn_ln.weight": "model-00002-of-00003.safetensors",
98
+ "model.layers.15.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
99
+ "model.layers.15.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
100
+ "model.layers.15.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
101
+ "model.layers.15.self_attn.rotary_emb.inv_freq": "model-00002-of-00003.safetensors",
102
+ "model.layers.15.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
103
+ "model.layers.16.input_layernorm.weight": "model-00002-of-00003.safetensors",
104
+ "model.layers.16.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
105
+ "model.layers.16.mlp.ffn_layernorm.weight": "model-00002-of-00003.safetensors",
106
+ "model.layers.16.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
107
+ "model.layers.16.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
108
+ "model.layers.16.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
109
+ "model.layers.16.self_attn.inner_attn_ln.weight": "model-00002-of-00003.safetensors",
110
+ "model.layers.16.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
111
+ "model.layers.16.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
112
+ "model.layers.16.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
113
+ "model.layers.16.self_attn.rotary_emb.inv_freq": "model-00002-of-00003.safetensors",
114
+ "model.layers.16.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
115
+ "model.layers.17.input_layernorm.weight": "model-00002-of-00003.safetensors",
116
+ "model.layers.17.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
117
+ "model.layers.17.mlp.ffn_layernorm.weight": "model-00002-of-00003.safetensors",
118
+ "model.layers.17.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
119
+ "model.layers.17.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
120
+ "model.layers.17.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
121
+ "model.layers.17.self_attn.inner_attn_ln.weight": "model-00002-of-00003.safetensors",
122
+ "model.layers.17.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
123
+ "model.layers.17.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
124
+ "model.layers.17.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
125
+ "model.layers.17.self_attn.rotary_emb.inv_freq": "model-00002-of-00003.safetensors",
126
+ "model.layers.17.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
127
+ "model.layers.18.input_layernorm.weight": "model-00002-of-00003.safetensors",
128
+ "model.layers.18.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
129
+ "model.layers.18.mlp.ffn_layernorm.weight": "model-00002-of-00003.safetensors",
130
+ "model.layers.18.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
131
+ "model.layers.18.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
132
+ "model.layers.18.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
133
+ "model.layers.18.self_attn.inner_attn_ln.weight": "model-00002-of-00003.safetensors",
134
+ "model.layers.18.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
135
+ "model.layers.18.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
136
+ "model.layers.18.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
137
+ "model.layers.18.self_attn.rotary_emb.inv_freq": "model-00002-of-00003.safetensors",
138
+ "model.layers.18.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
139
+ "model.layers.19.input_layernorm.weight": "model-00003-of-00003.safetensors",
140
+ "model.layers.19.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
141
+ "model.layers.19.mlp.ffn_layernorm.weight": "model-00003-of-00003.safetensors",
142
+ "model.layers.19.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
143
+ "model.layers.19.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
144
+ "model.layers.19.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
145
+ "model.layers.19.self_attn.inner_attn_ln.weight": "model-00002-of-00003.safetensors",
146
+ "model.layers.19.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
147
+ "model.layers.19.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
148
+ "model.layers.19.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
149
+ "model.layers.19.self_attn.rotary_emb.inv_freq": "model-00002-of-00003.safetensors",
150
+ "model.layers.19.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
151
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00003.safetensors",
152
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
153
+ "model.layers.2.mlp.ffn_layernorm.weight": "model-00001-of-00003.safetensors",
154
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
155
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
156
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
157
+ "model.layers.2.self_attn.inner_attn_ln.weight": "model-00001-of-00003.safetensors",
158
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
159
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
160
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
161
+ "model.layers.2.self_attn.rotary_emb.inv_freq": "model-00001-of-00003.safetensors",
162
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
163
+ "model.layers.20.input_layernorm.weight": "model-00003-of-00003.safetensors",
164
+ "model.layers.20.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
165
+ "model.layers.20.mlp.ffn_layernorm.weight": "model-00003-of-00003.safetensors",
166
+ "model.layers.20.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
167
+ "model.layers.20.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
168
+ "model.layers.20.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
169
+ "model.layers.20.self_attn.inner_attn_ln.weight": "model-00003-of-00003.safetensors",
170
+ "model.layers.20.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
171
+ "model.layers.20.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
172
+ "model.layers.20.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
173
+ "model.layers.20.self_attn.rotary_emb.inv_freq": "model-00003-of-00003.safetensors",
174
+ "model.layers.20.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
175
+ "model.layers.21.input_layernorm.weight": "model-00003-of-00003.safetensors",
176
+ "model.layers.21.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
177
+ "model.layers.21.mlp.ffn_layernorm.weight": "model-00003-of-00003.safetensors",
178
+ "model.layers.21.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
179
+ "model.layers.21.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
180
+ "model.layers.21.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
181
+ "model.layers.21.self_attn.inner_attn_ln.weight": "model-00003-of-00003.safetensors",
182
+ "model.layers.21.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
183
+ "model.layers.21.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
184
+ "model.layers.21.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
185
+ "model.layers.21.self_attn.rotary_emb.inv_freq": "model-00003-of-00003.safetensors",
186
+ "model.layers.21.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
187
+ "model.layers.22.input_layernorm.weight": "model-00003-of-00003.safetensors",
188
+ "model.layers.22.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
189
+ "model.layers.22.mlp.ffn_layernorm.weight": "model-00003-of-00003.safetensors",
190
+ "model.layers.22.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
191
+ "model.layers.22.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
192
+ "model.layers.22.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
193
+ "model.layers.22.self_attn.inner_attn_ln.weight": "model-00003-of-00003.safetensors",
194
+ "model.layers.22.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
195
+ "model.layers.22.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
196
+ "model.layers.22.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
197
+ "model.layers.22.self_attn.rotary_emb.inv_freq": "model-00003-of-00003.safetensors",
198
+ "model.layers.22.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
199
+ "model.layers.23.input_layernorm.weight": "model-00003-of-00003.safetensors",
200
+ "model.layers.23.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
201
+ "model.layers.23.mlp.ffn_layernorm.weight": "model-00003-of-00003.safetensors",
202
+ "model.layers.23.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
203
+ "model.layers.23.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
204
+ "model.layers.23.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
205
+ "model.layers.23.self_attn.inner_attn_ln.weight": "model-00003-of-00003.safetensors",
206
+ "model.layers.23.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
207
+ "model.layers.23.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
208
+ "model.layers.23.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
209
+ "model.layers.23.self_attn.rotary_emb.inv_freq": "model-00003-of-00003.safetensors",
210
+ "model.layers.23.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
211
+ "model.layers.24.input_layernorm.weight": "model-00003-of-00003.safetensors",
212
+ "model.layers.24.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
213
+ "model.layers.24.mlp.ffn_layernorm.weight": "model-00003-of-00003.safetensors",
214
+ "model.layers.24.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
215
+ "model.layers.24.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
216
+ "model.layers.24.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
217
+ "model.layers.24.self_attn.inner_attn_ln.weight": "model-00003-of-00003.safetensors",
218
+ "model.layers.24.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
219
+ "model.layers.24.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
220
+ "model.layers.24.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
221
+ "model.layers.24.self_attn.rotary_emb.inv_freq": "model-00003-of-00003.safetensors",
222
+ "model.layers.24.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
223
+ "model.layers.25.input_layernorm.weight": "model-00003-of-00003.safetensors",
224
+ "model.layers.25.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
225
+ "model.layers.25.mlp.ffn_layernorm.weight": "model-00003-of-00003.safetensors",
226
+ "model.layers.25.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
227
+ "model.layers.25.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
228
+ "model.layers.25.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
229
+ "model.layers.25.self_attn.inner_attn_ln.weight": "model-00003-of-00003.safetensors",
230
+ "model.layers.25.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
231
+ "model.layers.25.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
232
+ "model.layers.25.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
233
+ "model.layers.25.self_attn.rotary_emb.inv_freq": "model-00003-of-00003.safetensors",
234
+ "model.layers.25.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
235
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00003.safetensors",
236
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
237
+ "model.layers.3.mlp.ffn_layernorm.weight": "model-00001-of-00003.safetensors",
238
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
239
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
240
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
241
+ "model.layers.3.self_attn.inner_attn_ln.weight": "model-00001-of-00003.safetensors",
242
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
243
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
244
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
245
+ "model.layers.3.self_attn.rotary_emb.inv_freq": "model-00001-of-00003.safetensors",
246
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
247
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00003.safetensors",
248
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
249
+ "model.layers.4.mlp.ffn_layernorm.weight": "model-00001-of-00003.safetensors",
250
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
251
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
252
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
253
+ "model.layers.4.self_attn.inner_attn_ln.weight": "model-00001-of-00003.safetensors",
254
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
255
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
256
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
257
+ "model.layers.4.self_attn.rotary_emb.inv_freq": "model-00001-of-00003.safetensors",
258
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
259
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00003.safetensors",
260
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
261
+ "model.layers.5.mlp.ffn_layernorm.weight": "model-00001-of-00003.safetensors",
262
+ "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
263
+ "model.layers.5.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
264
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
265
+ "model.layers.5.self_attn.inner_attn_ln.weight": "model-00001-of-00003.safetensors",
266
+ "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
267
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
268
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
269
+ "model.layers.5.self_attn.rotary_emb.inv_freq": "model-00001-of-00003.safetensors",
270
+ "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
271
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00003.safetensors",
272
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
273
+ "model.layers.6.mlp.ffn_layernorm.weight": "model-00001-of-00003.safetensors",
274
+ "model.layers.6.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
275
+ "model.layers.6.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
276
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
277
+ "model.layers.6.self_attn.inner_attn_ln.weight": "model-00001-of-00003.safetensors",
278
+ "model.layers.6.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
279
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
280
+ "model.layers.6.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
281
+ "model.layers.6.self_attn.rotary_emb.inv_freq": "model-00001-of-00003.safetensors",
282
+ "model.layers.6.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
283
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00003.safetensors",
284
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
285
+ "model.layers.7.mlp.ffn_layernorm.weight": "model-00001-of-00003.safetensors",
286
+ "model.layers.7.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
287
+ "model.layers.7.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
288
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
289
+ "model.layers.7.self_attn.inner_attn_ln.weight": "model-00001-of-00003.safetensors",
290
+ "model.layers.7.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
291
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
292
+ "model.layers.7.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
293
+ "model.layers.7.self_attn.rotary_emb.inv_freq": "model-00001-of-00003.safetensors",
294
+ "model.layers.7.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
295
+ "model.layers.8.input_layernorm.weight": "model-00001-of-00003.safetensors",
296
+ "model.layers.8.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
297
+ "model.layers.8.mlp.ffn_layernorm.weight": "model-00001-of-00003.safetensors",
298
+ "model.layers.8.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
299
+ "model.layers.8.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
300
+ "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
301
+ "model.layers.8.self_attn.inner_attn_ln.weight": "model-00001-of-00003.safetensors",
302
+ "model.layers.8.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
303
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
304
+ "model.layers.8.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
305
+ "model.layers.8.self_attn.rotary_emb.inv_freq": "model-00001-of-00003.safetensors",
306
+ "model.layers.8.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
307
+ "model.layers.9.input_layernorm.weight": "model-00002-of-00003.safetensors",
308
+ "model.layers.9.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
309
+ "model.layers.9.mlp.ffn_layernorm.weight": "model-00002-of-00003.safetensors",
310
+ "model.layers.9.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
311
+ "model.layers.9.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
312
+ "model.layers.9.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
313
+ "model.layers.9.self_attn.inner_attn_ln.weight": "model-00002-of-00003.safetensors",
314
+ "model.layers.9.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
315
+ "model.layers.9.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
316
+ "model.layers.9.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
317
+ "model.layers.9.self_attn.rotary_emb.inv_freq": "model-00002-of-00003.safetensors",
318
+ "model.layers.9.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
319
+ "model.norm.weight": "model-00003-of-00003.safetensors"
320
+ }
321
+ }
modeling_bitnet.py ADDED
@@ -0,0 +1,1387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """PyTorch LLaMA model."""
21
+
22
+ import math
23
+ import warnings
24
+ from typing import List, Optional, Tuple, Union
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ import torch.utils.checkpoint
29
+ from torch import nn
30
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
31
+
32
+ from transformers.activations import ACT2FN
33
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
34
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
35
+ from transformers.modeling_outputs import (
36
+ BaseModelOutputWithPast,
37
+ CausalLMOutputWithPast,
38
+ QuestionAnsweringModelOutput,
39
+ SequenceClassifierOutputWithPast,
40
+ )
41
+ from transformers.modeling_utils import PreTrainedModel
42
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
43
+ from transformers.utils import (
44
+ add_start_docstrings,
45
+ add_start_docstrings_to_model_forward,
46
+ is_flash_attn_2_available,
47
+ is_flash_attn_greater_or_equal_2_10,
48
+ logging,
49
+ replace_return_docstrings,
50
+ )
51
+ from .configuration_bitnet import BitnetConfig
52
+ from .utils_quant import BitLinear
53
+
54
+
55
+ if is_flash_attn_2_available():
56
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
57
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
58
+
59
+
60
+ logger = logging.get_logger(__name__)
61
+
62
+ _CONFIG_FOR_DOC = "BitnetConfig"
63
+
64
+
65
+ def _get_unpad_data(attention_mask):
66
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
67
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
68
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
69
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
70
+ return (
71
+ indices,
72
+ cu_seqlens,
73
+ max_seqlen_in_batch,
74
+ )
75
+
76
+
77
+ class BitnetRMSNorm(nn.Module):
78
+ def __init__(self, hidden_size, eps=1e-6):
79
+ """
80
+ BitnetRMSNorm is equivalent to T5LayerNorm
81
+ """
82
+ super().__init__()
83
+ self.weight = nn.Parameter(torch.ones(hidden_size))
84
+ self.variance_epsilon = eps
85
+
86
+ def forward(self, hidden_states):
87
+ input_dtype = hidden_states.dtype
88
+ hidden_states = hidden_states.to(torch.float32)
89
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
90
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
91
+ return self.weight * hidden_states.to(input_dtype)
92
+
93
+
94
+ ALL_LAYERNORM_LAYERS.append(BitnetRMSNorm)
95
+
96
+
97
+ class BitnetRotaryEmbedding(nn.Module):
98
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
99
+ super().__init__()
100
+ self.scaling_factor = scaling_factor
101
+ self.dim = dim
102
+ self.max_position_embeddings = max_position_embeddings
103
+ self.base = base
104
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
105
+ self.register_buffer("inv_freq", inv_freq)
106
+ # For BC we register cos and sin cached
107
+ self.max_seq_len_cached = max_position_embeddings
108
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
109
+ t = t / self.scaling_factor
110
+ freqs = torch.outer(t, self.inv_freq)
111
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
112
+ emb = torch.cat((freqs, freqs), dim=-1)
113
+ self.register_buffer("_cos_cached", emb.cos().to(torch.get_default_dtype()), persistent=False)
114
+ self.register_buffer("_sin_cached", emb.sin().to(torch.get_default_dtype()), persistent=False)
115
+
116
+ @property
117
+ def sin_cached(self):
118
+ logger.warning_once(
119
+ "The sin_cached attribute will be removed in 4.39. Bear in mind that its contents changed in v4.38. Use "
120
+ "the forward method of RoPE from now on instead. It is not used in the `BitnetAttention` class"
121
+ )
122
+ return self._sin_cached
123
+
124
+ @property
125
+ def cos_cached(self):
126
+ logger.warning_once(
127
+ "The cos_cached attribute will be removed in 4.39. Bear in mind that its contents changed in v4.38. Use "
128
+ "the forward method of RoPE from now on instead. It is not used in the `BitnetAttention` class"
129
+ )
130
+ return self._cos_cached
131
+
132
+ @torch.no_grad()
133
+ def forward(self, x, position_ids):
134
+ # x: [bs, num_attention_heads, seq_len, head_size]
135
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
136
+ position_ids_expanded = position_ids[:, None, :].float()
137
+ # Force float32 since bfloat16 loses precision on long contexts
138
+ # See https://github.com/huggingface/transformers/pull/29285
139
+ device_type = x.device.type
140
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
141
+ with torch.autocast(device_type=device_type, enabled=False):
142
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
143
+ emb = torch.cat((freqs, freqs), dim=-1)
144
+ cos = emb.cos()
145
+ sin = emb.sin()
146
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
147
+
148
+
149
+ def rotate_half(x):
150
+ """Rotates half the hidden dims of the input."""
151
+ x1 = x[..., : x.shape[-1] // 2]
152
+ x2 = x[..., x.shape[-1] // 2 :]
153
+ return torch.cat((-x2, x1), dim=-1)
154
+
155
+
156
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
157
+ """Applies Rotary Position Embedding to the query and key tensors.
158
+
159
+ Args:
160
+ q (`torch.Tensor`): The query tensor.
161
+ k (`torch.Tensor`): The key tensor.
162
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
163
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
164
+ position_ids (`torch.Tensor`, *optional*):
165
+ Deprecated and unused.
166
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
167
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
168
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
169
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
170
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
171
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
172
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
173
+ Returns:
174
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
175
+ """
176
+ cos = cos.unsqueeze(unsqueeze_dim)
177
+ sin = sin.unsqueeze(unsqueeze_dim)
178
+ q_embed = (q * cos) + (rotate_half(q) * sin)
179
+ k_embed = (k * cos) + (rotate_half(k) * sin)
180
+ return q_embed, k_embed
181
+
182
+
183
+ class BitnetMLP(nn.Module):
184
+ def __init__(self, config):
185
+ super().__init__()
186
+ self.config = config
187
+ self.hidden_size = config.hidden_size
188
+ self.intermediate_size = config.intermediate_size
189
+ self.gate_proj = BitLinear(
190
+ self.hidden_size, self.intermediate_size, bias=False,
191
+ weight_bits=config.weight_bits, input_bits=config.input_bits,
192
+ )
193
+ self.up_proj = BitLinear(
194
+ self.hidden_size, self.intermediate_size, bias=False,
195
+ weight_bits=config.weight_bits, input_bits=config.input_bits,
196
+ )
197
+ self.down_proj = BitLinear(
198
+ self.intermediate_size, self.hidden_size, bias=False,
199
+ weight_bits=config.weight_bits, input_bits=config.input_bits,
200
+ )
201
+ self.act_fn = ACT2FN[config.hidden_act]
202
+ self.ffn_layernorm = BitnetRMSNorm(self.intermediate_size, eps=config.rms_norm_eps)
203
+
204
+ def forward(self, x):
205
+ x = self.act_fn(self.gate_proj(x)) * self.up_proj(x)
206
+ x = self.ffn_layernorm(x)
207
+ x = self.down_proj(x)
208
+ return x
209
+
210
+
211
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
212
+ """
213
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
214
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
215
+ """
216
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
217
+ if n_rep == 1:
218
+ return hidden_states
219
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
220
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
221
+
222
+
223
+ class BitnetAttention(nn.Module):
224
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
225
+
226
+ def __init__(self, config: BitnetConfig, layer_idx: Optional[int] = None):
227
+ super().__init__()
228
+ self.config = config
229
+ self.layer_idx = layer_idx
230
+ if layer_idx is None:
231
+ logger.warning_once(
232
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
233
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
234
+ "when creating this class."
235
+ )
236
+
237
+ self.attention_dropout = config.attention_dropout
238
+ self.hidden_size = config.hidden_size
239
+ self.num_heads = config.num_attention_heads
240
+ self.head_dim = self.hidden_size // self.num_heads
241
+ self.num_key_value_heads = config.num_key_value_heads
242
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
243
+ self.max_position_embeddings = config.max_position_embeddings
244
+ self.rope_theta = config.rope_theta
245
+ self.is_causal = True
246
+
247
+ if (self.head_dim * self.num_heads) != self.hidden_size:
248
+ raise ValueError(
249
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
250
+ f" and `num_heads`: {self.num_heads})."
251
+ )
252
+
253
+ self.q_proj = BitLinear(
254
+ self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias,
255
+ weight_bits=config.weight_bits, input_bits=config.input_bits,
256
+ )
257
+ self.k_proj = BitLinear(
258
+ self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias,
259
+ weight_bits=config.weight_bits, input_bits=config.input_bits,
260
+ )
261
+ self.v_proj = BitLinear(
262
+ self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias,
263
+ weight_bits=config.weight_bits, input_bits=config.input_bits,
264
+ )
265
+ self.o_proj = BitLinear(
266
+ self.hidden_size, self.hidden_size, bias=config.attention_bias,
267
+ weight_bits=config.weight_bits, input_bits=config.input_bits,
268
+ )
269
+ self._init_rope()
270
+ self.inner_attn_ln = BitnetRMSNorm(self.hidden_size, eps=config.rms_norm_eps)
271
+
272
+ def _init_rope(self):
273
+ if self.config.rope_scaling is None:
274
+ self.rotary_emb = BitnetRotaryEmbedding(
275
+ self.head_dim,
276
+ max_position_embeddings=self.max_position_embeddings,
277
+ base=self.rope_theta,
278
+ )
279
+ else:
280
+ raise NotImplementedError
281
+
282
+ def forward(
283
+ self,
284
+ hidden_states: torch.Tensor,
285
+ attention_mask: Optional[torch.Tensor] = None,
286
+ position_ids: Optional[torch.LongTensor] = None,
287
+ past_key_value: Optional[Cache] = None,
288
+ output_attentions: bool = False,
289
+ use_cache: bool = False,
290
+ cache_position: Optional[torch.LongTensor] = None,
291
+ **kwargs,
292
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
293
+ bsz, q_len, _ = hidden_states.size()
294
+
295
+ query_states = self.q_proj(hidden_states)
296
+ key_states = self.k_proj(hidden_states)
297
+ value_states = self.v_proj(hidden_states)
298
+
299
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
300
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
301
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
302
+
303
+ past_key_value = getattr(self, "past_key_value", past_key_value)
304
+ cos, sin = self.rotary_emb(value_states, position_ids)
305
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
306
+
307
+ if past_key_value is not None:
308
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
309
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
310
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
311
+
312
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
313
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
314
+
315
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
316
+
317
+ if attention_mask is not None: # no matter the length, we just slice it
318
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
319
+ attn_weights = attn_weights + causal_mask
320
+
321
+ # upcast attention to fp32
322
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
323
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
324
+ attn_output = torch.matmul(attn_weights, value_states)
325
+
326
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
327
+ raise ValueError(
328
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
329
+ f" {attn_output.size()}"
330
+ )
331
+
332
+ attn_output = attn_output.transpose(1, 2).contiguous()
333
+
334
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
335
+
336
+ attn_output = self.inner_attn_ln(attn_output)
337
+ attn_output = self.o_proj(attn_output)
338
+
339
+ if not output_attentions:
340
+ attn_weights = None
341
+
342
+ return attn_output, attn_weights, past_key_value
343
+
344
+
345
+ class BitnetFlashAttention2(BitnetAttention):
346
+ """
347
+ Bitnet flash attention module. This module inherits from `BitnetAttention` as the weights of the module stays
348
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
349
+ flash attention and deal with padding tokens in case the input contains any of them.
350
+ """
351
+
352
+ def __init__(self, *args, **kwargs):
353
+ super().__init__(*args, **kwargs)
354
+
355
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
356
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
357
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
358
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
359
+
360
+ def forward(
361
+ self,
362
+ hidden_states: torch.Tensor,
363
+ attention_mask: Optional[torch.LongTensor] = None,
364
+ position_ids: Optional[torch.LongTensor] = None,
365
+ past_key_value: Optional[Cache] = None,
366
+ output_attentions: bool = False,
367
+ use_cache: bool = False,
368
+ cache_position: Optional[torch.LongTensor] = None,
369
+ **kwargs,
370
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
371
+ output_attentions = False
372
+
373
+ bsz, q_len, _ = hidden_states.size()
374
+
375
+ query_states = self.q_proj(hidden_states)
376
+ key_states = self.k_proj(hidden_states)
377
+ value_states = self.v_proj(hidden_states)
378
+
379
+ # Flash attention requires the input to have the shape
380
+ # batch_size x seq_length x head_dim x hidden_dim
381
+ # therefore we just need to keep the original shape
382
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
383
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
384
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
385
+
386
+ cos, sin = self.rotary_emb(value_states, position_ids)
387
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
388
+
389
+ past_key_value = getattr(self, "past_key_value", past_key_value)
390
+
391
+ if past_key_value is not None:
392
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
393
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
394
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
395
+
396
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
397
+ # to be able to avoid many of these transpose/reshape/view.
398
+ query_states = query_states.transpose(1, 2)
399
+ key_states = key_states.transpose(1, 2)
400
+ value_states = value_states.transpose(1, 2)
401
+
402
+ dropout_rate = self.attention_dropout if self.training else 0.0
403
+
404
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
405
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
406
+ # cast them back in the correct dtype just to be sure everything works as expected.
407
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
408
+ # in fp32. (BitnetRMSNorm handles it correctly)
409
+
410
+ input_dtype = query_states.dtype
411
+ if input_dtype == torch.float32:
412
+ if torch.is_autocast_enabled():
413
+ target_dtype = torch.get_autocast_gpu_dtype()
414
+ # Handle the case where the model is quantized
415
+ elif hasattr(self.config, "_pre_quantization_dtype"):
416
+ target_dtype = self.config._pre_quantization_dtype
417
+ else:
418
+ target_dtype = self.q_proj.weight.dtype
419
+
420
+ logger.warning_once(
421
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
422
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
423
+ f" {target_dtype}."
424
+ )
425
+
426
+ query_states = query_states.to(target_dtype)
427
+ key_states = key_states.to(target_dtype)
428
+ value_states = value_states.to(target_dtype)
429
+
430
+ attn_output = self._flash_attention_forward(
431
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
432
+ )
433
+
434
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
435
+ attn_output = self.inner_attn_ln(attn_output)
436
+ attn_output = self.o_proj(attn_output)
437
+
438
+ if not output_attentions:
439
+ attn_weights = None
440
+
441
+ return attn_output, attn_weights, past_key_value
442
+
443
+ def _flash_attention_forward(
444
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
445
+ ):
446
+ """
447
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
448
+ first unpad the input, then computes the attention scores and pad the final attention scores.
449
+
450
+ Args:
451
+ query_states (`torch.Tensor`):
452
+ Input query states to be passed to Flash Attention API
453
+ key_states (`torch.Tensor`):
454
+ Input key states to be passed to Flash Attention API
455
+ value_states (`torch.Tensor`):
456
+ Input value states to be passed to Flash Attention API
457
+ attention_mask (`torch.Tensor`):
458
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
459
+ position of padding tokens and 1 for the position of non-padding tokens.
460
+ dropout (`float`):
461
+ Attention dropout
462
+ softmax_scale (`float`, *optional*):
463
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
464
+ """
465
+ if not self._flash_attn_uses_top_left_mask:
466
+ causal = self.is_causal
467
+ else:
468
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in BitnetFlashAttention2 __init__.
469
+ causal = self.is_causal and query_length != 1
470
+
471
+ # Contains at least one padding token in the sequence
472
+ if attention_mask is not None:
473
+ batch_size = query_states.shape[0]
474
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
475
+ query_states, key_states, value_states, attention_mask, query_length
476
+ )
477
+
478
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
479
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
480
+
481
+ attn_output_unpad = flash_attn_varlen_func(
482
+ query_states,
483
+ key_states,
484
+ value_states,
485
+ cu_seqlens_q=cu_seqlens_q,
486
+ cu_seqlens_k=cu_seqlens_k,
487
+ max_seqlen_q=max_seqlen_in_batch_q,
488
+ max_seqlen_k=max_seqlen_in_batch_k,
489
+ dropout_p=dropout,
490
+ softmax_scale=softmax_scale,
491
+ causal=causal,
492
+ )
493
+
494
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
495
+ else:
496
+ attn_output = flash_attn_func(
497
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
498
+ )
499
+
500
+ return attn_output
501
+
502
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
503
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
504
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
505
+
506
+ key_layer = index_first_axis(
507
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
508
+ )
509
+ value_layer = index_first_axis(
510
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
511
+ )
512
+ if query_length == kv_seq_len:
513
+ query_layer = index_first_axis(
514
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
515
+ )
516
+ cu_seqlens_q = cu_seqlens_k
517
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
518
+ indices_q = indices_k
519
+ elif query_length == 1:
520
+ max_seqlen_in_batch_q = 1
521
+ cu_seqlens_q = torch.arange(
522
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
523
+ ) # There is a memcpy here, that is very bad.
524
+ indices_q = cu_seqlens_q[:-1]
525
+ query_layer = query_layer.squeeze(1)
526
+ else:
527
+ # The -q_len: slice assumes left padding.
528
+ attention_mask = attention_mask[:, -query_length:]
529
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
530
+
531
+ return (
532
+ query_layer,
533
+ key_layer,
534
+ value_layer,
535
+ indices_q,
536
+ (cu_seqlens_q, cu_seqlens_k),
537
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
538
+ )
539
+
540
+
541
+
542
+ LLAMA_ATTENTION_CLASSES = {
543
+ "eager": BitnetAttention,
544
+ "flash_attention_2": BitnetFlashAttention2,
545
+ }
546
+
547
+
548
+ class BitnetDecoderLayer(nn.Module):
549
+ def __init__(self, config: BitnetConfig, layer_idx: int):
550
+ super().__init__()
551
+ self.hidden_size = config.hidden_size
552
+
553
+ self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
554
+
555
+ self.mlp = BitnetMLP(config)
556
+ self.input_layernorm = BitnetRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
557
+ self.post_attention_layernorm = BitnetRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
558
+
559
+ def forward(
560
+ self,
561
+ hidden_states: torch.Tensor,
562
+ attention_mask: Optional[torch.Tensor] = None,
563
+ position_ids: Optional[torch.LongTensor] = None,
564
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
565
+ output_attentions: Optional[bool] = False,
566
+ use_cache: Optional[bool] = False,
567
+ cache_position: Optional[torch.LongTensor] = None,
568
+ **kwargs,
569
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
570
+ """
571
+ Args:
572
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
573
+ attention_mask (`torch.FloatTensor`, *optional*):
574
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
575
+ query_sequence_length, key_sequence_length)` if default attention is used.
576
+ output_attentions (`bool`, *optional*):
577
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
578
+ returned tensors for more detail.
579
+ use_cache (`bool`, *optional*):
580
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
581
+ (see `past_key_values`).
582
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
583
+ """
584
+ if "padding_mask" in kwargs:
585
+ warnings.warn(
586
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
587
+ )
588
+
589
+ residual = hidden_states
590
+
591
+ hidden_states = self.input_layernorm(hidden_states)
592
+
593
+ # Self Attention
594
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
595
+ hidden_states=hidden_states,
596
+ attention_mask=attention_mask,
597
+ position_ids=position_ids,
598
+ past_key_value=past_key_value,
599
+ output_attentions=output_attentions,
600
+ use_cache=use_cache,
601
+ cache_position=cache_position,
602
+ **kwargs,
603
+ )
604
+ hidden_states = residual + hidden_states
605
+
606
+ # Fully Connected
607
+ residual = hidden_states
608
+ hidden_states = self.post_attention_layernorm(hidden_states)
609
+ hidden_states = self.mlp(hidden_states)
610
+ hidden_states = residual + hidden_states
611
+
612
+ outputs = (hidden_states,)
613
+
614
+ if output_attentions:
615
+ outputs += (self_attn_weights,)
616
+
617
+ if use_cache:
618
+ outputs += (present_key_value,)
619
+
620
+ return outputs
621
+
622
+
623
+ LLAMA_START_DOCSTRING = r"""
624
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
625
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
626
+ etc.)
627
+
628
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
629
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
630
+ and behavior.
631
+
632
+ Parameters:
633
+ config ([`BitnetConfig`]):
634
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
635
+ load the weights associated with the model, only the configuration. Check out the
636
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
637
+ """
638
+
639
+
640
+ @add_start_docstrings(
641
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
642
+ LLAMA_START_DOCSTRING,
643
+ )
644
+ class BitnetPreTrainedModel(PreTrainedModel):
645
+ config_class = BitnetConfig
646
+ base_model_prefix = "model"
647
+ supports_gradient_checkpointing = True
648
+ _no_split_modules = ["BitnetDecoderLayer"]
649
+ _skip_keys_device_placement = ["past_key_values"]
650
+ _supports_flash_attn_2 = True
651
+ _supports_sdpa = False
652
+ _supports_cache_class = True
653
+
654
+ def _init_weights(self, module):
655
+ std = self.config.initializer_range
656
+ if isinstance(module, nn.Linear):
657
+ module.weight.data.normal_(mean=0.0, std=std)
658
+ if module.bias is not None:
659
+ module.bias.data.zero_()
660
+ elif isinstance(module, nn.Embedding):
661
+ module.weight.data.normal_(mean=0.0, std=std)
662
+ if module.padding_idx is not None:
663
+ module.weight.data[module.padding_idx].zero_()
664
+
665
+ def _setup_cache(self, cache_cls, max_batch_size, max_cache_len: Optional[int] = None):
666
+ if self.config._attn_implementation == "flash_attention_2" and cache_cls == StaticCache:
667
+ raise ValueError(
668
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
669
+ "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
670
+ )
671
+
672
+ for layer in self.model.layers:
673
+ device = layer.input_layernorm.weight.device
674
+ if hasattr(self.config, "_pre_quantization_dtype"):
675
+ dtype = self.config._pre_quantization_dtype
676
+ else:
677
+ dtype = layer.self_attn.o_proj.weight.dtype
678
+ layer.self_attn.past_key_value = cache_cls(
679
+ self.config, max_batch_size, max_cache_len, device=device, dtype=dtype
680
+ )
681
+
682
+ def _reset_cache(self):
683
+ for layer in self.model.layers:
684
+ layer.self_attn.past_key_value = None
685
+
686
+
687
+ LLAMA_INPUTS_DOCSTRING = r"""
688
+ Args:
689
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
690
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
691
+ it.
692
+
693
+ Indices can be obtained using [`BitnetTokenizer`]. See [`PreTrainedTokenizer.encode`] and
694
+ [`PreTrainedTokenizer.__call__`] for details.
695
+
696
+ [What are input IDs?](../glossary#input-ids)
697
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
698
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
699
+
700
+ - 1 for tokens that are **not masked**,
701
+ - 0 for tokens that are **masked**.
702
+
703
+ [What are attention masks?](../glossary#attention-mask)
704
+
705
+ Indices can be obtained using [`BitnetTokenizer`]. See [`PreTrainedTokenizer.encode`] and
706
+ [`PreTrainedTokenizer.__call__`] for details.
707
+
708
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
709
+ `past_key_values`).
710
+
711
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
712
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
713
+ information on the default strategy.
714
+
715
+ - 1 indicates the head is **not masked**,
716
+ - 0 indicates the head is **masked**.
717
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
718
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
719
+ config.n_positions - 1]`.
720
+
721
+ [What are position IDs?](../glossary#position-ids)
722
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
723
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
724
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
725
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
726
+
727
+ Two formats are allowed:
728
+ - a [`~cache_utils.Cache`] instance;
729
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
730
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
731
+ cache format.
732
+
733
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
734
+ legacy cache format will be returned.
735
+
736
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
737
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
738
+ of shape `(batch_size, sequence_length)`.
739
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
740
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
741
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
742
+ model's internal embedding lookup matrix.
743
+ use_cache (`bool`, *optional*):
744
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
745
+ `past_key_values`).
746
+ output_attentions (`bool`, *optional*):
747
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
748
+ tensors for more detail.
749
+ output_hidden_states (`bool`, *optional*):
750
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
751
+ more detail.
752
+ return_dict (`bool`, *optional*):
753
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
754
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
755
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
756
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
757
+ the complete sequence length.
758
+ """
759
+
760
+
761
+ @add_start_docstrings(
762
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
763
+ LLAMA_START_DOCSTRING,
764
+ )
765
+ class BitnetModel(BitnetPreTrainedModel):
766
+ """
767
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`BitnetDecoderLayer`]
768
+
769
+ Args:
770
+ config: BitnetConfig
771
+ """
772
+
773
+ def __init__(self, config: BitnetConfig):
774
+ super().__init__(config)
775
+ self.padding_idx = config.pad_token_id
776
+ self.vocab_size = config.vocab_size
777
+
778
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
779
+ self.layers = nn.ModuleList(
780
+ [BitnetDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
781
+ )
782
+ self.norm = BitnetRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
783
+ self.gradient_checkpointing = False
784
+
785
+ # Initialize weights and apply final processing
786
+ self.post_init()
787
+
788
+ def get_input_embeddings(self):
789
+ return self.embed_tokens
790
+
791
+ def set_input_embeddings(self, value):
792
+ self.embed_tokens = value
793
+
794
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
795
+ def forward(
796
+ self,
797
+ input_ids: torch.LongTensor = None,
798
+ attention_mask: Optional[torch.Tensor] = None,
799
+ position_ids: Optional[torch.LongTensor] = None,
800
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
801
+ inputs_embeds: Optional[torch.FloatTensor] = None,
802
+ use_cache: Optional[bool] = None,
803
+ output_attentions: Optional[bool] = None,
804
+ output_hidden_states: Optional[bool] = None,
805
+ return_dict: Optional[bool] = None,
806
+ cache_position: Optional[torch.LongTensor] = None,
807
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
808
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
809
+ output_hidden_states = (
810
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
811
+ )
812
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
813
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
814
+
815
+ if (input_ids is None) ^ (inputs_embeds is not None):
816
+ raise ValueError(
817
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
818
+ )
819
+
820
+ if self.gradient_checkpointing and self.training and use_cache:
821
+ logger.warning_once(
822
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
823
+ )
824
+ use_cache = False
825
+
826
+ if inputs_embeds is None:
827
+ inputs_embeds = self.embed_tokens(input_ids)
828
+
829
+ past_seen_tokens = 0
830
+ if use_cache: # kept for BC (cache positions)
831
+ if not isinstance(past_key_values, StaticCache):
832
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
833
+ past_seen_tokens = past_key_values.get_seq_length()
834
+
835
+ if cache_position is None:
836
+ if isinstance(past_key_values, StaticCache):
837
+ raise ValueError("cache_position is a required argument when using StaticCache.")
838
+ cache_position = torch.arange(
839
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
840
+ )
841
+
842
+ if position_ids is None:
843
+ position_ids = cache_position.unsqueeze(0)
844
+
845
+ causal_mask = self._update_causal_mask(attention_mask, inputs_embeds, cache_position)
846
+
847
+ # embed positions
848
+ hidden_states = inputs_embeds
849
+
850
+ # decoder layers
851
+ all_hidden_states = () if output_hidden_states else None
852
+ all_self_attns = () if output_attentions else None
853
+ next_decoder_cache = None
854
+
855
+ for decoder_layer in self.layers:
856
+ if output_hidden_states:
857
+ all_hidden_states += (hidden_states,)
858
+
859
+ if self.gradient_checkpointing and self.training:
860
+ layer_outputs = self._gradient_checkpointing_func(
861
+ decoder_layer.__call__,
862
+ hidden_states,
863
+ causal_mask,
864
+ position_ids,
865
+ past_key_values,
866
+ output_attentions,
867
+ use_cache,
868
+ cache_position,
869
+ )
870
+ else:
871
+ layer_outputs = decoder_layer(
872
+ hidden_states,
873
+ attention_mask=causal_mask,
874
+ position_ids=position_ids,
875
+ past_key_value=past_key_values,
876
+ output_attentions=output_attentions,
877
+ use_cache=use_cache,
878
+ cache_position=cache_position,
879
+ )
880
+
881
+ hidden_states = layer_outputs[0]
882
+
883
+ if use_cache:
884
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
885
+
886
+ if output_attentions:
887
+ all_self_attns += (layer_outputs[1],)
888
+
889
+ hidden_states = self.norm(hidden_states)
890
+
891
+ # add hidden states from the last decoder layer
892
+ if output_hidden_states:
893
+ all_hidden_states += (hidden_states,)
894
+
895
+ next_cache = None
896
+ if use_cache:
897
+ next_cache = (
898
+ next_decoder_cache.to_legacy_cache() if isinstance(next_decoder_cache, Cache) else next_decoder_cache
899
+ )
900
+ if not return_dict:
901
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
902
+ return BaseModelOutputWithPast(
903
+ last_hidden_state=hidden_states,
904
+ past_key_values=next_cache,
905
+ hidden_states=all_hidden_states,
906
+ attentions=all_self_attns,
907
+ )
908
+
909
+ # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
910
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
911
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
912
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
913
+ def _update_causal_mask(self, attention_mask, input_tensor, cache_position):
914
+ if self.config._attn_implementation == "flash_attention_2":
915
+ if attention_mask is not None and 0.0 in attention_mask:
916
+ return attention_mask
917
+ return None
918
+
919
+ dtype, device = input_tensor.dtype, input_tensor.device
920
+ min_dtype = torch.finfo(dtype).min
921
+ sequence_length = input_tensor.shape[1]
922
+ if hasattr(self.layers[0].self_attn, "past_key_value"): # static cache
923
+ target_length = self.config.max_position_embeddings
924
+ else: # dynamic cache
925
+ target_length = (
926
+ attention_mask.shape[-1] if isinstance(attention_mask, torch.Tensor) else cache_position[-1] + 1
927
+ )
928
+
929
+ causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
930
+ if sequence_length != 1:
931
+ causal_mask = torch.triu(causal_mask, diagonal=1)
932
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
933
+ causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
934
+ if attention_mask is not None:
935
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
936
+ if attention_mask.dim() == 2:
937
+ mask_length = attention_mask.shape[-1]
938
+ padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[:, None, None, :].eq(0.0)
939
+ causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(padding_mask, min_dtype)
940
+ elif attention_mask.dim() == 4:
941
+ # backwards compatibility: we allow passing a 4D attention mask shorter than the input length with
942
+ # cache. In that case, the 4D attention mask attends to the newest tokens only.
943
+ if attention_mask.shape[-2] < cache_position[0] + sequence_length:
944
+ offset = cache_position[0]
945
+ else:
946
+ offset = 0
947
+ mask_shape = attention_mask.shape
948
+ mask_slice = (attention_mask.eq(0.0)).to(dtype=dtype) * min_dtype
949
+ causal_mask[
950
+ : mask_shape[0], : mask_shape[1], offset : mask_shape[2] + offset, : mask_shape[3]
951
+ ] = mask_slice
952
+
953
+ return causal_mask
954
+
955
+
956
+ class BitnetForCausalLM(BitnetPreTrainedModel):
957
+ _tied_weights_keys = ["lm_head.weight"]
958
+
959
+ def __init__(self, config):
960
+ super().__init__(config)
961
+ self.model = BitnetModel(config)
962
+ self.vocab_size = config.vocab_size
963
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
964
+
965
+ # Initialize weights and apply final processing
966
+ self.post_init()
967
+
968
+ def get_input_embeddings(self):
969
+ return self.model.embed_tokens
970
+
971
+ def set_input_embeddings(self, value):
972
+ self.model.embed_tokens = value
973
+
974
+ def get_output_embeddings(self):
975
+ return self.lm_head
976
+
977
+ def set_output_embeddings(self, new_embeddings):
978
+ self.lm_head = new_embeddings
979
+
980
+ def set_decoder(self, decoder):
981
+ self.model = decoder
982
+
983
+ def get_decoder(self):
984
+ return self.model
985
+
986
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
987
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
988
+ def forward(
989
+ self,
990
+ input_ids: torch.LongTensor = None,
991
+ attention_mask: Optional[torch.Tensor] = None,
992
+ position_ids: Optional[torch.LongTensor] = None,
993
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
994
+ inputs_embeds: Optional[torch.FloatTensor] = None,
995
+ labels: Optional[torch.LongTensor] = None,
996
+ use_cache: Optional[bool] = None,
997
+ output_attentions: Optional[bool] = None,
998
+ output_hidden_states: Optional[bool] = None,
999
+ return_dict: Optional[bool] = None,
1000
+ cache_position: Optional[torch.LongTensor] = None,
1001
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1002
+ r"""
1003
+ Args:
1004
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1005
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1006
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1007
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1008
+
1009
+ Returns:
1010
+
1011
+ Example:
1012
+
1013
+ ```python
1014
+ >>> from transformers import LlamaTokenizer, LlamaForCausalLM
1015
+
1016
+ >>> model = LlamaForCausalLM.from_pretrained("meta-llama/Bitnet-2-7b-hf")
1017
+ >>> tokenizer = LlamaTokenizer.from_pretrained("meta-llama/Bitnet-2-7b-hf")
1018
+
1019
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1020
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1021
+
1022
+ >>> # Generate
1023
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1024
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1025
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1026
+ ```"""
1027
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1028
+ output_hidden_states = (
1029
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1030
+ )
1031
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1032
+
1033
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1034
+ outputs = self.model(
1035
+ input_ids=input_ids,
1036
+ attention_mask=attention_mask,
1037
+ position_ids=position_ids,
1038
+ past_key_values=past_key_values,
1039
+ inputs_embeds=inputs_embeds,
1040
+ use_cache=use_cache,
1041
+ output_attentions=output_attentions,
1042
+ output_hidden_states=output_hidden_states,
1043
+ return_dict=return_dict,
1044
+ cache_position=cache_position,
1045
+ )
1046
+
1047
+ hidden_states = outputs[0]
1048
+ logits = self.lm_head(hidden_states)
1049
+ logits = logits.float()
1050
+
1051
+ loss = None
1052
+ if labels is not None:
1053
+ # Shift so that tokens < n predict n
1054
+ shift_logits = logits[..., :-1, :].contiguous()
1055
+ shift_labels = labels[..., 1:].contiguous()
1056
+ # Flatten the tokens
1057
+ loss_fct = CrossEntropyLoss()
1058
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1059
+ shift_labels = shift_labels.view(-1)
1060
+ # Enable model parallelism
1061
+ shift_labels = shift_labels.to(shift_logits.device)
1062
+ loss = loss_fct(shift_logits, shift_labels)
1063
+
1064
+ if not return_dict:
1065
+ output = (logits,) + outputs[1:]
1066
+ return (loss,) + output if loss is not None else output
1067
+
1068
+ return CausalLMOutputWithPast(
1069
+ loss=loss,
1070
+ logits=logits,
1071
+ past_key_values=outputs.past_key_values,
1072
+ hidden_states=outputs.hidden_states,
1073
+ attentions=outputs.attentions,
1074
+ )
1075
+
1076
+ def prepare_inputs_for_generation(
1077
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, cache_position=None, **kwargs
1078
+ ):
1079
+ # With static cache, the `past_key_values` is None
1080
+ # TODO joao: standardize interface for the different Cache classes and remove of this if
1081
+ has_static_cache = False
1082
+ if past_key_values is None:
1083
+ past_key_values = getattr(self.model.layers[0].self_attn, "past_key_value", None)
1084
+ has_static_cache = past_key_values is not None
1085
+
1086
+ past_length = 0
1087
+ if past_key_values is not None:
1088
+ if isinstance(past_key_values, Cache):
1089
+ past_length = cache_position[0] if cache_position is not None else past_key_values.get_seq_length()
1090
+ max_cache_length = (
1091
+ torch.tensor(past_key_values.get_max_length(), device=input_ids.device)
1092
+ if past_key_values.get_max_length() is not None
1093
+ else None
1094
+ )
1095
+ cache_length = past_length if max_cache_length is None else torch.min(max_cache_length, past_length)
1096
+ # TODO joao: remove this `else` after `generate` prioritizes `Cache` objects
1097
+ else:
1098
+ cache_length = past_length = past_key_values[0][0].shape[2]
1099
+ max_cache_length = None
1100
+
1101
+ # Keep only the unprocessed tokens:
1102
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1103
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1104
+ # input)
1105
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1106
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1107
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1108
+ # input_ids based on the past_length.
1109
+ elif past_length < input_ids.shape[1]:
1110
+ input_ids = input_ids[:, past_length:]
1111
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1112
+
1113
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1114
+ if (
1115
+ max_cache_length is not None
1116
+ and attention_mask is not None
1117
+ and cache_length + input_ids.shape[1] > max_cache_length
1118
+ ):
1119
+ attention_mask = attention_mask[:, -max_cache_length:]
1120
+
1121
+ position_ids = kwargs.get("position_ids", None)
1122
+ if attention_mask is not None and position_ids is None:
1123
+ # create position_ids on the fly for batch generation
1124
+ position_ids = attention_mask.long().cumsum(-1) - 1
1125
+ position_ids.masked_fill_(attention_mask == 0, 1)
1126
+ if past_key_values:
1127
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1128
+
1129
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1130
+ if inputs_embeds is not None and past_key_values is None:
1131
+ model_inputs = {"inputs_embeds": inputs_embeds}
1132
+ else:
1133
+ # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
1134
+ # recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
1135
+ # TODO: use `next_tokens` directly instead.
1136
+ model_inputs = {"input_ids": input_ids.contiguous()}
1137
+
1138
+ input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
1139
+ if cache_position is None:
1140
+ cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
1141
+ else:
1142
+ cache_position = cache_position[-input_length:]
1143
+
1144
+ if has_static_cache:
1145
+ past_key_values = None
1146
+
1147
+ model_inputs.update(
1148
+ {
1149
+ "position_ids": position_ids,
1150
+ "cache_position": cache_position,
1151
+ "past_key_values": past_key_values,
1152
+ "use_cache": kwargs.get("use_cache"),
1153
+ "attention_mask": attention_mask,
1154
+ }
1155
+ )
1156
+ return model_inputs
1157
+
1158
+ @staticmethod
1159
+ def _reorder_cache(past_key_values, beam_idx):
1160
+ reordered_past = ()
1161
+ for layer_past in past_key_values:
1162
+ reordered_past += (
1163
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1164
+ )
1165
+ return reordered_past
1166
+
1167
+
1168
+ @add_start_docstrings(
1169
+ """
1170
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
1171
+
1172
+ [`BitnetForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1173
+ (e.g. GPT-2) do.
1174
+
1175
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1176
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1177
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1178
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1179
+ each row of the batch).
1180
+ """,
1181
+ LLAMA_START_DOCSTRING,
1182
+ )
1183
+ class BitnetForSequenceClassification(BitnetPreTrainedModel):
1184
+ def __init__(self, config):
1185
+ super().__init__(config)
1186
+ self.num_labels = config.num_labels
1187
+ self.model = BitnetModel(config)
1188
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1189
+
1190
+ # Initialize weights and apply final processing
1191
+ self.post_init()
1192
+
1193
+ def get_input_embeddings(self):
1194
+ return self.model.embed_tokens
1195
+
1196
+ def set_input_embeddings(self, value):
1197
+ self.model.embed_tokens = value
1198
+
1199
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1200
+ def forward(
1201
+ self,
1202
+ input_ids: torch.LongTensor = None,
1203
+ attention_mask: Optional[torch.Tensor] = None,
1204
+ position_ids: Optional[torch.LongTensor] = None,
1205
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1206
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1207
+ labels: Optional[torch.LongTensor] = None,
1208
+ use_cache: Optional[bool] = None,
1209
+ output_attentions: Optional[bool] = None,
1210
+ output_hidden_states: Optional[bool] = None,
1211
+ return_dict: Optional[bool] = None,
1212
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1213
+ r"""
1214
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1215
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1216
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1217
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1218
+ """
1219
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1220
+
1221
+ transformer_outputs = self.model(
1222
+ input_ids,
1223
+ attention_mask=attention_mask,
1224
+ position_ids=position_ids,
1225
+ past_key_values=past_key_values,
1226
+ inputs_embeds=inputs_embeds,
1227
+ use_cache=use_cache,
1228
+ output_attentions=output_attentions,
1229
+ output_hidden_states=output_hidden_states,
1230
+ return_dict=return_dict,
1231
+ )
1232
+ hidden_states = transformer_outputs[0]
1233
+ logits = self.score(hidden_states)
1234
+
1235
+ if input_ids is not None:
1236
+ batch_size = input_ids.shape[0]
1237
+ else:
1238
+ batch_size = inputs_embeds.shape[0]
1239
+
1240
+ if self.config.pad_token_id is None and batch_size != 1:
1241
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1242
+ if self.config.pad_token_id is None:
1243
+ sequence_lengths = -1
1244
+ else:
1245
+ if input_ids is not None:
1246
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1247
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1248
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1249
+ sequence_lengths = sequence_lengths.to(logits.device)
1250
+ else:
1251
+ sequence_lengths = -1
1252
+
1253
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1254
+
1255
+ loss = None
1256
+ if labels is not None:
1257
+ labels = labels.to(logits.device)
1258
+ if self.config.problem_type is None:
1259
+ if self.num_labels == 1:
1260
+ self.config.problem_type = "regression"
1261
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1262
+ self.config.problem_type = "single_label_classification"
1263
+ else:
1264
+ self.config.problem_type = "multi_label_classification"
1265
+
1266
+ if self.config.problem_type == "regression":
1267
+ loss_fct = MSELoss()
1268
+ if self.num_labels == 1:
1269
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1270
+ else:
1271
+ loss = loss_fct(pooled_logits, labels)
1272
+ elif self.config.problem_type == "single_label_classification":
1273
+ loss_fct = CrossEntropyLoss()
1274
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1275
+ elif self.config.problem_type == "multi_label_classification":
1276
+ loss_fct = BCEWithLogitsLoss()
1277
+ loss = loss_fct(pooled_logits, labels)
1278
+ if not return_dict:
1279
+ output = (pooled_logits,) + transformer_outputs[1:]
1280
+ return ((loss,) + output) if loss is not None else output
1281
+
1282
+ return SequenceClassifierOutputWithPast(
1283
+ loss=loss,
1284
+ logits=pooled_logits,
1285
+ past_key_values=transformer_outputs.past_key_values,
1286
+ hidden_states=transformer_outputs.hidden_states,
1287
+ attentions=transformer_outputs.attentions,
1288
+ )
1289
+
1290
+
1291
+ @add_start_docstrings(
1292
+ """
1293
+ The Bitnet Model transformer with a span classification head on top for extractive question-answering tasks like
1294
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1295
+ """,
1296
+ LLAMA_START_DOCSTRING,
1297
+ )
1298
+ class BitnetForQuestionAnswering(BitnetPreTrainedModel):
1299
+ base_model_prefix = "transformer"
1300
+
1301
+ # Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->Bitnet
1302
+ def __init__(self, config):
1303
+ super().__init__(config)
1304
+ self.transformer = BitnetModel(config)
1305
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1306
+
1307
+ # Initialize weights and apply final processing
1308
+ self.post_init()
1309
+
1310
+ def get_input_embeddings(self):
1311
+ return self.transformer.embed_tokens
1312
+
1313
+ def set_input_embeddings(self, value):
1314
+ self.transformer.embed_tokens = value
1315
+
1316
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1317
+ def forward(
1318
+ self,
1319
+ input_ids: Optional[torch.LongTensor] = None,
1320
+ attention_mask: Optional[torch.FloatTensor] = None,
1321
+ position_ids: Optional[torch.LongTensor] = None,
1322
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1323
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1324
+ start_positions: Optional[torch.LongTensor] = None,
1325
+ end_positions: Optional[torch.LongTensor] = None,
1326
+ output_attentions: Optional[bool] = None,
1327
+ output_hidden_states: Optional[bool] = None,
1328
+ return_dict: Optional[bool] = None,
1329
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1330
+ r"""
1331
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1332
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1333
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1334
+ are not taken into account for computing the loss.
1335
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1336
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1337
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1338
+ are not taken into account for computing the loss.
1339
+ """
1340
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1341
+
1342
+ outputs = self.transformer(
1343
+ input_ids,
1344
+ attention_mask=attention_mask,
1345
+ position_ids=position_ids,
1346
+ past_key_values=past_key_values,
1347
+ inputs_embeds=inputs_embeds,
1348
+ output_attentions=output_attentions,
1349
+ output_hidden_states=output_hidden_states,
1350
+ return_dict=return_dict,
1351
+ )
1352
+
1353
+ sequence_output = outputs[0]
1354
+
1355
+ logits = self.qa_outputs(sequence_output)
1356
+ start_logits, end_logits = logits.split(1, dim=-1)
1357
+ start_logits = start_logits.squeeze(-1).contiguous()
1358
+ end_logits = end_logits.squeeze(-1).contiguous()
1359
+
1360
+ total_loss = None
1361
+ if start_positions is not None and end_positions is not None:
1362
+ # If we are on multi-GPU, split add a dimension
1363
+ if len(start_positions.size()) > 1:
1364
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1365
+ if len(end_positions.size()) > 1:
1366
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1367
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1368
+ ignored_index = start_logits.size(1)
1369
+ start_positions = start_positions.clamp(0, ignored_index)
1370
+ end_positions = end_positions.clamp(0, ignored_index)
1371
+
1372
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1373
+ start_loss = loss_fct(start_logits, start_positions)
1374
+ end_loss = loss_fct(end_logits, end_positions)
1375
+ total_loss = (start_loss + end_loss) / 2
1376
+
1377
+ if not return_dict:
1378
+ output = (start_logits, end_logits) + outputs[2:]
1379
+ return ((total_loss,) + output) if total_loss is not None else output
1380
+
1381
+ return QuestionAnsweringModelOutput(
1382
+ loss=total_loss,
1383
+ start_logits=start_logits,
1384
+ end_logits=end_logits,
1385
+ hidden_states=outputs.hidden_states,
1386
+ attentions=outputs.attentions,
1387
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "</line>"
4
+ ],
5
+ "bos_token": {
6
+ "content": "<s>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "eos_token": {
13
+ "content": "</s>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false
18
+ },
19
+ "pad_token": {
20
+ "content": "<pad>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false
25
+ },
26
+ "unk_token": {
27
+ "content": "<unk>",
28
+ "lstrip": false,
29
+ "normalized": false,
30
+ "rstrip": false,
31
+ "single_word": false
32
+ }
33
+ }
tokenization_bitnet.py ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ """Tokenization classes for LLaMA."""
22
+ import os
23
+ from shutil import copyfile
24
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
25
+
26
+ import sentencepiece as spm
27
+
28
+ from transformers.convert_slow_tokenizer import import_protobuf
29
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
30
+ from transformers.utils import logging
31
+
32
+
33
+ if TYPE_CHECKING:
34
+ from transformers.tokenization_utils_base import TextInput
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
39
+
40
+ PRETRAINED_VOCAB_FILES_MAP = {
41
+ "vocab_file": {
42
+ "hf-internal-testing/llama-tokenizer": "https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer.model",
43
+ },
44
+ "tokenizer_file": {
45
+ "hf-internal-testing/llama-tokenizer": "https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer_config.json",
46
+ },
47
+ }
48
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
49
+ "hf-internal-testing/llama-tokenizer": 2048,
50
+ }
51
+ SPIECE_UNDERLINE = "▁"
52
+
53
+ B_INST, E_INST = "[INST]", "[/INST]"
54
+ B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
55
+
56
+ # fmt: off
57
+ DEFAULT_SYSTEM_PROMPT = """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your \
58
+ answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
59
+ that your responses are socially unbiased and positive in nature.
60
+
61
+ If a question does not make any sense, or is not factually coherent, explain why instead of answering something not \
62
+ correct. If you don't know the answer to a question, please don't share false information."""
63
+ # fmt: on
64
+
65
+
66
+ class BitnetTokenizer(PreTrainedTokenizer):
67
+ """
68
+ Construct a Bitnet tokenizer. Based on byte-level Byte-Pair-Encoding. The default padding token is unset as there is
69
+ no padding token in the original model.
70
+
71
+ Args:
72
+ vocab_file (`str`):
73
+ Path to the vocabulary file.
74
+ unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<unk>"`):
75
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
76
+ token instead.
77
+ bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<s>"`):
78
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
79
+ eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"</s>"`):
80
+ The end of sequence token.
81
+ pad_token (`str` or `tokenizers.AddedToken`, *optional*):
82
+ A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by
83
+ attention mechanisms or loss computation.
84
+ sp_model_kwargs (`Dict[str, Any]`, `Optional`, *optional*):
85
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
86
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
87
+ to set:
88
+
89
+ - `enable_sampling`: Enable subword regularization.
90
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
91
+
92
+ - `nbest_size = {0,1}`: No sampling is performed.
93
+ - `nbest_size > 1`: samples from the nbest_size results.
94
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
95
+ using forward-filtering-and-backward-sampling algorithm.
96
+
97
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
98
+ BPE-dropout.
99
+
100
+ add_bos_token (`bool`, *optional*, defaults to `True`):
101
+ Whether or not to add an `bos_token` at the start of sequences.
102
+ add_eos_token (`bool`, *optional*, defaults to `False`):
103
+ Whether or not to add an `eos_token` at the end of sequences.
104
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
105
+ Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
106
+ extra spaces.
107
+ use_default_system_prompt (`bool`, *optional*, defaults to `False`):
108
+ Whether or not the default system prompt for Bitnet should be used.
109
+ spaces_between_special_tokens (`bool`, *optional*, defaults to `False`):
110
+ Whether or not to add spaces between special tokens.
111
+ legacy (`bool`, *optional*):
112
+ Whether or not the `legacy` behavior of the tokenizer should be used. Legacy is before the merge of #24622
113
+ and #25224 which includes fixes to properly handle tokens that appear after special tokens. A simple
114
+ example:
115
+
116
+ - `legacy=True`:
117
+ ```python
118
+ >>> from transformers import T5Tokenizer
119
+
120
+ >>> tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-base", legacy=True)
121
+ >>> tokenizer.encode("Hello <extra_id_0>.")
122
+ [8774, 32099, 3, 5, 1]
123
+ ```
124
+ - `legacy=False`:
125
+ ```python
126
+ >>> from transformers import T5Tokenizer
127
+
128
+ >>> tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-base", legacy=False)
129
+ >>> tokenizer.encode("Hello <extra_id_0>.") # the extra space `[3]` is no longer here
130
+ [8774, 32099, 5, 1]
131
+ ```
132
+ Checkout the [pull request](https://github.com/huggingface/transformers/pull/24565) for more details.
133
+ add_prefix_space (`bool`, *optional*, defaults to `True`):
134
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
135
+ other word.
136
+
137
+ """
138
+
139
+ vocab_files_names = VOCAB_FILES_NAMES
140
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
141
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
142
+ model_input_names = ["input_ids", "attention_mask"]
143
+
144
+ def __init__(
145
+ self,
146
+ vocab_file,
147
+ unk_token="<unk>",
148
+ bos_token="<s>",
149
+ eos_token="</s>",
150
+ pad_token=None,
151
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
152
+ add_bos_token=True,
153
+ add_eos_token=False,
154
+ clean_up_tokenization_spaces=False,
155
+ use_default_system_prompt=False,
156
+ spaces_between_special_tokens=False,
157
+ legacy=None,
158
+ add_prefix_space=True,
159
+ **kwargs,
160
+ ):
161
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
162
+ bos_token = AddedToken(bos_token, normalized=False, special=True) if isinstance(bos_token, str) else bos_token
163
+ eos_token = AddedToken(eos_token, normalized=False, special=True) if isinstance(eos_token, str) else eos_token
164
+ unk_token = AddedToken(unk_token, normalized=False, special=True) if isinstance(unk_token, str) else unk_token
165
+ pad_token = AddedToken(pad_token, normalized=False, special=True) if isinstance(pad_token, str) else pad_token
166
+
167
+ if legacy is None:
168
+ logger.warning_once(
169
+ f"You are using the default legacy behaviour of the {self.__class__}. This is"
170
+ " expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you."
171
+ " If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it"
172
+ " means, and thoroughly read the reason why this was added as explained in"
173
+ " https://github.com/huggingface/transformers/pull/24565"
174
+ )
175
+ legacy = True
176
+
177
+ self.legacy = legacy
178
+ self.vocab_file = vocab_file
179
+ self.add_bos_token = add_bos_token
180
+ self.add_eos_token = add_eos_token
181
+ self.use_default_system_prompt = use_default_system_prompt
182
+ self.sp_model = self.get_spm_processor(kwargs.pop("from_slow", False))
183
+ self.add_prefix_space = add_prefix_space
184
+
185
+ super().__init__(
186
+ bos_token=bos_token,
187
+ eos_token=eos_token,
188
+ unk_token=unk_token,
189
+ pad_token=pad_token,
190
+ add_bos_token=add_bos_token,
191
+ add_eos_token=add_eos_token,
192
+ sp_model_kwargs=self.sp_model_kwargs,
193
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
194
+ use_default_system_prompt=use_default_system_prompt,
195
+ spaces_between_special_tokens=spaces_between_special_tokens,
196
+ legacy=legacy,
197
+ add_prefix_space=add_prefix_space,
198
+ **kwargs,
199
+ )
200
+
201
+ @property
202
+ def unk_token_length(self):
203
+ return len(self.sp_model.encode(str(self.unk_token)))
204
+
205
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.get_spm_processor
206
+ def get_spm_processor(self, from_slow=False):
207
+ tokenizer = spm.SentencePieceProcessor(**self.sp_model_kwargs)
208
+ if self.legacy or from_slow: # no dependency on protobuf
209
+ tokenizer.Load(self.vocab_file)
210
+ return tokenizer
211
+
212
+ with open(self.vocab_file, "rb") as f:
213
+ sp_model = f.read()
214
+ model_pb2 = import_protobuf(f"The new behaviour of {self.__class__.__name__} (with `self.legacy = False`)")
215
+ model = model_pb2.ModelProto.FromString(sp_model)
216
+ normalizer_spec = model_pb2.NormalizerSpec()
217
+ normalizer_spec.add_dummy_prefix = False
218
+ model.normalizer_spec.MergeFrom(normalizer_spec)
219
+ sp_model = model.SerializeToString()
220
+ tokenizer.LoadFromSerializedProto(sp_model)
221
+ return tokenizer
222
+
223
+ def __getstate__(self):
224
+ state = self.__dict__.copy()
225
+ state["sp_model"] = None
226
+ state["sp_model_proto"] = self.sp_model.serialized_model_proto()
227
+ return state
228
+
229
+ def __setstate__(self, d):
230
+ self.__dict__ = d
231
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
232
+ self.sp_model.LoadFromSerializedProto(self.sp_model_proto)
233
+
234
+ @property
235
+ def vocab_size(self):
236
+ """Returns vocab size"""
237
+ return self.sp_model.get_piece_size()
238
+
239
+ def get_vocab(self):
240
+ """Returns vocab as a dict"""
241
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
242
+ vocab.update(self.added_tokens_encoder)
243
+ return vocab
244
+
245
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.tokenize
246
+ def tokenize(self, text: "TextInput", **kwargs) -> List[str]:
247
+ """
248
+ Converts a string to a list of tokens. If `self.legacy` is set to `False`, a prefix token is added unless the
249
+ first token is special.
250
+ """
251
+ if self.legacy or len(text) == 0:
252
+ return super().tokenize(text, **kwargs)
253
+
254
+ text = text.replace(SPIECE_UNDERLINE, " ")
255
+ if self.add_prefix_space:
256
+ text = SPIECE_UNDERLINE + text
257
+
258
+ tokens = super().tokenize(text, **kwargs)
259
+
260
+ if len(tokens) > 1 and tokens[0] == SPIECE_UNDERLINE and tokens[1] in self.all_special_tokens:
261
+ tokens = tokens[1:]
262
+ return tokens
263
+
264
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer._tokenize
265
+ def _tokenize(self, text, **kwargs):
266
+ """
267
+ Returns a tokenized string.
268
+
269
+ We de-activated the `add_dummy_prefix` option, thus the sentencepiece internals will always strip any
270
+ SPIECE_UNDERLINE. For example: `self.sp_model.encode(f"{SPIECE_UNDERLINE}Hey", out_type = str)` will give
271
+ `['H', 'e', 'y']` instead of `['▁He', 'y']`. Thus we always encode `f"{unk_token}text"` and strip the
272
+ `unk_token`. Here is an example with `unk_token = "<unk>"` and `unk_token_length = 4`.
273
+ `self.tokenizer.sp_model.encode("<unk> Hey", out_type = str)[4:]`.
274
+ """
275
+ tokens = self.sp_model.encode(text, out_type=str)
276
+ if self.legacy or not text.startswith((SPIECE_UNDERLINE, " ")):
277
+ return tokens
278
+
279
+ # 1. Encode string + prefix ex: "<unk> Hey"
280
+ tokens = self.sp_model.encode(self.unk_token + text, out_type=str)
281
+ # 2. Remove self.unk_token from ['<','unk','>', '▁Hey']
282
+ return tokens[self.unk_token_length :] if len(tokens) >= self.unk_token_length else tokens
283
+
284
+ def _convert_token_to_id(self, token):
285
+ """Converts a token (str) in an id using the vocab."""
286
+ return self.sp_model.piece_to_id(token)
287
+
288
+ def _convert_id_to_token(self, index):
289
+ """Converts an index (integer) in a token (str) using the vocab."""
290
+ token = self.sp_model.IdToPiece(index)
291
+ return token
292
+
293
+ def convert_tokens_to_string(self, tokens):
294
+ """Converts a sequence of tokens (string) in a single string."""
295
+ # since we manually add the prefix space, we have to remove it when decoding
296
+ if tokens[0].startswith(SPIECE_UNDERLINE) and self.add_prefix_space:
297
+ tokens[0] = tokens[0][1:]
298
+
299
+ current_sub_tokens = []
300
+ out_string = ""
301
+ prev_is_special = False
302
+ for i, token in enumerate(tokens):
303
+ # make sure that special tokens are not decoded using sentencepiece model
304
+ if token in self.all_special_tokens:
305
+ if not prev_is_special and i != 0 and self.legacy:
306
+ out_string += " "
307
+ out_string += self.sp_model.decode(current_sub_tokens) + token
308
+ prev_is_special = True
309
+ current_sub_tokens = []
310
+ else:
311
+ current_sub_tokens.append(token)
312
+ prev_is_special = False
313
+ out_string += self.sp_model.decode(current_sub_tokens)
314
+ return out_string
315
+
316
+ def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
317
+ """
318
+ Save the vocabulary and special tokens file to a directory.
319
+
320
+ Args:
321
+ save_directory (`str`):
322
+ The directory in which to save the vocabulary.
323
+
324
+ Returns:
325
+ `Tuple(str)`: Paths to the files saved.
326
+ """
327
+ if not os.path.isdir(save_directory):
328
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
329
+ return
330
+ out_vocab_file = os.path.join(
331
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
332
+ )
333
+
334
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
335
+ copyfile(self.vocab_file, out_vocab_file)
336
+ elif not os.path.isfile(self.vocab_file):
337
+ with open(out_vocab_file, "wb") as fi:
338
+ content_spiece_model = self.sp_model.serialized_model_proto()
339
+ fi.write(content_spiece_model)
340
+
341
+ return (out_vocab_file,)
342
+
343
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
344
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
345
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
346
+
347
+ output = bos_token_id + token_ids_0 + eos_token_id
348
+
349
+ if token_ids_1 is not None:
350
+ output = output + bos_token_id + token_ids_1 + eos_token_id
351
+
352
+ return output
353
+
354
+ def get_special_tokens_mask(
355
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
356
+ ) -> List[int]:
357
+ """
358
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
359
+ special tokens using the tokenizer `prepare_for_model` method.
360
+
361
+ Args:
362
+ token_ids_0 (`List[int]`):
363
+ List of IDs.
364
+ token_ids_1 (`List[int]`, *optional*):
365
+ Optional second list of IDs for sequence pairs.
366
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
367
+ Whether or not the token list is already formatted with special tokens for the model.
368
+
369
+ Returns:
370
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
371
+ """
372
+ if already_has_special_tokens:
373
+ return super().get_special_tokens_mask(
374
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
375
+ )
376
+
377
+ bos_token_id = [1] if self.add_bos_token else []
378
+ eos_token_id = [1] if self.add_eos_token else []
379
+
380
+ if token_ids_1 is None:
381
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
382
+ return (
383
+ bos_token_id
384
+ + ([0] * len(token_ids_0))
385
+ + eos_token_id
386
+ + bos_token_id
387
+ + ([0] * len(token_ids_1))
388
+ + eos_token_id
389
+ )
390
+
391
+ def create_token_type_ids_from_sequences(
392
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
393
+ ) -> List[int]:
394
+ """
395
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
396
+ sequence pair mask has the following format:
397
+
398
+ ```
399
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
400
+ | first sequence | second sequence |
401
+ ```
402
+
403
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
404
+
405
+ Args:
406
+ token_ids_0 (`List[int]`):
407
+ List of ids.
408
+ token_ids_1 (`List[int]`, *optional*):
409
+ Optional second list of IDs for sequence pairs.
410
+
411
+ Returns:
412
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
413
+ """
414
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
415
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
416
+
417
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
418
+
419
+ if token_ids_1 is not None:
420
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
421
+
422
+ return output
423
+
424
+ @property
425
+ def default_chat_template(self):
426
+ """
427
+ LLaMA uses [INST] and [/INST] to indicate user messages, and <<SYS>> and <</SYS>> to indicate system messages.
428
+ Assistant messages do not have special tokens, because LLaMA chat models are generally trained with strict
429
+ user/assistant/user/assistant message ordering, and so assistant messages can be identified from the ordering
430
+ rather than needing special tokens. The system message is partly 'embedded' in the first user message, which
431
+ results in an unusual token ordering when it is present. This template should definitely be changed if you wish
432
+ to fine-tune a model with more flexible role ordering!
433
+
434
+ The output should look something like:
435
+
436
+ <bos>[INST] B_SYS SystemPrompt E_SYS Prompt [/INST] Answer <eos><bos>[INST] Prompt [/INST] Answer <eos>
437
+ <bos>[INST] Prompt [/INST]
438
+
439
+ The reference for this chat template is [this code
440
+ snippet](https://github.com/facebookresearch/llama/blob/556949fdfb72da27c2f4a40b7f0e4cf0b8153a28/llama/generation.py#L320-L362)
441
+ in the original repository.
442
+ """
443
+ logger.warning_once(
444
+ "\nNo chat template is defined for this tokenizer - using the default template "
445
+ f"for the {self.__class__.__name__} class. If the default is not appropriate for "
446
+ "your model, please set `tokenizer.chat_template` to an appropriate template. "
447
+ "See https://huggingface.co/docs/transformers/main/chat_templating for more information.\n"
448
+ )
449
+ template = (
450
+ "{% if messages[0]['role'] == 'system' %}"
451
+ "{% set loop_messages = messages[1:] %}" # Extract system message if it's present
452
+ "{% set system_message = messages[0]['content'] %}"
453
+ "{% elif USE_DEFAULT_PROMPT == true and not '<<SYS>>' in messages[0]['content'] %}"
454
+ "{% set loop_messages = messages %}" # Or use the default system message if the flag is set
455
+ "{% set system_message = 'DEFAULT_SYSTEM_MESSAGE' %}"
456
+ "{% else %}"
457
+ "{% set loop_messages = messages %}"
458
+ "{% set system_message = false %}"
459
+ "{% endif %}"
460
+ "{% for message in loop_messages %}" # Loop over all non-system messages
461
+ "{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}"
462
+ "{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}"
463
+ "{% endif %}"
464
+ "{% if loop.index0 == 0 and system_message != false %}" # Embed system message in first message
465
+ "{% set content = '<<SYS>>\\n' + system_message + '\\n<</SYS>>\\n\\n' + message['content'] %}"
466
+ "{% else %}"
467
+ "{% set content = message['content'] %}"
468
+ "{% endif %}"
469
+ "{% if message['role'] == 'user' %}" # After all of that, handle messages/roles in a fairly normal way
470
+ "{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}"
471
+ "{% elif message['role'] == 'system' %}"
472
+ "{{ '<<SYS>>\\n' + content.strip() + '\\n<</SYS>>\\n\\n' }}"
473
+ "{% elif message['role'] == 'assistant' %}"
474
+ "{{ ' ' + content.strip() + ' ' + eos_token }}"
475
+ "{% endif %}"
476
+ "{% endfor %}"
477
+ )
478
+ template = template.replace("USE_DEFAULT_PROMPT", "true" if self.use_default_system_prompt else "false")
479
+ default_message = DEFAULT_SYSTEM_PROMPT.replace("\n", "\\n").replace("'", "\\'")
480
+ template = template.replace("DEFAULT_SYSTEM_MESSAGE", default_message)
481
+
482
+ return template
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
3
+ size 499723
tokenizer_config.json ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": true,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ },
30
+ "32000": {
31
+ "content": "<pad>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "32001": {
39
+ "content": "</line>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": false,
43
+ "single_word": false,
44
+ "special": true
45
+ }
46
+ },
47
+ "additional_special_tokens": [
48
+ "</line>"
49
+ ],
50
+ "bos_token": "<s>",
51
+ "clean_up_tokenization_spaces": false,
52
+ "eos_token": "</s>",
53
+ "legacy": false,
54
+ "model_max_length": 1000000000000000019884624838656,
55
+ "pad_token": "<pad>",
56
+ "padding_side": "right",
57
+ "sp_model_kwargs": {},
58
+ "spaces_between_special_tokens": false,
59
+ "tokenizer_class": "BitnetTokenizer",
60
+ "unk_token": "<unk>",
61
+ "use_default_system_prompt": false
62
+ }
utils_quant.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn
4
+
5
+
6
+ def weight_quant(weight, num_bits=1):
7
+ dtype = weight.dtype
8
+ weight = weight.float()
9
+ s = 1 / weight.abs().mean().clamp(min=1e-5)
10
+ result = (weight * s).round().clamp(-1, 1) / s
11
+ return result.type(dtype)
12
+
13
+
14
+ def activation_quant(x, num_bits=8):
15
+ dtype = x.dtype
16
+ x = x.float()
17
+ Qn = -2 ** (num_bits - 1)
18
+ Qp = 2 ** (num_bits - 1) - 1
19
+ s = Qp / x.abs().max(dim=-1, keepdim=True).values.clamp(min=1e-5)
20
+ result = (x * s).round().clamp(Qn, Qp) / s
21
+ return result.type(dtype)
22
+
23
+
24
+ class BitLinear(nn.Linear):
25
+
26
+ def __init__(self,
27
+ *kargs,
28
+ weight_bits=1,
29
+ input_bits=8,
30
+ **kwargs
31
+ ):
32
+ super(BitLinear, self).__init__(*kargs, **kwargs)
33
+ """
34
+ RMSNorm is placed outside BitLinear
35
+ """
36
+ self.weight_bits = weight_bits
37
+ self.input_bits = input_bits
38
+
39
+ def forward(self, input):
40
+
41
+ quant_input = input + (activation_quant(input, self.input_bits) - input).detach()
42
+ quant_weight = self.weight + (weight_quant(self.weight, self.weight_bits) - self.weight).detach()
43
+
44
+ out = nn.functional.linear(quant_input, quant_weight)
45
+ if not self.bias is None:
46
+ out += self.bias.view(1, -1).expand_as(out)
47
+
48
+ return out