kousw commited on
Commit
29964ce
1 Parent(s): 2b65093

Upload 21 files

Browse files
.gitignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # ignored python files
2
+ __pycache__/
3
+ *.pyc
4
+ *.pyo
5
+ *.pyd
6
+
7
+ # env
8
+ .venv/
9
+ .env
README.md CHANGED
@@ -1,3 +1,40 @@
1
  ---
2
  license: mit
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: mit
3
  ---
4
+
5
+ # Quantized BitNet-B1-58-3B
6
+
7
+ This repository contains a quantized version of the [1bitLLM/bitnet_b1_58-3B](https://huggingface.co/1bitLLM/bitnet_b1_58-3B) model.
8
+ While the original repository showcases impressive validation results, it emulates BitNet's Linear layers, resulting in memory usage similar to fp16 models. By leveraging the QuantLinear module from [AutoGPTQ](https://github.com/AutoGPTQ/AutoGPTQ), this repository enables the output and execution of a 2-bit quantized model.
9
+
10
+ The quantized model offers significant advantages in terms of model size and memory consumption. With a model size of just 1GB , the quantized 3B model can perform inference with a context size of 2048 while consuming only 4.5GB of VRAM. Furthermore, since the weights used during execution are the same as the original repository, the perplexity (PPL) output remains unchanged.
11
+
12
+
13
+ ## Install
14
+
15
+ ```
16
+ pip install -r requirements.txt
17
+ ```
18
+
19
+ ## Quantization
20
+
21
+ The quantized model is already provided in this repository. However, if you wish to quantize the model yourself, you can load it from 1bitLLM/bitnet_b1_58-3B and save the quantized version (2-bit) to ./bitnet_b1_58-3B_quantized by running the following command:
22
+
23
+ ```
24
+ python quantization.py
25
+ ```
26
+
27
+
28
+ ## Evaluation
29
+
30
+ ```
31
+ python eval_ppl.py --hf_path ./ --seqlen 2048 --max_dataset_size 1000
32
+ ```
33
+ ```
34
+ python eval_task.py --hf_path ./ \
35
+ --batch_size 1 \
36
+ --tasks \
37
+ --output_path result.json \
38
+ --num_fewshot 0 \
39
+ --ctx_size 2048
40
+ ```
added_tokens.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "</line>": 32001,
3
+ "<pad>": 32000
4
+ }
config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "group_size": 128,
11
+ "hidden_act": "silu",
12
+ "hidden_size": 3200,
13
+ "initializer_range": 0.02,
14
+ "input_bits": 8,
15
+ "intermediate_size": 8640,
16
+ "max_position_embeddings": 2048,
17
+ "model_type": "llama",
18
+ "num_attention_heads": 32,
19
+ "num_hidden_layers": 26,
20
+ "num_key_value_heads": 32,
21
+ "pad_token_id": 32000,
22
+ "pretraining_tp": 1,
23
+ "quant_bits": 2,
24
+ "rms_norm_eps": 1e-05,
25
+ "rope_scaling": null,
26
+ "rope_theta": 10000.0,
27
+ "tie_word_embeddings": true,
28
+ "torch_dtype": "float16",
29
+ "transformers_version": "4.39.2",
30
+ "use_cache": true,
31
+ "vocab_size": 32002,
32
+ "weight_bits": 1
33
+ }
configuration_bitnet.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ logger = logging.get_logger(__name__)
26
+
27
+ LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
28
+
29
+
30
+ class BitnetConfig(PretrainedConfig):
31
+ r"""
32
+ This is the configuration class to store the configuration of a [`BitnetModel`]. It is used to instantiate an LLaMA
33
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
34
+ defaults will yield a similar configuration to that of the LLaMA-7B.
35
+
36
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
37
+ documentation from [`PretrainedConfig`] for more information.
38
+
39
+
40
+ Args:
41
+ vocab_size (`int`, *optional*, defaults to 32000):
42
+ Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
43
+ `inputs_ids` passed when calling [`BitnetModel`]
44
+ hidden_size (`int`, *optional*, defaults to 4096):
45
+ Dimension of the hidden representations.
46
+ intermediate_size (`int`, *optional*, defaults to 11008):
47
+ Dimension of the MLP representations.
48
+ num_hidden_layers (`int`, *optional*, defaults to 32):
49
+ Number of hidden layers in the Transformer decoder.
50
+ num_attention_heads (`int`, *optional*, defaults to 32):
51
+ Number of attention heads for each attention layer in the Transformer decoder.
52
+ num_key_value_heads (`int`, *optional*):
53
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
54
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
55
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
56
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
57
+ by meanpooling all the original heads within that group. For more details checkout [this
58
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
59
+ `num_attention_heads`.
60
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
61
+ The non-linear activation function (function or string) in the decoder.
62
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
63
+ The maximum sequence length that this model might ever be used with. Bitnet 1 supports up to 2048 tokens,
64
+ Bitnet 2 up to 4096, CodeBitnet up to 16384.
65
+ initializer_range (`float`, *optional*, defaults to 0.02):
66
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
67
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
68
+ The epsilon used by the rms normalization layers.
69
+ use_cache (`bool`, *optional*, defaults to `True`):
70
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
71
+ relevant if `config.is_decoder=True`.
72
+ pad_token_id (`int`, *optional*):
73
+ Padding token id.
74
+ bos_token_id (`int`, *optional*, defaults to 1):
75
+ Beginning of stream token id.
76
+ eos_token_id (`int`, *optional*, defaults to 2):
77
+ End of stream token id.
78
+ pretraining_tp (`int`, *optional*, defaults to 1):
79
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
80
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to understand more about it. This value is
81
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
82
+ issue](https://github.com/pytorch/pytorch/issues/76232).
83
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
84
+ Whether to tie weight embeddings
85
+ rope_theta (`float`, *optional*, defaults to 10000.0):
86
+ The base period of the RoPE embeddings.
87
+ rope_scaling (`Dict`, *optional*):
88
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
89
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
90
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
91
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
92
+ these scaling strategies behave:
93
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
94
+ experimental feature, subject to breaking API changes in future versions.
95
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
96
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
97
+ attention_dropout (`float`, *optional*, defaults to 0.0):
98
+ The dropout ratio for the attention probabilities.
99
+
100
+ ```python
101
+ >>> from transformers import BitnetModel, BitnetConfig
102
+
103
+ >>> # Initializing a LLaMA llama-7b style configuration
104
+ >>> configuration = BitnetConfig()
105
+
106
+ >>> # Initializing a model from the llama-7b style configuration
107
+ >>> model = BitnetModel(configuration)
108
+
109
+ >>> # Accessing the model configuration
110
+ >>> configuration = model.config
111
+ ```"""
112
+
113
+ model_type = "llama"
114
+ keys_to_ignore_at_inference = ["past_key_values"]
115
+
116
+ def __init__(
117
+ self,
118
+ vocab_size=32000,
119
+ hidden_size=4096,
120
+ intermediate_size=11008,
121
+ num_hidden_layers=32,
122
+ num_attention_heads=32,
123
+ num_key_value_heads=None,
124
+ hidden_act="silu",
125
+ max_position_embeddings=2048,
126
+ initializer_range=0.02,
127
+ rms_norm_eps=1e-6,
128
+ use_cache=True,
129
+ pad_token_id=None,
130
+ bos_token_id=1,
131
+ eos_token_id=2,
132
+ pretraining_tp=1,
133
+ tie_word_embeddings=False,
134
+ rope_theta=10000.0,
135
+ rope_scaling=None,
136
+ attention_bias=False,
137
+ attention_dropout=0.0,
138
+ weight_bits=1,
139
+ input_bits=8,
140
+ quant_bits=None,
141
+ group_size=128,
142
+ **kwargs,
143
+ ):
144
+ self.vocab_size = vocab_size
145
+ self.max_position_embeddings = max_position_embeddings
146
+ self.hidden_size = hidden_size
147
+ self.intermediate_size = intermediate_size
148
+ self.num_hidden_layers = num_hidden_layers
149
+ self.num_attention_heads = num_attention_heads
150
+
151
+ # for backward compatibility
152
+ if num_key_value_heads is None:
153
+ num_key_value_heads = num_attention_heads
154
+
155
+ self.num_key_value_heads = num_key_value_heads
156
+ self.hidden_act = hidden_act
157
+ self.initializer_range = initializer_range
158
+ self.rms_norm_eps = rms_norm_eps
159
+ self.pretraining_tp = pretraining_tp
160
+ self.use_cache = use_cache
161
+ self.rope_theta = rope_theta
162
+ self.rope_scaling = rope_scaling
163
+ self._rope_scaling_validation()
164
+ self.attention_bias = attention_bias
165
+ self.attention_dropout = attention_dropout
166
+ self.weight_bits = weight_bits
167
+ self.input_bits = input_bits
168
+ self.quant_bits = quant_bits
169
+ self.group_size = group_size
170
+
171
+ super().__init__(
172
+ pad_token_id=pad_token_id,
173
+ bos_token_id=bos_token_id,
174
+ eos_token_id=eos_token_id,
175
+ tie_word_embeddings=tie_word_embeddings,
176
+ **kwargs,
177
+ )
178
+
179
+ def _rope_scaling_validation(self):
180
+ """
181
+ Validate the `rope_scaling` configuration.
182
+ """
183
+ if self.rope_scaling is None:
184
+ return
185
+
186
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
187
+ raise ValueError(
188
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
189
+ f"got {self.rope_scaling}"
190
+ )
191
+ rope_scaling_type = self.rope_scaling.get("type", None)
192
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
193
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
194
+ raise ValueError(
195
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
196
+ )
197
+ if (
198
+ rope_scaling_factor is None
199
+ or not isinstance(rope_scaling_factor, float)
200
+ or rope_scaling_factor <= 1.0
201
+ ):
202
+ raise ValueError(
203
+ f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}"
204
+ )
eval_ppl.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import math
3
+ import random
4
+
5
+ import torch
6
+ from tqdm import tqdm
7
+
8
+ from eval_utils import get_test_dataset
9
+ from modeling_bitnet import BitnetForCausalLM
10
+ from tokenization_bitnet import BitnetTokenizer
11
+
12
+ torch.set_grad_enabled(False)
13
+
14
+ parser = argparse.ArgumentParser()
15
+ parser.add_argument("--seed", default=0, type=int)
16
+ parser.add_argument("--hf_path", default="./", type=str) # 1bitLLM/bitnet_b1_58-3B
17
+ parser.add_argument("--seqlen", default=2048, type=int)
18
+ parser.add_argument("--max_dataset_size", default=100000, type=int)
19
+
20
+
21
+ def calulate_loss(model, input, loss_fct):
22
+ output = model(
23
+ input, use_cache=False, output_hidden_states=False, output_attentions=False
24
+ )[0]
25
+ shift_logits = output[:, :-1, :].contiguous()
26
+ shift_labels = input[:, 1:]
27
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
28
+ return loss
29
+
30
+
31
+ def main(args):
32
+ datasets = ["wikitext2"] # ['c4', 'wikitext2']
33
+
34
+ model = BitnetForCausalLM.from_pretrained(
35
+ args.hf_path,
36
+ device_map="auto",
37
+ low_cpu_mem_usage=True,
38
+ use_flash_attention_2=True,
39
+ torch_dtype=torch.float16,
40
+ ).half()
41
+ tokenizer = BitnetTokenizer.from_pretrained(args.hf_path, use_fast=False)
42
+ loss_fct = torch.nn.CrossEntropyLoss(reduction="sum").cuda()
43
+
44
+ ppl = []
45
+
46
+ for dataset in datasets:
47
+ testdata = get_test_dataset(dataset, tokenizer, seqlen=args.seqlen)
48
+ acc_loss, count = 0.0, 0
49
+
50
+ dataset_size = (
51
+ args.max_dataset_size
52
+ if len(testdata) > args.max_dataset_size
53
+ else len(testdata)
54
+ )
55
+ progress = tqdm(range(dataset_size))
56
+ for ii in progress:
57
+ input = torch.Tensor(testdata[ii]).long().cuda().view(1, -1)
58
+ loss = calulate_loss(model, input, loss_fct)
59
+ count += input.size(-1) - 1
60
+ acc_loss += loss.item()
61
+ progress.set_description(f"avg_loss = {acc_loss/ count / math.log(2)}")
62
+
63
+ avg_loss = acc_loss / count / math.log(2)
64
+ ppl.append(2**avg_loss)
65
+ print("{} PPL: {}".format(dataset, ppl[-1]))
66
+
67
+ print(ppl)
68
+ print("Avg PPL:", sum(ppl) / len(ppl))
69
+
70
+
71
+ if __name__ == "__main__":
72
+ torch.set_grad_enabled(False)
73
+ args = parser.parse_args()
74
+ random.seed(args.seed)
75
+ torch.random.manual_seed(args.seed)
76
+ 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.2"
7
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d13e383dca8cf70c25c4cbe947b25039ec038641d46f0ce384798508f8b17fba
3
+ size 1070878476
modeling_bitnet.py ADDED
@@ -0,0 +1,1851 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
33
+ from transformers.modeling_outputs import (
34
+ BaseModelOutputWithPast,
35
+ CausalLMOutputWithPast,
36
+ QuestionAnsweringModelOutput,
37
+ SequenceClassifierOutputWithPast,
38
+ )
39
+ from transformers.modeling_utils import PreTrainedModel
40
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
41
+ from transformers.utils import (
42
+ add_start_docstrings,
43
+ add_start_docstrings_to_model_forward,
44
+ is_flash_attn_2_available,
45
+ is_flash_attn_greater_or_equal_2_10,
46
+ logging,
47
+ replace_return_docstrings,
48
+ )
49
+
50
+ from configuration_bitnet import BitnetConfig
51
+
52
+ # from utils_quant import BitLinear
53
+ from utils_quant import BitLinear, QuantizedBitLinear
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__(
99
+ self,
100
+ dim,
101
+ max_position_embeddings=2048,
102
+ base=10000,
103
+ device=None,
104
+ scaling_factor=1.0,
105
+ ):
106
+ super().__init__()
107
+ self.scaling_factor = scaling_factor
108
+ self.dim = dim
109
+ self.max_position_embeddings = max_position_embeddings
110
+ self.base = base
111
+ inv_freq = 1.0 / (
112
+ self.base
113
+ ** (
114
+ torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device)
115
+ / self.dim
116
+ )
117
+ )
118
+ self.register_buffer("inv_freq", inv_freq)
119
+ # For BC we register cos and sin cached
120
+ self.max_seq_len_cached = max_position_embeddings
121
+ t = torch.arange(
122
+ self.max_seq_len_cached, device=device, dtype=torch.int64
123
+ ).type_as(self.inv_freq)
124
+ t = t / self.scaling_factor
125
+ freqs = torch.outer(t, self.inv_freq)
126
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
127
+ emb = torch.cat((freqs, freqs), dim=-1)
128
+ self.register_buffer(
129
+ "_cos_cached", emb.cos().to(torch.get_default_dtype()), persistent=False
130
+ )
131
+ self.register_buffer(
132
+ "_sin_cached", emb.sin().to(torch.get_default_dtype()), persistent=False
133
+ )
134
+
135
+ @property
136
+ def sin_cached(self):
137
+ logger.warning_once(
138
+ "The sin_cached attribute will be removed in 4.39. Bear in mind that its contents changed in v4.38. Use "
139
+ "the forward method of RoPE from now on instead. It is not used in the `BitnetAttention` class"
140
+ )
141
+ return self._sin_cached
142
+
143
+ @property
144
+ def cos_cached(self):
145
+ logger.warning_once(
146
+ "The cos_cached attribute will be removed in 4.39. Bear in mind that its contents changed in v4.38. Use "
147
+ "the forward method of RoPE from now on instead. It is not used in the `BitnetAttention` class"
148
+ )
149
+ return self._cos_cached
150
+
151
+ @torch.no_grad()
152
+ def forward(self, x, position_ids):
153
+ # x: [bs, num_attention_heads, seq_len, head_size]
154
+ inv_freq_expanded = (
155
+ self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
156
+ )
157
+ position_ids_expanded = position_ids[:, None, :].float()
158
+ # Force float32 since bfloat16 loses precision on long contexts
159
+ # See https://github.com/huggingface/transformers/pull/29285
160
+ device_type = x.device.type
161
+ device_type = (
162
+ device_type
163
+ if isinstance(device_type, str) and device_type != "mps"
164
+ else "cpu"
165
+ )
166
+ with torch.autocast(device_type=device_type, enabled=False):
167
+ freqs = (
168
+ inv_freq_expanded.float() @ position_ids_expanded.float()
169
+ ).transpose(1, 2)
170
+ emb = torch.cat((freqs, freqs), dim=-1)
171
+ cos = emb.cos()
172
+ sin = emb.sin()
173
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
174
+
175
+
176
+ def rotate_half(x):
177
+ """Rotates half the hidden dims of the input."""
178
+ x1 = x[..., : x.shape[-1] // 2]
179
+ x2 = x[..., x.shape[-1] // 2 :]
180
+ return torch.cat((-x2, x1), dim=-1)
181
+
182
+
183
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
184
+ """Applies Rotary Position Embedding to the query and key tensors.
185
+
186
+ Args:
187
+ q (`torch.Tensor`): The query tensor.
188
+ k (`torch.Tensor`): The key tensor.
189
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
190
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
191
+ position_ids (`torch.Tensor`, *optional*):
192
+ Deprecated and unused.
193
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
194
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
195
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
196
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
197
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
198
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
199
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
200
+ Returns:
201
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
202
+ """
203
+ cos = cos.unsqueeze(unsqueeze_dim)
204
+ sin = sin.unsqueeze(unsqueeze_dim)
205
+ q_embed = (q * cos) + (rotate_half(q) * sin)
206
+ k_embed = (k * cos) + (rotate_half(k) * sin)
207
+ return q_embed, k_embed
208
+
209
+
210
+ def generate_BitLinear(
211
+ quantized,
212
+ in_features,
213
+ out_features,
214
+ bias,
215
+ weight_bits,
216
+ input_bits,
217
+ quant_bits,
218
+ group_size,
219
+ ):
220
+ if quantized:
221
+ return QuantizedBitLinear(
222
+ in_features,
223
+ out_features,
224
+ bias=bias,
225
+ weight_bits=weight_bits,
226
+ input_bits=input_bits,
227
+ quant_bits=quant_bits,
228
+ group_size=group_size,
229
+ )
230
+ else:
231
+ return BitLinear(
232
+ in_features,
233
+ out_features,
234
+ bias=bias,
235
+ weight_bits=weight_bits,
236
+ input_bits=input_bits,
237
+ )
238
+
239
+
240
+ class BitnetMLP(nn.Module):
241
+ def __init__(self, config):
242
+ super().__init__()
243
+ self.config = config
244
+ self.hidden_size = config.hidden_size
245
+ self.intermediate_size = config.intermediate_size
246
+
247
+ self.gate_proj = generate_BitLinear(
248
+ config.quant_bits is not None,
249
+ self.hidden_size,
250
+ self.intermediate_size,
251
+ bias=False,
252
+ weight_bits=config.weight_bits,
253
+ input_bits=config.input_bits,
254
+ quant_bits=config.quant_bits,
255
+ group_size=config.group_size,
256
+ )
257
+
258
+ self.up_proj = generate_BitLinear(
259
+ config.quant_bits is not None,
260
+ self.hidden_size,
261
+ self.intermediate_size,
262
+ bias=False,
263
+ weight_bits=config.weight_bits,
264
+ input_bits=config.input_bits,
265
+ quant_bits=config.quant_bits,
266
+ group_size=config.group_size,
267
+ )
268
+
269
+ self.down_proj = generate_BitLinear(
270
+ config.quant_bits is not None,
271
+ self.intermediate_size,
272
+ self.hidden_size,
273
+ bias=False,
274
+ weight_bits=config.weight_bits,
275
+ input_bits=config.input_bits,
276
+ quant_bits=config.quant_bits,
277
+ group_size=config.group_size,
278
+ )
279
+
280
+ self.is_quantized = config.quant_bits is not None
281
+
282
+ # self.gate_proj = BitLinear(
283
+ # self.hidden_size,
284
+ # self.intermediate_size,
285
+ # bias=False,
286
+ # weight_bits=config.weight_bits,
287
+ # input_bits=config.input_bits,
288
+ # )
289
+ # self.up_proj = BitLinear(
290
+ # self.hidden_size,
291
+ # self.intermediate_size,
292
+ # bias=False,
293
+ # weight_bits=config.weight_bits,
294
+ # input_bits=config.input_bits,
295
+ # )
296
+ # self.down_proj = BitLinear(
297
+ # self.intermediate_size,
298
+ # self.hidden_size,
299
+ # bias=False,
300
+ # weight_bits=config.weight_bits,
301
+ # input_bits=config.input_bits,
302
+ # )
303
+ self.act_fn = ACT2FN[config.hidden_act]
304
+ self.ffn_layernorm = BitnetRMSNorm(
305
+ self.intermediate_size, eps=config.rms_norm_eps
306
+ )
307
+
308
+ def forward(self, x):
309
+ x = self.act_fn(self.gate_proj(x)) * self.up_proj(x)
310
+ x = self.ffn_layernorm(x)
311
+ x = self.down_proj(x)
312
+ return x
313
+
314
+ def quantize(self, quant_bits=2, group_size=128):
315
+ if not self.is_quantized:
316
+ self.gate_proj.quantize()
317
+ self.up_proj.quantize()
318
+ self.down_proj.quantize()
319
+
320
+ new_gate_proj = QuantizedBitLinear(
321
+ self.gate_proj.in_features,
322
+ self.gate_proj.out_features,
323
+ self.gate_proj.bias is not None,
324
+ self.gate_proj.weight_bits,
325
+ self.gate_proj.input_bits,
326
+ quant_bits,
327
+ group_size,
328
+ )
329
+ new_up_proj = QuantizedBitLinear(
330
+ self.up_proj.in_features,
331
+ self.up_proj.out_features,
332
+ self.up_proj.bias is not None,
333
+ self.up_proj.weight_bits,
334
+ self.up_proj.input_bits,
335
+ quant_bits,
336
+ group_size,
337
+ )
338
+ new_down_proj = QuantizedBitLinear(
339
+ self.down_proj.in_features,
340
+ self.down_proj.out_features,
341
+ self.down_proj.bias is not None,
342
+ self.down_proj.weight_bits,
343
+ self.down_proj.input_bits,
344
+ quant_bits,
345
+ group_size,
346
+ )
347
+
348
+ new_gate_proj.pack(self.gate_proj)
349
+ new_up_proj.pack(self.up_proj)
350
+ new_down_proj.pack(self.down_proj)
351
+
352
+ old_gate_proj = self.gate_proj
353
+ old_up_proj = self.up_proj
354
+ old_down_proj = self.down_proj
355
+
356
+ self.gate_proj = new_gate_proj
357
+ self.up_proj = new_up_proj
358
+ self.down_proj = new_down_proj
359
+
360
+ del old_gate_proj
361
+ del old_up_proj
362
+ del old_down_proj
363
+
364
+ self.is_quantized = True
365
+
366
+
367
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
368
+ """
369
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
370
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
371
+ """
372
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
373
+ if n_rep == 1:
374
+ return hidden_states
375
+ hidden_states = hidden_states[:, :, None, :, :].expand(
376
+ batch, num_key_value_heads, n_rep, slen, head_dim
377
+ )
378
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
379
+
380
+
381
+ class BitnetAttention(nn.Module):
382
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
383
+
384
+ def __init__(self, config: BitnetConfig, layer_idx: Optional[int] = None):
385
+ super().__init__()
386
+ self.config = config
387
+ self.layer_idx = layer_idx
388
+ if layer_idx is None:
389
+ logger.warning_once(
390
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
391
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
392
+ "when creating this class."
393
+ )
394
+
395
+ self.attention_dropout = config.attention_dropout
396
+ self.hidden_size = config.hidden_size
397
+ self.num_heads = config.num_attention_heads
398
+ self.head_dim = self.hidden_size // self.num_heads
399
+ self.num_key_value_heads = config.num_key_value_heads
400
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
401
+ self.max_position_embeddings = config.max_position_embeddings
402
+ self.rope_theta = config.rope_theta
403
+ self.is_causal = True
404
+
405
+ if (self.head_dim * self.num_heads) != self.hidden_size:
406
+ raise ValueError(
407
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
408
+ f" and `num_heads`: {self.num_heads})."
409
+ )
410
+
411
+ self.q_proj = generate_BitLinear(
412
+ config.quant_bits is not None,
413
+ self.hidden_size,
414
+ self.num_heads * self.head_dim,
415
+ bias=config.attention_bias,
416
+ weight_bits=config.weight_bits,
417
+ input_bits=config.input_bits,
418
+ quant_bits=config.quant_bits,
419
+ group_size=config.group_size,
420
+ )
421
+
422
+ self.k_proj = generate_BitLinear(
423
+ config.quant_bits is not None,
424
+ self.hidden_size,
425
+ self.num_key_value_heads * self.head_dim,
426
+ bias=config.attention_bias,
427
+ weight_bits=config.weight_bits,
428
+ input_bits=config.input_bits,
429
+ quant_bits=config.quant_bits,
430
+ group_size=config.group_size,
431
+ )
432
+
433
+ self.v_proj = generate_BitLinear(
434
+ config.quant_bits is not None,
435
+ self.hidden_size,
436
+ self.num_key_value_heads * self.head_dim,
437
+ bias=config.attention_bias,
438
+ weight_bits=config.weight_bits,
439
+ input_bits=config.input_bits,
440
+ quant_bits=config.quant_bits,
441
+ group_size=config.group_size,
442
+ )
443
+
444
+ self.o_proj = generate_BitLinear(
445
+ config.quant_bits is not None,
446
+ self.hidden_size,
447
+ self.hidden_size,
448
+ bias=config.attention_bias,
449
+ weight_bits=config.weight_bits,
450
+ input_bits=config.input_bits,
451
+ quant_bits=config.quant_bits,
452
+ group_size=config.group_size,
453
+ )
454
+
455
+ self.is_quantized = config.quant_bits is not None
456
+
457
+ # self.q_proj = BitLinear(
458
+ # self.hidden_size,
459
+ # self.num_heads * self.head_dim,
460
+ # bias=config.attention_bias,
461
+ # weight_bits=config.weight_bits,
462
+ # input_bits=config.input_bits,
463
+ # )
464
+ # self.k_proj = BitLinear(
465
+ # self.hidden_size,
466
+ # self.num_key_value_heads * self.head_dim,
467
+ # bias=config.attention_bias,
468
+ # weight_bits=config.weight_bits,
469
+ # input_bits=config.input_bits,
470
+ # )
471
+ # self.v_proj = BitLinear(
472
+ # self.hidden_size,
473
+ # self.num_key_value_heads * self.head_dim,
474
+ # bias=config.attention_bias,
475
+ # weight_bits=config.weight_bits,
476
+ # input_bits=config.input_bits,
477
+ # )
478
+ # self.o_proj = BitLinear(
479
+ # self.hidden_size,
480
+ # self.hidden_size,
481
+ # bias=config.attention_bias,
482
+ # weight_bits=config.weight_bits,
483
+ # input_bits=config.input_bits,
484
+ # )
485
+ self._init_rope()
486
+ self.inner_attn_ln = BitnetRMSNorm(self.hidden_size, eps=config.rms_norm_eps)
487
+
488
+ def _init_rope(self):
489
+ if self.config.rope_scaling is None:
490
+ self.rotary_emb = BitnetRotaryEmbedding(
491
+ self.head_dim,
492
+ max_position_embeddings=self.max_position_embeddings,
493
+ base=self.rope_theta,
494
+ )
495
+ else:
496
+ raise NotImplementedError
497
+
498
+ def quantize(self, quant_bits=2, group_size=128):
499
+ if not self.is_quantized:
500
+ self.q_proj.quantize()
501
+ self.k_proj.quantize()
502
+ self.v_proj.quantize()
503
+ self.o_proj.quantize()
504
+
505
+ new_q_proj = QuantizedBitLinear(
506
+ self.q_proj.in_features,
507
+ self.q_proj.out_features,
508
+ self.q_proj.bias is not None,
509
+ self.q_proj.weight_bits,
510
+ self.q_proj.input_bits,
511
+ quant_bits,
512
+ group_size,
513
+ )
514
+ new_k_proj = QuantizedBitLinear(
515
+ self.k_proj.in_features,
516
+ self.k_proj.out_features,
517
+ self.k_proj.bias is not None,
518
+ self.k_proj.weight_bits,
519
+ self.k_proj.input_bits,
520
+ quant_bits,
521
+ group_size,
522
+ )
523
+ new_v_proj = QuantizedBitLinear(
524
+ self.v_proj.in_features,
525
+ self.v_proj.out_features,
526
+ self.v_proj.bias is not None,
527
+ self.v_proj.weight_bits,
528
+ self.v_proj.input_bits,
529
+ quant_bits,
530
+ group_size,
531
+ )
532
+ new_o_proj = QuantizedBitLinear(
533
+ self.o_proj.in_features,
534
+ self.o_proj.out_features,
535
+ self.o_proj.bias is not None,
536
+ self.o_proj.weight_bits,
537
+ self.o_proj.input_bits,
538
+ quant_bits,
539
+ group_size,
540
+ )
541
+
542
+ new_q_proj.pack(self.q_proj)
543
+ new_k_proj.pack(self.k_proj)
544
+ new_v_proj.pack(self.v_proj)
545
+ new_o_proj.pack(self.o_proj)
546
+
547
+ old_q_proj = self.q_proj
548
+ old_k_proj = self.k_proj
549
+ old_v_proj = self.v_proj
550
+ old_o_proj = self.o_proj
551
+
552
+ self.q_proj = new_q_proj
553
+ self.k_proj = new_k_proj
554
+ self.v_proj = new_v_proj
555
+ self.o_proj = new_o_proj
556
+
557
+ del old_q_proj
558
+ del old_k_proj
559
+ del old_v_proj
560
+ del old_o_proj
561
+
562
+ self.is_quantized = True
563
+
564
+ def forward(
565
+ self,
566
+ hidden_states: torch.Tensor,
567
+ attention_mask: Optional[torch.Tensor] = None,
568
+ position_ids: Optional[torch.LongTensor] = None,
569
+ past_key_value: Optional[Cache] = None,
570
+ output_attentions: bool = False,
571
+ use_cache: bool = False,
572
+ cache_position: Optional[torch.LongTensor] = None,
573
+ **kwargs,
574
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
575
+ bsz, q_len, _ = hidden_states.size()
576
+
577
+ query_states = self.q_proj(hidden_states)
578
+ key_states = self.k_proj(hidden_states)
579
+ value_states = self.v_proj(hidden_states)
580
+
581
+ query_states = query_states.view(
582
+ bsz, q_len, self.num_heads, self.head_dim
583
+ ).transpose(1, 2)
584
+ key_states = key_states.view(
585
+ bsz, q_len, self.num_key_value_heads, self.head_dim
586
+ ).transpose(1, 2)
587
+ value_states = value_states.view(
588
+ bsz, q_len, self.num_key_value_heads, self.head_dim
589
+ ).transpose(1, 2)
590
+
591
+ past_key_value = getattr(self, "past_key_value", past_key_value)
592
+ cos, sin = self.rotary_emb(value_states, position_ids)
593
+ query_states, key_states = apply_rotary_pos_emb(
594
+ query_states, key_states, cos, sin
595
+ )
596
+
597
+ if past_key_value is not None:
598
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
599
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
600
+ key_states, value_states = past_key_value.update(
601
+ key_states, value_states, self.layer_idx, cache_kwargs
602
+ )
603
+
604
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
605
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
606
+
607
+ attn_weights = torch.matmul(
608
+ query_states, key_states.transpose(2, 3)
609
+ ) / math.sqrt(self.head_dim)
610
+
611
+ if attention_mask is not None: # no matter the length, we just slice it
612
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
613
+ attn_weights = attn_weights + causal_mask
614
+
615
+ # upcast attention to fp32
616
+ attn_weights = nn.functional.softmax(
617
+ attn_weights, dim=-1, dtype=torch.float32
618
+ ).to(query_states.dtype)
619
+ attn_weights = nn.functional.dropout(
620
+ attn_weights, p=self.attention_dropout, training=self.training
621
+ )
622
+ attn_output = torch.matmul(attn_weights, value_states)
623
+
624
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
625
+ raise ValueError(
626
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
627
+ f" {attn_output.size()}"
628
+ )
629
+
630
+ attn_output = attn_output.transpose(1, 2).contiguous()
631
+
632
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
633
+
634
+ attn_output = self.inner_attn_ln(attn_output)
635
+ attn_output = self.o_proj(attn_output)
636
+
637
+ if not output_attentions:
638
+ attn_weights = None
639
+
640
+ return attn_output, attn_weights, past_key_value
641
+
642
+
643
+ class BitnetFlashAttention2(BitnetAttention):
644
+ """
645
+ Bitnet flash attention module. This module inherits from `BitnetAttention` as the weights of the module stays
646
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
647
+ flash attention and deal with padding tokens in case the input contains any of them.
648
+ """
649
+
650
+ def __init__(self, *args, **kwargs):
651
+ super().__init__(*args, **kwargs)
652
+
653
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
654
+ # 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.
655
+ # 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).
656
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
657
+
658
+ def forward(
659
+ self,
660
+ hidden_states: torch.Tensor,
661
+ attention_mask: Optional[torch.LongTensor] = None,
662
+ position_ids: Optional[torch.LongTensor] = None,
663
+ past_key_value: Optional[Cache] = None,
664
+ output_attentions: bool = False,
665
+ use_cache: bool = False,
666
+ cache_position: Optional[torch.LongTensor] = None,
667
+ **kwargs,
668
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
669
+ output_attentions = False
670
+
671
+ bsz, q_len, _ = hidden_states.size()
672
+
673
+ query_states = self.q_proj(hidden_states)
674
+ key_states = self.k_proj(hidden_states)
675
+ value_states = self.v_proj(hidden_states)
676
+
677
+ # Flash attention requires the input to have the shape
678
+ # batch_size x seq_length x head_dim x hidden_dim
679
+ # therefore we just need to keep the original shape
680
+ query_states = query_states.view(
681
+ bsz, q_len, self.num_heads, self.head_dim
682
+ ).transpose(1, 2)
683
+ key_states = key_states.view(
684
+ bsz, q_len, self.num_key_value_heads, self.head_dim
685
+ ).transpose(1, 2)
686
+ value_states = value_states.view(
687
+ bsz, q_len, self.num_key_value_heads, self.head_dim
688
+ ).transpose(1, 2)
689
+
690
+ cos, sin = self.rotary_emb(value_states, position_ids)
691
+ query_states, key_states = apply_rotary_pos_emb(
692
+ query_states, key_states, cos, sin
693
+ )
694
+
695
+ past_key_value = getattr(self, "past_key_value", past_key_value)
696
+
697
+ if past_key_value is not None:
698
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
699
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
700
+ key_states, value_states = past_key_value.update(
701
+ key_states, value_states, self.layer_idx, cache_kwargs
702
+ )
703
+
704
+ # 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
705
+ # to be able to avoid many of these transpose/reshape/view.
706
+ query_states = query_states.transpose(1, 2)
707
+ key_states = key_states.transpose(1, 2)
708
+ value_states = value_states.transpose(1, 2)
709
+
710
+ dropout_rate = self.attention_dropout if self.training else 0.0
711
+
712
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
713
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
714
+ # cast them back in the correct dtype just to be sure everything works as expected.
715
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
716
+ # in fp32. (BitnetRMSNorm handles it correctly)
717
+
718
+ input_dtype = query_states.dtype
719
+ if input_dtype == torch.float32:
720
+ if torch.is_autocast_enabled():
721
+ target_dtype = torch.get_autocast_gpu_dtype()
722
+ # Handle the case where the model is quantized
723
+ elif hasattr(self.config, "_pre_quantization_dtype"):
724
+ target_dtype = self.config._pre_quantization_dtype
725
+ else:
726
+ target_dtype = self.q_proj.weight.dtype
727
+
728
+ logger.warning_once(
729
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
730
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
731
+ f" {target_dtype}."
732
+ )
733
+
734
+ query_states = query_states.to(target_dtype)
735
+ key_states = key_states.to(target_dtype)
736
+ value_states = value_states.to(target_dtype)
737
+
738
+ attn_output = self._flash_attention_forward(
739
+ query_states,
740
+ key_states,
741
+ value_states,
742
+ attention_mask,
743
+ q_len,
744
+ dropout=dropout_rate,
745
+ )
746
+
747
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
748
+ attn_output = self.inner_attn_ln(attn_output)
749
+ attn_output = self.o_proj(attn_output)
750
+
751
+ if not output_attentions:
752
+ attn_weights = None
753
+
754
+ return attn_output, attn_weights, past_key_value
755
+
756
+ def _flash_attention_forward(
757
+ self,
758
+ query_states,
759
+ key_states,
760
+ value_states,
761
+ attention_mask,
762
+ query_length,
763
+ dropout=0.0,
764
+ softmax_scale=None,
765
+ ):
766
+ """
767
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
768
+ first unpad the input, then computes the attention scores and pad the final attention scores.
769
+
770
+ Args:
771
+ query_states (`torch.Tensor`):
772
+ Input query states to be passed to Flash Attention API
773
+ key_states (`torch.Tensor`):
774
+ Input key states to be passed to Flash Attention API
775
+ value_states (`torch.Tensor`):
776
+ Input value states to be passed to Flash Attention API
777
+ attention_mask (`torch.Tensor`):
778
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
779
+ position of padding tokens and 1 for the position of non-padding tokens.
780
+ dropout (`float`):
781
+ Attention dropout
782
+ softmax_scale (`float`, *optional*):
783
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
784
+ """
785
+ if not self._flash_attn_uses_top_left_mask:
786
+ causal = self.is_causal
787
+ else:
788
+ # 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__.
789
+ causal = self.is_causal and query_length != 1
790
+
791
+ # Contains at least one padding token in the sequence
792
+ if attention_mask is not None:
793
+ batch_size = query_states.shape[0]
794
+ (
795
+ query_states,
796
+ key_states,
797
+ value_states,
798
+ indices_q,
799
+ cu_seq_lens,
800
+ max_seq_lens,
801
+ ) = self._upad_input(
802
+ query_states, key_states, value_states, attention_mask, query_length
803
+ )
804
+
805
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
806
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
807
+
808
+ attn_output_unpad = flash_attn_varlen_func(
809
+ query_states,
810
+ key_states,
811
+ value_states,
812
+ cu_seqlens_q=cu_seqlens_q,
813
+ cu_seqlens_k=cu_seqlens_k,
814
+ max_seqlen_q=max_seqlen_in_batch_q,
815
+ max_seqlen_k=max_seqlen_in_batch_k,
816
+ dropout_p=dropout,
817
+ softmax_scale=softmax_scale,
818
+ causal=causal,
819
+ )
820
+
821
+ attn_output = pad_input(
822
+ attn_output_unpad, indices_q, batch_size, query_length
823
+ )
824
+ else:
825
+ attn_output = flash_attn_func(
826
+ query_states,
827
+ key_states,
828
+ value_states,
829
+ dropout,
830
+ softmax_scale=softmax_scale,
831
+ causal=causal,
832
+ )
833
+
834
+ return attn_output
835
+
836
+ def _upad_input(
837
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
838
+ ):
839
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
840
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
841
+
842
+ key_layer = index_first_axis(
843
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
844
+ indices_k,
845
+ )
846
+ value_layer = index_first_axis(
847
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
848
+ indices_k,
849
+ )
850
+ if query_length == kv_seq_len:
851
+ query_layer = index_first_axis(
852
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
853
+ indices_k,
854
+ )
855
+ cu_seqlens_q = cu_seqlens_k
856
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
857
+ indices_q = indices_k
858
+ elif query_length == 1:
859
+ max_seqlen_in_batch_q = 1
860
+ cu_seqlens_q = torch.arange(
861
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
862
+ ) # There is a memcpy here, that is very bad.
863
+ indices_q = cu_seqlens_q[:-1]
864
+ query_layer = query_layer.squeeze(1)
865
+ else:
866
+ # The -q_len: slice assumes left padding.
867
+ attention_mask = attention_mask[:, -query_length:]
868
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
869
+ query_layer, attention_mask
870
+ )
871
+
872
+ return (
873
+ query_layer,
874
+ key_layer,
875
+ value_layer,
876
+ indices_q,
877
+ (cu_seqlens_q, cu_seqlens_k),
878
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
879
+ )
880
+
881
+
882
+ LLAMA_ATTENTION_CLASSES = {
883
+ "eager": BitnetAttention,
884
+ "flash_attention_2": BitnetFlashAttention2,
885
+ }
886
+
887
+
888
+ class BitnetDecoderLayer(nn.Module):
889
+ def __init__(self, config: BitnetConfig, layer_idx: int):
890
+ super().__init__()
891
+ self.hidden_size = config.hidden_size
892
+
893
+ self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](
894
+ config=config, layer_idx=layer_idx
895
+ )
896
+
897
+ self.mlp = BitnetMLP(config)
898
+ self.input_layernorm = BitnetRMSNorm(
899
+ config.hidden_size, eps=config.rms_norm_eps
900
+ )
901
+ self.post_attention_layernorm = BitnetRMSNorm(
902
+ config.hidden_size, eps=config.rms_norm_eps
903
+ )
904
+
905
+ def quantize(self, quant_bits=2, group_size=128):
906
+ self.self_attn.quantize(quant_bits, group_size)
907
+ self.mlp.quantize(quant_bits, group_size)
908
+
909
+ def forward(
910
+ self,
911
+ hidden_states: torch.Tensor,
912
+ attention_mask: Optional[torch.Tensor] = None,
913
+ position_ids: Optional[torch.LongTensor] = None,
914
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
915
+ output_attentions: Optional[bool] = False,
916
+ use_cache: Optional[bool] = False,
917
+ cache_position: Optional[torch.LongTensor] = None,
918
+ **kwargs,
919
+ ) -> Tuple[
920
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
921
+ ]:
922
+ """
923
+ Args:
924
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
925
+ attention_mask (`torch.FloatTensor`, *optional*):
926
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
927
+ query_sequence_length, key_sequence_length)` if default attention is used.
928
+ output_attentions (`bool`, *optional*):
929
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
930
+ returned tensors for more detail.
931
+ use_cache (`bool`, *optional*):
932
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
933
+ (see `past_key_values`).
934
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
935
+ """
936
+ if "padding_mask" in kwargs:
937
+ warnings.warn(
938
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
939
+ )
940
+
941
+ residual = hidden_states
942
+
943
+ hidden_states = self.input_layernorm(hidden_states)
944
+
945
+ # Self Attention
946
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
947
+ hidden_states=hidden_states,
948
+ attention_mask=attention_mask,
949
+ position_ids=position_ids,
950
+ past_key_value=past_key_value,
951
+ output_attentions=output_attentions,
952
+ use_cache=use_cache,
953
+ cache_position=cache_position,
954
+ **kwargs,
955
+ )
956
+ hidden_states = residual + hidden_states
957
+
958
+ # Fully Connected
959
+ residual = hidden_states
960
+ hidden_states = self.post_attention_layernorm(hidden_states)
961
+ hidden_states = self.mlp(hidden_states)
962
+ hidden_states = residual + hidden_states
963
+
964
+ outputs = (hidden_states,)
965
+
966
+ if output_attentions:
967
+ outputs += (self_attn_weights,)
968
+
969
+ if use_cache:
970
+ outputs += (present_key_value,)
971
+
972
+ return outputs
973
+
974
+
975
+ LLAMA_START_DOCSTRING = r"""
976
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
977
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
978
+ etc.)
979
+
980
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
981
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
982
+ and behavior.
983
+
984
+ Parameters:
985
+ config ([`BitnetConfig`]):
986
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
987
+ load the weights associated with the model, only the configuration. Check out the
988
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
989
+ """
990
+
991
+
992
+ @add_start_docstrings(
993
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
994
+ LLAMA_START_DOCSTRING,
995
+ )
996
+ class BitnetPreTrainedModel(PreTrainedModel):
997
+ config_class = BitnetConfig
998
+ base_model_prefix = "model"
999
+ supports_gradient_checkpointing = True
1000
+ _no_split_modules = ["BitnetDecoderLayer"]
1001
+ _skip_keys_device_placement = ["past_key_values"]
1002
+ _supports_flash_attn_2 = True
1003
+ _supports_sdpa = False
1004
+ _supports_cache_class = True
1005
+
1006
+ def _init_weights(self, module):
1007
+ std = self.config.initializer_range
1008
+ if isinstance(module, nn.Linear):
1009
+ module.weight.data.normal_(mean=0.0, std=std)
1010
+ if module.bias is not None:
1011
+ module.bias.data.zero_()
1012
+ elif isinstance(module, nn.Embedding):
1013
+ module.weight.data.normal_(mean=0.0, std=std)
1014
+ if module.padding_idx is not None:
1015
+ module.weight.data[module.padding_idx].zero_()
1016
+
1017
+ def _setup_cache(
1018
+ self, cache_cls, max_batch_size, max_cache_len: Optional[int] = None
1019
+ ):
1020
+ if (
1021
+ self.config._attn_implementation == "flash_attention_2"
1022
+ and cache_cls == StaticCache
1023
+ ):
1024
+ raise ValueError(
1025
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
1026
+ "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
1027
+ )
1028
+
1029
+ for layer in self.model.layers:
1030
+ device = layer.input_layernorm.weight.device
1031
+ if hasattr(self.config, "_pre_quantization_dtype"):
1032
+ dtype = self.config._pre_quantization_dtype
1033
+ else:
1034
+ dtype = layer.self_attn.o_proj.weight.dtype
1035
+ layer.self_attn.past_key_value = cache_cls(
1036
+ self.config, max_batch_size, max_cache_len, device=device, dtype=dtype
1037
+ )
1038
+
1039
+ def _reset_cache(self):
1040
+ for layer in self.model.layers:
1041
+ layer.self_attn.past_key_value = None
1042
+
1043
+
1044
+ LLAMA_INPUTS_DOCSTRING = r"""
1045
+ Args:
1046
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1047
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1048
+ it.
1049
+
1050
+ Indices can be obtained using [`BitnetTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1051
+ [`PreTrainedTokenizer.__call__`] for details.
1052
+
1053
+ [What are input IDs?](../glossary#input-ids)
1054
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1055
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1056
+
1057
+ - 1 for tokens that are **not masked**,
1058
+ - 0 for tokens that are **masked**.
1059
+
1060
+ [What are attention masks?](../glossary#attention-mask)
1061
+
1062
+ Indices can be obtained using [`BitnetTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1063
+ [`PreTrainedTokenizer.__call__`] for details.
1064
+
1065
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1066
+ `past_key_values`).
1067
+
1068
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1069
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1070
+ information on the default strategy.
1071
+
1072
+ - 1 indicates the head is **not masked**,
1073
+ - 0 indicates the head is **masked**.
1074
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1075
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1076
+ config.n_positions - 1]`.
1077
+
1078
+ [What are position IDs?](../glossary#position-ids)
1079
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1080
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1081
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1082
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1083
+
1084
+ Two formats are allowed:
1085
+ - a [`~cache_utils.Cache`] instance;
1086
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1087
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1088
+ cache format.
1089
+
1090
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1091
+ legacy cache format will be returned.
1092
+
1093
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1094
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1095
+ of shape `(batch_size, sequence_length)`.
1096
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1097
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1098
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1099
+ model's internal embedding lookup matrix.
1100
+ use_cache (`bool`, *optional*):
1101
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1102
+ `past_key_values`).
1103
+ output_attentions (`bool`, *optional*):
1104
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1105
+ tensors for more detail.
1106
+ output_hidden_states (`bool`, *optional*):
1107
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1108
+ more detail.
1109
+ return_dict (`bool`, *optional*):
1110
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1111
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
1112
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
1113
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
1114
+ the complete sequence length.
1115
+ """
1116
+
1117
+
1118
+ @add_start_docstrings(
1119
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
1120
+ LLAMA_START_DOCSTRING,
1121
+ )
1122
+ class BitnetModel(BitnetPreTrainedModel):
1123
+ """
1124
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`BitnetDecoderLayer`]
1125
+
1126
+ Args:
1127
+ config: BitnetConfig
1128
+ """
1129
+
1130
+ def __init__(self, config: BitnetConfig):
1131
+ super().__init__(config)
1132
+ self.padding_idx = config.pad_token_id
1133
+ self.vocab_size = config.vocab_size
1134
+
1135
+ self.embed_tokens = nn.Embedding(
1136
+ config.vocab_size, config.hidden_size, self.padding_idx
1137
+ )
1138
+ self.layers = nn.ModuleList(
1139
+ [
1140
+ BitnetDecoderLayer(config, layer_idx)
1141
+ for layer_idx in range(config.num_hidden_layers)
1142
+ ]
1143
+ )
1144
+ self.norm = BitnetRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1145
+ self.gradient_checkpointing = False
1146
+
1147
+ # Initialize weights and apply final processing
1148
+ self.post_init()
1149
+
1150
+ def get_input_embeddings(self):
1151
+ return self.embed_tokens
1152
+
1153
+ def set_input_embeddings(self, value):
1154
+ self.embed_tokens = value
1155
+
1156
+ def quantize(self, quant_bits=2, group_size=128):
1157
+ for layer in self.layers:
1158
+ layer.quantize(quant_bits, group_size)
1159
+
1160
+ self.config.quant_bits = quant_bits
1161
+ self.config.group_size = group_size
1162
+
1163
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1164
+ def forward(
1165
+ self,
1166
+ input_ids: torch.LongTensor = None,
1167
+ attention_mask: Optional[torch.Tensor] = None,
1168
+ position_ids: Optional[torch.LongTensor] = None,
1169
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1170
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1171
+ use_cache: Optional[bool] = None,
1172
+ output_attentions: Optional[bool] = None,
1173
+ output_hidden_states: Optional[bool] = None,
1174
+ return_dict: Optional[bool] = None,
1175
+ cache_position: Optional[torch.LongTensor] = None,
1176
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1177
+ output_attentions = (
1178
+ output_attentions
1179
+ if output_attentions is not None
1180
+ else self.config.output_attentions
1181
+ )
1182
+ output_hidden_states = (
1183
+ output_hidden_states
1184
+ if output_hidden_states is not None
1185
+ else self.config.output_hidden_states
1186
+ )
1187
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1188
+ return_dict = (
1189
+ return_dict if return_dict is not None else self.config.use_return_dict
1190
+ )
1191
+
1192
+ if (input_ids is None) ^ (inputs_embeds is not None):
1193
+ raise ValueError(
1194
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
1195
+ )
1196
+
1197
+ if self.gradient_checkpointing and self.training and use_cache:
1198
+ logger.warning_once(
1199
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
1200
+ )
1201
+ use_cache = False
1202
+
1203
+ if inputs_embeds is None:
1204
+ inputs_embeds = self.embed_tokens(input_ids)
1205
+
1206
+ past_seen_tokens = 0
1207
+ if use_cache: # kept for BC (cache positions)
1208
+ if not isinstance(past_key_values, StaticCache):
1209
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1210
+ past_seen_tokens = past_key_values.get_seq_length()
1211
+
1212
+ if cache_position is None:
1213
+ if isinstance(past_key_values, StaticCache):
1214
+ raise ValueError(
1215
+ "cache_position is a required argument when using StaticCache."
1216
+ )
1217
+ cache_position = torch.arange(
1218
+ past_seen_tokens,
1219
+ past_seen_tokens + inputs_embeds.shape[1],
1220
+ device=inputs_embeds.device,
1221
+ )
1222
+
1223
+ if position_ids is None:
1224
+ position_ids = cache_position.unsqueeze(0)
1225
+
1226
+ causal_mask = self._update_causal_mask(
1227
+ attention_mask, inputs_embeds, cache_position
1228
+ )
1229
+
1230
+ # embed positions
1231
+ hidden_states = inputs_embeds
1232
+
1233
+ # decoder layers
1234
+ all_hidden_states = () if output_hidden_states else None
1235
+ all_self_attns = () if output_attentions else None
1236
+ next_decoder_cache = None
1237
+
1238
+ for decoder_layer in self.layers:
1239
+ if output_hidden_states:
1240
+ all_hidden_states += (hidden_states,)
1241
+
1242
+ if self.gradient_checkpointing and self.training:
1243
+ layer_outputs = self._gradient_checkpointing_func(
1244
+ decoder_layer.__call__,
1245
+ hidden_states,
1246
+ causal_mask,
1247
+ position_ids,
1248
+ past_key_values,
1249
+ output_attentions,
1250
+ use_cache,
1251
+ cache_position,
1252
+ )
1253
+ else:
1254
+ layer_outputs = decoder_layer(
1255
+ hidden_states,
1256
+ attention_mask=causal_mask,
1257
+ position_ids=position_ids,
1258
+ past_key_value=past_key_values,
1259
+ output_attentions=output_attentions,
1260
+ use_cache=use_cache,
1261
+ cache_position=cache_position,
1262
+ )
1263
+
1264
+ hidden_states = layer_outputs[0]
1265
+
1266
+ if use_cache:
1267
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1268
+
1269
+ if output_attentions:
1270
+ all_self_attns += (layer_outputs[1],)
1271
+
1272
+ hidden_states = self.norm(hidden_states)
1273
+
1274
+ # add hidden states from the last decoder layer
1275
+ if output_hidden_states:
1276
+ all_hidden_states += (hidden_states,)
1277
+
1278
+ next_cache = None
1279
+ if use_cache:
1280
+ next_cache = (
1281
+ next_decoder_cache.to_legacy_cache()
1282
+ if isinstance(next_decoder_cache, Cache)
1283
+ else next_decoder_cache
1284
+ )
1285
+ if not return_dict:
1286
+ return tuple(
1287
+ v
1288
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1289
+ if v is not None
1290
+ )
1291
+ return BaseModelOutputWithPast(
1292
+ last_hidden_state=hidden_states,
1293
+ past_key_values=next_cache,
1294
+ hidden_states=all_hidden_states,
1295
+ attentions=all_self_attns,
1296
+ )
1297
+
1298
+ # 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
1299
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
1300
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
1301
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
1302
+ def _update_causal_mask(self, attention_mask, input_tensor, cache_position):
1303
+ if self.config._attn_implementation == "flash_attention_2":
1304
+ if attention_mask is not None and 0.0 in attention_mask:
1305
+ return attention_mask
1306
+ return None
1307
+
1308
+ dtype, device = input_tensor.dtype, input_tensor.device
1309
+ min_dtype = torch.finfo(dtype).min
1310
+ sequence_length = input_tensor.shape[1]
1311
+ if hasattr(self.layers[0].self_attn, "past_key_value"): # static cache
1312
+ target_length = self.config.max_position_embeddings
1313
+ else: # dynamic cache
1314
+ target_length = (
1315
+ attention_mask.shape[-1]
1316
+ if isinstance(attention_mask, torch.Tensor)
1317
+ else cache_position[-1] + 1
1318
+ )
1319
+
1320
+ causal_mask = torch.full(
1321
+ (sequence_length, target_length),
1322
+ fill_value=min_dtype,
1323
+ dtype=dtype,
1324
+ device=device,
1325
+ )
1326
+ if sequence_length != 1:
1327
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1328
+ causal_mask *= torch.arange(
1329
+ target_length, device=device
1330
+ ) > cache_position.reshape(-1, 1)
1331
+ causal_mask = causal_mask[None, None, :, :].expand(
1332
+ input_tensor.shape[0], 1, -1, -1
1333
+ )
1334
+ if attention_mask is not None:
1335
+ causal_mask = (
1336
+ causal_mask.clone()
1337
+ ) # copy to contiguous memory for in-place edit
1338
+ if attention_mask.dim() == 2:
1339
+ mask_length = attention_mask.shape[-1]
1340
+ padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[
1341
+ :, None, None, :
1342
+ ].eq(0.0)
1343
+ causal_mask[..., :mask_length] = causal_mask[
1344
+ ..., :mask_length
1345
+ ].masked_fill(padding_mask, min_dtype)
1346
+ elif attention_mask.dim() == 4:
1347
+ # backwards compatibility: we allow passing a 4D attention mask shorter than the input length with
1348
+ # cache. In that case, the 4D attention mask attends to the newest tokens only.
1349
+ if attention_mask.shape[-2] < cache_position[0] + sequence_length:
1350
+ offset = cache_position[0]
1351
+ else:
1352
+ offset = 0
1353
+ mask_shape = attention_mask.shape
1354
+ mask_slice = (attention_mask.eq(0.0)).to(dtype=dtype) * min_dtype
1355
+ causal_mask[
1356
+ : mask_shape[0],
1357
+ : mask_shape[1],
1358
+ offset : mask_shape[2] + offset,
1359
+ : mask_shape[3],
1360
+ ] = mask_slice
1361
+
1362
+ return causal_mask
1363
+
1364
+
1365
+ class BitnetForCausalLM(BitnetPreTrainedModel):
1366
+ _tied_weights_keys = ["lm_head.weight"]
1367
+
1368
+ def __init__(self, config):
1369
+ super().__init__(config)
1370
+ self.model = BitnetModel(config)
1371
+ self.vocab_size = config.vocab_size
1372
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1373
+
1374
+ # Initialize weights and apply final processing
1375
+ self.post_init()
1376
+
1377
+ def get_input_embeddings(self):
1378
+ return self.model.embed_tokens
1379
+
1380
+ def set_input_embeddings(self, value):
1381
+ self.model.embed_tokens = value
1382
+
1383
+ def get_output_embeddings(self):
1384
+ return self.lm_head
1385
+
1386
+ def set_output_embeddings(self, new_embeddings):
1387
+ self.lm_head = new_embeddings
1388
+
1389
+ def set_decoder(self, decoder):
1390
+ self.model = decoder
1391
+
1392
+ def get_decoder(self):
1393
+ return self.model
1394
+
1395
+ def quantize(self, quant_bits=2, group_size=128):
1396
+ self.model.quantize(quant_bits, group_size)
1397
+
1398
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1399
+ @replace_return_docstrings(
1400
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1401
+ )
1402
+ def forward(
1403
+ self,
1404
+ input_ids: torch.LongTensor = None,
1405
+ attention_mask: Optional[torch.Tensor] = None,
1406
+ position_ids: Optional[torch.LongTensor] = None,
1407
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1408
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1409
+ labels: Optional[torch.LongTensor] = None,
1410
+ use_cache: Optional[bool] = None,
1411
+ output_attentions: Optional[bool] = None,
1412
+ output_hidden_states: Optional[bool] = None,
1413
+ return_dict: Optional[bool] = None,
1414
+ cache_position: Optional[torch.LongTensor] = None,
1415
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1416
+ r"""
1417
+ Args:
1418
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1419
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1420
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1421
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1422
+
1423
+ Returns:
1424
+
1425
+ Example:
1426
+
1427
+ ```python
1428
+ >>> from transformers import LlamaTokenizer, LlamaForCausalLM
1429
+
1430
+ >>> model = LlamaForCausalLM.from_pretrained("meta-llama/Bitnet-2-7b-hf")
1431
+ >>> tokenizer = LlamaTokenizer.from_pretrained("meta-llama/Bitnet-2-7b-hf")
1432
+
1433
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1434
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1435
+
1436
+ >>> # Generate
1437
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1438
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1439
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1440
+ ```"""
1441
+ output_attentions = (
1442
+ output_attentions
1443
+ if output_attentions is not None
1444
+ else self.config.output_attentions
1445
+ )
1446
+ output_hidden_states = (
1447
+ output_hidden_states
1448
+ if output_hidden_states is not None
1449
+ else self.config.output_hidden_states
1450
+ )
1451
+ return_dict = (
1452
+ return_dict if return_dict is not None else self.config.use_return_dict
1453
+ )
1454
+
1455
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1456
+ outputs = self.model(
1457
+ input_ids=input_ids,
1458
+ attention_mask=attention_mask,
1459
+ position_ids=position_ids,
1460
+ past_key_values=past_key_values,
1461
+ inputs_embeds=inputs_embeds,
1462
+ use_cache=use_cache,
1463
+ output_attentions=output_attentions,
1464
+ output_hidden_states=output_hidden_states,
1465
+ return_dict=return_dict,
1466
+ cache_position=cache_position,
1467
+ )
1468
+
1469
+ hidden_states = outputs[0]
1470
+ logits = self.lm_head(hidden_states)
1471
+ logits = logits.float()
1472
+
1473
+ loss = None
1474
+ if labels is not None:
1475
+ # Shift so that tokens < n predict n
1476
+ shift_logits = logits[..., :-1, :].contiguous()
1477
+ shift_labels = labels[..., 1:].contiguous()
1478
+ # Flatten the tokens
1479
+ loss_fct = CrossEntropyLoss()
1480
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1481
+ shift_labels = shift_labels.view(-1)
1482
+ # Enable model parallelism
1483
+ shift_labels = shift_labels.to(shift_logits.device)
1484
+ loss = loss_fct(shift_logits, shift_labels)
1485
+
1486
+ if not return_dict:
1487
+ output = (logits,) + outputs[1:]
1488
+ return (loss,) + output if loss is not None else output
1489
+
1490
+ return CausalLMOutputWithPast(
1491
+ loss=loss,
1492
+ logits=logits,
1493
+ past_key_values=outputs.past_key_values,
1494
+ hidden_states=outputs.hidden_states,
1495
+ attentions=outputs.attentions,
1496
+ )
1497
+
1498
+ def prepare_inputs_for_generation(
1499
+ self,
1500
+ input_ids,
1501
+ past_key_values=None,
1502
+ attention_mask=None,
1503
+ inputs_embeds=None,
1504
+ cache_position=None,
1505
+ **kwargs,
1506
+ ):
1507
+ # With static cache, the `past_key_values` is None
1508
+ # TODO joao: standardize interface for the different Cache classes and remove of this if
1509
+ has_static_cache = False
1510
+ if past_key_values is None:
1511
+ past_key_values = getattr(
1512
+ self.model.layers[0].self_attn, "past_key_value", None
1513
+ )
1514
+ has_static_cache = past_key_values is not None
1515
+
1516
+ past_length = 0
1517
+ if past_key_values is not None:
1518
+ if isinstance(past_key_values, Cache):
1519
+ past_length = (
1520
+ cache_position[0]
1521
+ if cache_position is not None
1522
+ else past_key_values.get_seq_length()
1523
+ )
1524
+ max_cache_length = (
1525
+ torch.tensor(
1526
+ past_key_values.get_max_length(), device=input_ids.device
1527
+ )
1528
+ if past_key_values.get_max_length() is not None
1529
+ else None
1530
+ )
1531
+ cache_length = (
1532
+ past_length
1533
+ if max_cache_length is None
1534
+ else torch.min(max_cache_length, past_length)
1535
+ )
1536
+ # TODO joao: remove this `else` after `generate` prioritizes `Cache` objects
1537
+ else:
1538
+ cache_length = past_length = past_key_values[0][0].shape[2]
1539
+ max_cache_length = None
1540
+
1541
+ # Keep only the unprocessed tokens:
1542
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1543
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1544
+ # input)
1545
+ if (
1546
+ attention_mask is not None
1547
+ and attention_mask.shape[1] > input_ids.shape[1]
1548
+ ):
1549
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1550
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1551
+ # input_ids based on the past_length.
1552
+ elif past_length < input_ids.shape[1]:
1553
+ input_ids = input_ids[:, past_length:]
1554
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1555
+
1556
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1557
+ if (
1558
+ max_cache_length is not None
1559
+ and attention_mask is not None
1560
+ and cache_length + input_ids.shape[1] > max_cache_length
1561
+ ):
1562
+ attention_mask = attention_mask[:, -max_cache_length:]
1563
+
1564
+ position_ids = kwargs.get("position_ids", None)
1565
+ if attention_mask is not None and position_ids is None:
1566
+ # create position_ids on the fly for batch generation
1567
+ position_ids = attention_mask.long().cumsum(-1) - 1
1568
+ position_ids.masked_fill_(attention_mask == 0, 1)
1569
+ if past_key_values:
1570
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1571
+
1572
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1573
+ if inputs_embeds is not None and past_key_values is None:
1574
+ model_inputs = {"inputs_embeds": inputs_embeds}
1575
+ else:
1576
+ # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
1577
+ # recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
1578
+ # TODO: use `next_tokens` directly instead.
1579
+ model_inputs = {"input_ids": input_ids.contiguous()}
1580
+
1581
+ input_length = (
1582
+ position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
1583
+ )
1584
+ if cache_position is None:
1585
+ cache_position = torch.arange(
1586
+ past_length, past_length + input_length, device=input_ids.device
1587
+ )
1588
+ else:
1589
+ cache_position = cache_position[-input_length:]
1590
+
1591
+ if has_static_cache:
1592
+ past_key_values = None
1593
+
1594
+ model_inputs.update(
1595
+ {
1596
+ "position_ids": position_ids,
1597
+ "cache_position": cache_position,
1598
+ "past_key_values": past_key_values,
1599
+ "use_cache": kwargs.get("use_cache"),
1600
+ "attention_mask": attention_mask,
1601
+ }
1602
+ )
1603
+ return model_inputs
1604
+
1605
+ @staticmethod
1606
+ def _reorder_cache(past_key_values, beam_idx):
1607
+ reordered_past = ()
1608
+ for layer_past in past_key_values:
1609
+ reordered_past += (
1610
+ tuple(
1611
+ past_state.index_select(0, beam_idx.to(past_state.device))
1612
+ for past_state in layer_past
1613
+ ),
1614
+ )
1615
+ return reordered_past
1616
+
1617
+
1618
+ @add_start_docstrings(
1619
+ """
1620
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
1621
+
1622
+ [`BitnetForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1623
+ (e.g. GPT-2) do.
1624
+
1625
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1626
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1627
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1628
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1629
+ each row of the batch).
1630
+ """,
1631
+ LLAMA_START_DOCSTRING,
1632
+ )
1633
+ class BitnetForSequenceClassification(BitnetPreTrainedModel):
1634
+ def __init__(self, config):
1635
+ super().__init__(config)
1636
+ self.num_labels = config.num_labels
1637
+ self.model = BitnetModel(config)
1638
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1639
+
1640
+ # Initialize weights and apply final processing
1641
+ self.post_init()
1642
+
1643
+ def get_input_embeddings(self):
1644
+ return self.model.embed_tokens
1645
+
1646
+ def set_input_embeddings(self, value):
1647
+ self.model.embed_tokens = value
1648
+
1649
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1650
+ def forward(
1651
+ self,
1652
+ input_ids: torch.LongTensor = None,
1653
+ attention_mask: Optional[torch.Tensor] = None,
1654
+ position_ids: Optional[torch.LongTensor] = None,
1655
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1656
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1657
+ labels: Optional[torch.LongTensor] = None,
1658
+ use_cache: Optional[bool] = None,
1659
+ output_attentions: Optional[bool] = None,
1660
+ output_hidden_states: Optional[bool] = None,
1661
+ return_dict: Optional[bool] = None,
1662
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1663
+ r"""
1664
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1665
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1666
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1667
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1668
+ """
1669
+ return_dict = (
1670
+ return_dict if return_dict is not None else self.config.use_return_dict
1671
+ )
1672
+
1673
+ transformer_outputs = self.model(
1674
+ input_ids,
1675
+ attention_mask=attention_mask,
1676
+ position_ids=position_ids,
1677
+ past_key_values=past_key_values,
1678
+ inputs_embeds=inputs_embeds,
1679
+ use_cache=use_cache,
1680
+ output_attentions=output_attentions,
1681
+ output_hidden_states=output_hidden_states,
1682
+ return_dict=return_dict,
1683
+ )
1684
+ hidden_states = transformer_outputs[0]
1685
+ logits = self.score(hidden_states)
1686
+
1687
+ if input_ids is not None:
1688
+ batch_size = input_ids.shape[0]
1689
+ else:
1690
+ batch_size = inputs_embeds.shape[0]
1691
+
1692
+ if self.config.pad_token_id is None and batch_size != 1:
1693
+ raise ValueError(
1694
+ "Cannot handle batch sizes > 1 if no padding token is defined."
1695
+ )
1696
+ if self.config.pad_token_id is None:
1697
+ sequence_lengths = -1
1698
+ else:
1699
+ if input_ids is not None:
1700
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1701
+ sequence_lengths = (
1702
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1703
+ )
1704
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1705
+ sequence_lengths = sequence_lengths.to(logits.device)
1706
+ else:
1707
+ sequence_lengths = -1
1708
+
1709
+ pooled_logits = logits[
1710
+ torch.arange(batch_size, device=logits.device), sequence_lengths
1711
+ ]
1712
+
1713
+ loss = None
1714
+ if labels is not None:
1715
+ labels = labels.to(logits.device)
1716
+ if self.config.problem_type is None:
1717
+ if self.num_labels == 1:
1718
+ self.config.problem_type = "regression"
1719
+ elif self.num_labels > 1 and (
1720
+ labels.dtype == torch.long or labels.dtype == torch.int
1721
+ ):
1722
+ self.config.problem_type = "single_label_classification"
1723
+ else:
1724
+ self.config.problem_type = "multi_label_classification"
1725
+
1726
+ if self.config.problem_type == "regression":
1727
+ loss_fct = MSELoss()
1728
+ if self.num_labels == 1:
1729
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1730
+ else:
1731
+ loss = loss_fct(pooled_logits, labels)
1732
+ elif self.config.problem_type == "single_label_classification":
1733
+ loss_fct = CrossEntropyLoss()
1734
+ loss = loss_fct(
1735
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
1736
+ )
1737
+ elif self.config.problem_type == "multi_label_classification":
1738
+ loss_fct = BCEWithLogitsLoss()
1739
+ loss = loss_fct(pooled_logits, labels)
1740
+ if not return_dict:
1741
+ output = (pooled_logits,) + transformer_outputs[1:]
1742
+ return ((loss,) + output) if loss is not None else output
1743
+
1744
+ return SequenceClassifierOutputWithPast(
1745
+ loss=loss,
1746
+ logits=pooled_logits,
1747
+ past_key_values=transformer_outputs.past_key_values,
1748
+ hidden_states=transformer_outputs.hidden_states,
1749
+ attentions=transformer_outputs.attentions,
1750
+ )
1751
+
1752
+
1753
+ @add_start_docstrings(
1754
+ """
1755
+ The Bitnet Model transformer with a span classification head on top for extractive question-answering tasks like
1756
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1757
+ """,
1758
+ LLAMA_START_DOCSTRING,
1759
+ )
1760
+ class BitnetForQuestionAnswering(BitnetPreTrainedModel):
1761
+ base_model_prefix = "transformer"
1762
+
1763
+ # Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->Bitnet
1764
+ def __init__(self, config):
1765
+ super().__init__(config)
1766
+ self.transformer = BitnetModel(config)
1767
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1768
+
1769
+ # Initialize weights and apply final processing
1770
+ self.post_init()
1771
+
1772
+ def get_input_embeddings(self):
1773
+ return self.transformer.embed_tokens
1774
+
1775
+ def set_input_embeddings(self, value):
1776
+ self.transformer.embed_tokens = value
1777
+
1778
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1779
+ def forward(
1780
+ self,
1781
+ input_ids: Optional[torch.LongTensor] = None,
1782
+ attention_mask: Optional[torch.FloatTensor] = None,
1783
+ position_ids: Optional[torch.LongTensor] = None,
1784
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1785
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1786
+ start_positions: Optional[torch.LongTensor] = None,
1787
+ end_positions: Optional[torch.LongTensor] = None,
1788
+ output_attentions: Optional[bool] = None,
1789
+ output_hidden_states: Optional[bool] = None,
1790
+ return_dict: Optional[bool] = None,
1791
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1792
+ r"""
1793
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1794
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1795
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1796
+ are not taken into account for computing the loss.
1797
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1798
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1799
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1800
+ are not taken into account for computing the loss.
1801
+ """
1802
+ return_dict = (
1803
+ return_dict if return_dict is not None else self.config.use_return_dict
1804
+ )
1805
+
1806
+ outputs = self.transformer(
1807
+ input_ids,
1808
+ attention_mask=attention_mask,
1809
+ position_ids=position_ids,
1810
+ past_key_values=past_key_values,
1811
+ inputs_embeds=inputs_embeds,
1812
+ output_attentions=output_attentions,
1813
+ output_hidden_states=output_hidden_states,
1814
+ return_dict=return_dict,
1815
+ )
1816
+
1817
+ sequence_output = outputs[0]
1818
+
1819
+ logits = self.qa_outputs(sequence_output)
1820
+ start_logits, end_logits = logits.split(1, dim=-1)
1821
+ start_logits = start_logits.squeeze(-1).contiguous()
1822
+ end_logits = end_logits.squeeze(-1).contiguous()
1823
+
1824
+ total_loss = None
1825
+ if start_positions is not None and end_positions is not None:
1826
+ # If we are on multi-GPU, split add a dimension
1827
+ if len(start_positions.size()) > 1:
1828
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1829
+ if len(end_positions.size()) > 1:
1830
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1831
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1832
+ ignored_index = start_logits.size(1)
1833
+ start_positions = start_positions.clamp(0, ignored_index)
1834
+ end_positions = end_positions.clamp(0, ignored_index)
1835
+
1836
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1837
+ start_loss = loss_fct(start_logits, start_positions)
1838
+ end_loss = loss_fct(end_logits, end_positions)
1839
+ total_loss = (start_loss + end_loss) / 2
1840
+
1841
+ if not return_dict:
1842
+ output = (start_logits, end_logits) + outputs[2:]
1843
+ return ((total_loss,) + output) if total_loss is not None else output
1844
+
1845
+ return QuestionAnsweringModelOutput(
1846
+ loss=total_loss,
1847
+ start_logits=start_logits,
1848
+ end_logits=end_logits,
1849
+ hidden_states=outputs.hidden_states,
1850
+ attentions=outputs.attentions,
1851
+ )
quantization.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ import torch
4
+
5
+ from modeling_bitnet import BitnetForCausalLM
6
+ from tokenization_bitnet import BitnetTokenizer
7
+
8
+ torch.set_grad_enabled(False)
9
+
10
+
11
+ parser = argparse.ArgumentParser()
12
+ parser.add_argument("--hf_path", default="1bitLLM/bitnet_b1_58-3B", type=str)
13
+ parser.add_argument("--output_path", default="./bitnet_b1_58-3B_quantized", type=str)
14
+
15
+
16
+ def main(args):
17
+ model = BitnetForCausalLM.from_pretrained(
18
+ args.hf_path,
19
+ device_map="auto",
20
+ low_cpu_mem_usage=True,
21
+ use_flash_attention_2=True,
22
+ torch_dtype=torch.float16,
23
+ ).half()
24
+ tokenizer = BitnetTokenizer.from_pretrained(args.hf_path, use_fast=False)
25
+
26
+ model.quantize()
27
+
28
+ model.save_pretrained(args.output_path, max_shard_size="5GB")
29
+
30
+ print("Quantized model saved to", args.output_path)
31
+
32
+
33
+ if __name__ == "__main__":
34
+ args = parser.parse_args()
35
+ main(args)
requirements.txt ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl-py==2.1.0
2
+ accelerate==0.28.0
3
+ aiohttp==3.9.3
4
+ aiosignal==1.3.1
5
+ annotated-types==0.6.0
6
+ anyio==4.3.0
7
+ async-timeout==4.0.3
8
+ attrs==23.2.0
9
+ auto-gptq==0.7.1
10
+ bitsandbytes==0.43.0
11
+ certifi==2024.2.2
12
+ chardet==5.2.0
13
+ charset-normalizer==3.3.2
14
+ click==8.1.7
15
+ colorama==0.4.6
16
+ dataproperty==1.0.1
17
+ datasets==2.18.0
18
+ dill==0.3.8
19
+ distro==1.9.0
20
+ einops==0.7.0
21
+ exceptiongroup==1.2.0
22
+ filelock==3.13.3
23
+ flash-attn==2.5.6
24
+ frozenlist==1.4.1
25
+ fsspec==2024.2.0
26
+ gekko==1.1.0
27
+ glog==0.3.1
28
+ h11==0.14.0
29
+ hf-transfer==0.1.6
30
+ httpcore==1.0.5
31
+ httpx==0.27.0
32
+ huggingface-hub==0.22.2
33
+ idna==3.6
34
+ jinja2==3.1.3
35
+ joblib==1.3.2
36
+ jsonlines==4.0.0
37
+ lm-eval==0.3.0
38
+ markupsafe==2.1.5
39
+ mbstrdecoder==1.1.3
40
+ mpmath==1.3.0
41
+ multidict==6.0.5
42
+ multiprocess==0.70.16
43
+ networkx==3.2.1
44
+ ninja==1.11.1.1
45
+ nltk==3.8.1
46
+ numexpr==2.9.0
47
+ numpy==1.26.4
48
+ nvidia-cublas-cu12==12.1.3.1
49
+ nvidia-cuda-cupti-cu12==12.1.105
50
+ nvidia-cuda-nvrtc-cu12==12.1.105
51
+ nvidia-cuda-runtime-cu12==12.1.105
52
+ nvidia-cudnn-cu12==8.9.2.26
53
+ nvidia-cufft-cu12==11.0.2.54
54
+ nvidia-curand-cu12==10.3.2.106
55
+ nvidia-cusolver-cu12==11.4.5.107
56
+ nvidia-cusparse-cu12==12.1.0.106
57
+ nvidia-nccl-cu12==2.19.3
58
+ nvidia-nvjitlink-cu12==12.4.99
59
+ nvidia-nvtx-cu12==12.1.105
60
+ openai==1.14.3
61
+ packaging==24.0
62
+ pandas==2.2.1
63
+ pathvalidate==3.2.0
64
+ peft==0.10.0
65
+ portalocker==2.8.2
66
+ protobuf==5.26.1
67
+ psutil==5.9.8
68
+ pyarrow==15.0.2
69
+ pyarrow-hotfix==0.6
70
+ pybind11==2.12.0
71
+ pycountry==23.12.11
72
+ pydantic==2.6.4
73
+ pydantic-core==2.16.3
74
+ pytablewriter==1.2.0
75
+ python-dateutil==2.9.0.post0
76
+ python-gflags==3.1.2
77
+ pytz==2024.1
78
+ pyyaml==6.0.1
79
+ regex==2023.12.25
80
+ requests==2.31.0
81
+ rouge==1.0.1
82
+ rouge-score==0.1.2
83
+ sacrebleu==1.5.0
84
+ safetensors==0.4.2
85
+ scikit-learn==1.4.1.post1
86
+ scipy==1.12.0
87
+ sentencepiece==0.2.0
88
+ setuptools==69.2.0
89
+ six==1.16.0
90
+ sniffio==1.3.1
91
+ sqlitedict==2.1.0
92
+ sympy==1.12
93
+ tabledata==1.3.3
94
+ tcolorpy==0.1.4
95
+ threadpoolctl==3.4.0
96
+ tokenizers==0.15.2
97
+ torch==2.2.2
98
+ tqdm==4.66.2
99
+ tqdm-multiprocess==0.0.11
100
+ transformers==4.39.2
101
+ triton==2.2.0
102
+ typepy==1.3.2
103
+ typing-extensions==4.10.0
104
+ tzdata==2024.1
105
+ urllib3==2.2.1
106
+ wheel==0.43.0
107
+ xxhash==3.4.1
108
+ yarl==1.9.4
109
+ zstandard==0.22.0
show_keys.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoModelForCausalLM, AutoTokenizer
2
+
3
+ # モデル名を指定
4
+ model_name = "./"
5
+
6
+ # モデルとトークナイザーを読み込む
7
+ model = AutoModelForCausalLM.from_pretrained(model_name)
8
+ # tokenizer = AutoTokenizer.from_pretrained(model_name)
9
+
10
+ # モデルの状態ディクショナリを取得
11
+ state_dict = model.state_dict()
12
+
13
+ # weightキーを表示
14
+ for key in state_dict.keys():
15
+ if "weight" in key:
16
+ print(key)
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,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import numpy as np
4
+ import torch
5
+ import transformers
6
+ from auto_gptq.nn_modules.triton_utils.mixin import TritonModuleMixin
7
+ from torch import nn
8
+
9
+
10
+ def weight_quant(weight, num_bits=1):
11
+ dtype = weight.dtype
12
+ weight = weight.float()
13
+ s = 1 / weight.abs().mean().clamp(min=1e-5)
14
+ result = (weight * s).round().clamp(-1, 1) / s
15
+ return result.type(dtype)
16
+
17
+
18
+ def weight_quant2(weight, num_bits=1):
19
+ dtype = weight.dtype
20
+ weight = weight.float()
21
+ s = 1 / weight.abs().mean().clamp(min=1e-5)
22
+ result = (weight * s).round().clamp(-1, 1)
23
+ return result.type(dtype), 1 / s
24
+
25
+
26
+ def activation_quant(x, num_bits=8):
27
+ dtype = x.dtype
28
+ x = x.float()
29
+ Qn = -(2 ** (num_bits - 1))
30
+ Qp = 2 ** (num_bits - 1) - 1
31
+ s = Qp / x.abs().max(dim=-1, keepdim=True).values.clamp(min=1e-5)
32
+ result = (x * s).round().clamp(Qn, Qp) / s
33
+ return result.type(dtype)
34
+
35
+
36
+ def optimized_linear(quant_input, weight, scale):
37
+ # 重み行列のスパース性を利用して、乗算の代わりに加算と減算を行う
38
+ pos_mask = weight == 1
39
+ neg_mask = weight == -1
40
+
41
+ # 加算と減算を行い、結果を集約する
42
+ pos_sum = torch.matmul(quant_input, pos_mask.to(quant_input.dtype))
43
+ neg_sum = torch.matmul(quant_input, neg_mask.to(quant_input.dtype))
44
+ result = pos_sum - neg_sum
45
+
46
+ # scaleをかける
47
+ result *= scale
48
+
49
+ return result
50
+
51
+
52
+ class BitLinear(nn.Linear):
53
+ def __init__(self, *kargs, weight_bits=1, input_bits=8, **kwargs):
54
+ super(BitLinear, self).__init__(*kargs, **kwargs)
55
+ """
56
+ RMSNorm is placed outside BitLinear
57
+ """
58
+ self.weight_bits = weight_bits
59
+ self.input_bits = input_bits
60
+ self.quant_initialized = False
61
+ self.quant_scale = None
62
+
63
+ def quantize(self):
64
+ if not self.quant_initialized:
65
+ quant_weight, quant_scale = weight_quant2(self.weight, self.weight_bits)
66
+ quant_weight = self.weight + (quant_weight - self.weight).detach()
67
+ # print(f'Quantized weight: {quant_weight}')
68
+ # print(f'Quantized scale: {quant_scale}')
69
+ self.weight.data = quant_weight
70
+ self.quant_scale = quant_scale
71
+ self.quant_initialized = True
72
+
73
+ def forward(self, input):
74
+ if not self.quant_initialized:
75
+ self.quantize()
76
+
77
+ quant_input = (
78
+ input + (activation_quant(input, self.input_bits) - input).detach()
79
+ )
80
+
81
+ out = nn.functional.linear(quant_input, self.weight) * self.quant_scale
82
+ if self.bias is not None:
83
+ out += self.bias.view(1, -1).expand_as(out)
84
+
85
+ return out
86
+
87
+
88
+
89
+ # Original code from https://github.com/AutoGPTQ/AutoGPTQ
90
+ # MIT License
91
+
92
+ try:
93
+ from auto_gptq.nn_modules.triton_utils.kernels import (
94
+ QuantLinearFunction,
95
+ QuantLinearInferenceOnlyFunction,
96
+ quant_matmul_248,
97
+ quant_matmul_inference_only_248,
98
+ transpose_quant_matmul_248,
99
+ )
100
+ except ImportError as e:
101
+ triton_import_exception = e
102
+
103
+ def error_raiser_triton(*args, **kwargs):
104
+ raise ValueError(
105
+ f"Trying to use the triton backend, but could not import triton dependencies with the following error: {triton_import_exception}"
106
+ )
107
+
108
+ class FakeTriton:
109
+ def __getattr__(self, name):
110
+ raise ImportError(
111
+ f"Trying to use the triton backend, but could not import triton dependencies with the following error: {triton_import_exception}"
112
+ )
113
+
114
+ quant_matmul_248 = error_raiser_triton
115
+ transpose_quant_matmul_248 = error_raiser_triton
116
+ quant_matmul_inference_only_248 = error_raiser_triton
117
+ QuantLinearFunction = FakeTriton
118
+ QuantLinearInferenceOnlyFunction = FakeTriton
119
+
120
+
121
+ class QuantizedBitLinear(nn.Module, TritonModuleMixin):
122
+ QUANT_TYPE = "triton"
123
+
124
+ def __init__(
125
+ self,
126
+ infeatures,
127
+ outfeatures,
128
+ bias,
129
+ weight_bits=1,
130
+ input_bits=8,
131
+ quant_bits=2,
132
+ group_size=128,
133
+ trainable=False,
134
+ **kwargs,
135
+ ):
136
+ super().__init__()
137
+ if quant_bits not in [2, 4, 8]:
138
+ raise NotImplementedError("Only 2,4,8 bits are supported.")
139
+ if infeatures % 32 != 0 or outfeatures % 32 != 0:
140
+ raise NotImplementedError(
141
+ "in_feature and out_feature must be divisible by 32."
142
+ )
143
+ self.infeatures = infeatures
144
+ self.outfeatures = outfeatures
145
+ self.weight_bits = weight_bits
146
+ self.input_bits = input_bits
147
+ self.quant_bits = quant_bits
148
+ self.group_size = group_size if group_size != -1 else infeatures
149
+ self.maxq = 2**self.quant_bits - 1
150
+
151
+ self.register_buffer(
152
+ "qweight",
153
+ torch.zeros(
154
+ (infeatures // 32 * self.quant_bits, outfeatures), dtype=torch.int32
155
+ ),
156
+ )
157
+ self.register_buffer(
158
+ "qzeros",
159
+ torch.zeros(
160
+ (
161
+ math.ceil(infeatures / self.group_size),
162
+ outfeatures // 32 * self.quant_bits,
163
+ ),
164
+ dtype=torch.int32,
165
+ ),
166
+ )
167
+ self.register_buffer(
168
+ "scales",
169
+ torch.zeros(
170
+ (math.ceil(infeatures / self.group_size), outfeatures),
171
+ dtype=torch.float16,
172
+ ),
173
+ )
174
+ self.register_buffer(
175
+ "g_idx",
176
+ torch.tensor(
177
+ [i // self.group_size for i in range(infeatures)], dtype=torch.int32
178
+ ),
179
+ )
180
+ if bias:
181
+ self.register_buffer(
182
+ "bias", torch.zeros((outfeatures), dtype=torch.float16)
183
+ )
184
+ else:
185
+ self.bias = None
186
+
187
+ self.register_buffer("scale", torch.tensor(1.0, dtype=torch.float16))
188
+
189
+ self.trainable = trainable
190
+
191
+ def post_init(self):
192
+ pass
193
+
194
+ def pack(self, bitlinear: BitLinear):
195
+ device = bitlinear.weight.device
196
+ bitlinear = bitlinear.cpu()
197
+
198
+ W = bitlinear.weight.data.clone()
199
+ if isinstance(bitlinear, nn.Conv2d):
200
+ W = W.flatten(1)
201
+ if isinstance(bitlinear, transformers.pytorch_utils.Conv1D):
202
+ W = W.t()
203
+
204
+ self.scale = torch.tensor(bitlinear.quant_scale, dtype=torch.float16)
205
+ # self.scales.fill_(self.scale).half()
206
+ # self.scales.fill_(1).half()
207
+
208
+ scales = torch.ones(
209
+ self.outfeatures,
210
+ math.ceil(self.infeatures / self.group_size),
211
+ )
212
+ zero = 1
213
+ zeros = torch.zeros(
214
+ self.outfeatures,
215
+ math.ceil(self.infeatures / self.group_size),
216
+ )
217
+ zeros.fill_(zero)
218
+
219
+ scales = scales.t().contiguous()
220
+ zeros = zeros.t().contiguous()
221
+ scale_zeros = zeros * scales
222
+ self.scales = scales.clone().half()
223
+ if bitlinear.bias is not None:
224
+ self.bias = bitlinear.bias.clone().half()
225
+
226
+ intweight = []
227
+ for idx in range(self.infeatures):
228
+ intweight.append(
229
+ torch.round(
230
+ (W[:, idx] + scale_zeros[self.g_idx[idx]])
231
+ / self.scales[self.g_idx[idx]]
232
+ ).to(torch.int)[:, None]
233
+ )
234
+
235
+ intweight = torch.cat(intweight, dim=1)
236
+ intweight = intweight.t().contiguous()
237
+ intweight = intweight.numpy().astype(np.uint32)
238
+
239
+ print(f"Int weight: {intweight}")
240
+
241
+ i = 0
242
+ row = 0
243
+ qweight = np.zeros(
244
+ (intweight.shape[0] // 32 * self.quant_bits, intweight.shape[1]),
245
+ dtype=np.uint32,
246
+ )
247
+ while row < qweight.shape[0]:
248
+ if self.quant_bits in [2, 4, 8]:
249
+ for j in range(i, i + (32 // self.quant_bits)):
250
+ qweight[row] |= intweight[j] << (self.quant_bits * (j - i))
251
+ i += 32 // self.quant_bits
252
+ row += 1
253
+ else:
254
+ raise NotImplementedError("Only 2,4,8 bits are supported.")
255
+
256
+ qweight = qweight.astype(np.int32)
257
+ self.qweight = torch.from_numpy(qweight)
258
+
259
+ print(f"Quantized weight: {self.qweight}")
260
+
261
+ zeros -= 1
262
+ zeros = zeros.numpy().astype(np.uint32)
263
+ qzeros = np.zeros(
264
+ (zeros.shape[0], zeros.shape[1] // 32 * self.quant_bits), dtype=np.uint32
265
+ ) # math.ceil(infeatures / self.group_size), outfeatures // 32 * self.quant_bits,
266
+ i = 0
267
+ col = 0
268
+ while col < qzeros.shape[1]:
269
+ if self.quant_bits in [2, 4, 8]:
270
+ for j in range(i, i + (32 // self.quant_bits)):
271
+ qzeros[:, col] |= zeros[:, j] << (self.quant_bits * (j - i))
272
+ i += 32 // self.quant_bits
273
+ col += 1
274
+ else:
275
+ raise NotImplementedError("Only 2,4,8 bits are supported.")
276
+
277
+ qzeros = qzeros.astype(np.int32)
278
+ self.qzeros = torch.from_numpy(qzeros)
279
+
280
+ self.to(device)
281
+
282
+ # zeros -= 1
283
+ # zeros = zeros.numpy().astype(np.uint32)
284
+ # qzeros = np.zeros((zeros.shape[0], zeros.shape[1] // 32 * self.quant_bits), dtype=np.uint32)
285
+ # i = 0
286
+ # col = 0
287
+ # while col < qzeros.shape[1]:
288
+ # if self.quant_bits in [2, 4, 8]:
289
+ # for j in range(i, i + (32 // self.quant_bits)):
290
+ # qzeros[:, col] |= zeros[:, j] << (self.quant_bits * (j - i))
291
+ # i += 32 // self.quant_bits
292
+ # col += 1
293
+ # else:
294
+ # raise NotImplementedError("Only 2,4,8 bits are supported.")
295
+
296
+ # qzeros = qzeros.astype(np.int32)
297
+ # self.qzeros = torch.from_numpy(qzeros)
298
+
299
+ def forward(self, x):
300
+ # out_shape = x.shape[:-1] + (self.outfeatures,)
301
+ # quant_linear_fn = QuantLinearFunction if self.trainable else QuantLinearInferenceOnlyFunction
302
+ # out = quant_linear_fn.apply(
303
+ # x.reshape(-1, x.shape[-1]),
304
+ # self.qweight,
305
+ # self.scales,
306
+ # self.qzeros,
307
+ # self.g_idx,
308
+ # self.quant_bits,
309
+ # self.maxq,
310
+ # )
311
+ # out = out.half().reshape(out_shape)
312
+ # out = out + self.bias if self.bias is not None else out
313
+ # return out
314
+
315
+ x = x + (activation_quant(x, self.input_bits) - x).detach()
316
+ out_shape = x.shape[:-1] + (self.outfeatures,)
317
+
318
+ quant_linear_fn = (
319
+ QuantLinearFunction if self.trainable else QuantLinearInferenceOnlyFunction
320
+ )
321
+ out = quant_linear_fn.apply(
322
+ x.reshape(-1, x.shape[-1]),
323
+ self.qweight,
324
+ self.scales,
325
+ self.qzeros,
326
+ self.g_idx,
327
+ self.quant_bits,
328
+ self.maxq,
329
+ )
330
+
331
+ out *= self.scale
332
+
333
+ out = out.half().reshape(out_shape)
334
+ out = out + self.bias if self.bias is not None else out
335
+
336
+ return out
337
+
338
+ @classmethod
339
+ def warmup(cls, model, transpose=False, seqlen=2048):
340
+ """
341
+ Pre-tunes the quantized kernel
342
+ """
343
+ from tqdm import tqdm
344
+
345
+ kn_values = {}
346
+
347
+ for _, m in model.named_modules():
348
+ if not isinstance(m, cls):
349
+ continue
350
+
351
+ k = m.infeatures
352
+ n = m.outfeatures
353
+
354
+ if (k, n) not in kn_values:
355
+ kn_values[(k, n)] = (
356
+ m.qweight,
357
+ m.scales,
358
+ m.qzeros,
359
+ m.g_idx,
360
+ m.bits,
361
+ m.maxq,
362
+ )
363
+
364
+ # logger.info(f"Found {len(kn_values)} unique KN Linear values.")
365
+ # logger.info("Warming up autotune cache ...")
366
+ with torch.no_grad():
367
+ for m in tqdm(range(0, math.ceil(math.log2(seqlen)) + 1)):
368
+ m = 2**m
369
+ for (k, n), (
370
+ qweight,
371
+ scales,
372
+ qzeros,
373
+ g_idx,
374
+ bits,
375
+ maxq,
376
+ ) in kn_values.items():
377
+ if transpose:
378
+ a = torch.randn(m, k, dtype=torch.float16, device=model.device)
379
+ quant_matmul_248(a, qweight, scales, qzeros, g_idx, bits, maxq)
380
+ a = torch.randn(m, n, dtype=torch.float16, device=model.device)
381
+ transpose_quant_matmul_248(
382
+ a, qweight, scales, qzeros, g_idx, bits, maxq
383
+ )
384
+ else:
385
+ a = torch.randn(m, k, dtype=torch.float16, device=model.device)
386
+ quant_matmul_inference_only_248(
387
+ a, qweight, scales, qzeros, g_idx, bits, maxq
388
+ )
389
+ del kn_values