shirayukikun commited on
Commit
92e2f03
·
verified ·
1 Parent(s): 6b705a2

Upload folder using huggingface_hub

Browse files
README.md CHANGED
@@ -1,3 +1,375 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - ja
5
+ ---
6
+
7
+ (English part follows Japanese one.)
8
+
9
+ # byBERT-JP 100M
10
+
11
+ バイト単位のtokenizerを採用して,日本語 [BERT](https://aclanthology.org/N19-1423/) モデルです。
12
+
13
+ ## 利用方法
14
+ [transformers version 4.56.1](https://github.com/huggingface/transformers/releases/tag/v4.56.1) において、動作確認をしています。
15
+
16
+ ```python
17
+ import argparse
18
+
19
+ import torch
20
+ from transformers import AutoModelForMaskedLM, AutoTokenizer
21
+
22
+ MASK_PLACEHOLDER = "<mask>"
23
+ SAMPLE_INPUT_TEXTS = [
24
+ f"東北大学は宮城県{MASK_PLACEHOLDER * 6}市にある大学です。", # 6 bytes mask
25
+ f"日本一高い山は{MASK_PLACEHOLDER * 9}です。", # 9 bytes mask
26
+ ]
27
+
28
+
29
+ def main(args):
30
+ torch.manual_seed(args.seed)
31
+ device = torch.device("cuda")
32
+
33
+ tokenizer = AutoTokenizer.from_pretrained(
34
+ args.model_name_or_path,
35
+ trust_remote_code=True,
36
+ )
37
+ model = AutoModelForMaskedLM.from_pretrained(
38
+ args.model_name_or_path,
39
+ dtype=torch.bfloat16,
40
+ trust_remote_code=True,
41
+ )
42
+ model.to(device)
43
+ model.eval()
44
+
45
+ input_texts = [
46
+ s.replace(MASK_PLACEHOLDER, tokenizer.mask_token)
47
+ for s in SAMPLE_INPUT_TEXTS
48
+ ]
49
+ batch = tokenizer(input_texts, return_tensors="pt", padding="longest")
50
+
51
+ batch = batch.to(device)
52
+ outputs = model(**batch)
53
+ decoded_ids = torch.argmax(outputs.logits, dim=-1)
54
+ is_pad = batch.input_ids == tokenizer.pad_token_id
55
+ decoded_ids[is_pad] = tokenizer.pad_token_id
56
+ decoded_texts = tokenizer.batch_decode(decoded_ids, skip_special_tokens=False)
57
+
58
+
59
+ for input_ids, decoded_text in zip(batch.input_ids, decoded_texts):
60
+ input_text = tokenizer.decode(input_ids, skip_special_tokens=False)
61
+ print("===")
62
+ print(f"Input: {input_text}")
63
+ print(f"Decoded: {decoded_text}")
64
+
65
+
66
+ if __name__ == "__main__":
67
+ parser = argparse.ArgumentParser(allow_abbrev=False)
68
+ parser.add_argument(
69
+ "--model_name_or_path",
70
+ "-m",
71
+ type=str,
72
+ default="tohoku-nlp/bybert-jp-next-100m",
73
+ help="Path to the model or model identifier from huggingface.co/models."
74
+ )
75
+ parser.add_argument("--seed", "-s", type=int, help="Random seed", default=42)
76
+ args = parser.parse_args()
77
+ main(args)
78
+ ```
79
+
80
+
81
+ ## モデルアーキテクチャ
82
+
83
+ [Llama](https://arxiv.org/abs/2302.13971) アーキテクチャをベースとし、Causal Attention Mask を取り除くことで、Encoder 型言語モデルとして利用しています。
84
+ 具体的には、以下のモジュールを採用しています。
85
+
86
+ - [SwiGLU](https://arxiv.org/abs/2002.05202)
87
+ - [Rotary Positional Embeddings (RoPE)](https://arxiv.org/abs/2104.09864)
88
+ - [Grouped Query Attention (GQA)](https://aclanthology.org/2023.emnlp-main.298/)
89
+
90
+
91
+ ## 学習データ
92
+
93
+ [llm-jp-corpus-v3](https://gitlab.llm-jp.nii.ac.jp/datasets/llm-jp-corpus-v3) の日本語コーパスのサブセット (ja\_cc, ja\_warp\_html, ja\_warp\_pdf, ja\_wiki, kaken) を使用しました。
94
+ また、学習時には Whole Word Masking を実施しています。
95
+ Whole Word Masking 単語分割器には、[vibrato](https://github.com/daac-tools/vibrato) を利用しました。
96
+ 辞書は [bccwj-suw+unidic-cwj-3_1_1](https://github.com/daac-tools/vibrato/releases#:~:text=Compact%2Ddual-,bccwj%2Dsuw%2Bunidic%2Dcwj%2D3_1_1,-618%20MB) を用いています。
97
+
98
+
99
+ ## 学習時の設定
100
+
101
+ モデルの重みを初期化した Llama アーキテクチャベースの Encoder モデルを from scratch で学習させています。
102
+ 各モデルの学習設定は以下の通りです。
103
+
104
+ | | Params. | Tokens | Steps | Batch Size (tokens) |
105
+ | --- | --- | --- | --- | --- |
106
+ | tohoku-nlp/bybert-jp-100m | 107 M | 623 B | 198,000 | 3,145,728 |
107
+ | tohoku-nlp/bybert-jp-200m | 205 M | 637 B | 270,000 | 2,359,296 |
108
+ | tohoku-nlp/bybert-jp-400m | 397 M | 1.23 T | 308,000 | 3,981,312 |
109
+ | tohoku-nlp/bybert-jp-next-100m | 114 M | 2.76 T | 330,000 | 8,388,608 |
110
+
111
+
112
+ 学習には、Masked Language Modeling (MLM) のみ実施し、Next Sentence Prediction (NSP) は実施していません。
113
+ また,tohoku-nlp/bybert-jp-next-100mでは
114
+
115
+ - 学習データ量を2.85T tokensに増やす
116
+ - unicodeのencodingに独自形式を採用
117
+ - マスク率を50%で学習.その後30%に減少
118
+ - QKVの線形変換にバイアス項を追加
119
+ - batch sizeのwarmupを導入
120
+
121
+ により,小規模モデルながら比較的高い性能を達成しています.
122
+
123
+
124
+ ### 学習設定の詳細
125
+
126
+ | | bybert-jp-100,200,400m | bybert-jp-next-100m |
127
+ | ---- | ---- | ---- |
128
+ | Max Learning Rate | 1.0E-3 | 1.0E-3 |
129
+ | Min Learning Rate | 1.0E-6 | 1.0E-6 |
130
+ | Learning Rate Warmup Steps | 2,000 | 2,000 |
131
+ | Scheduler | cosine | cosine |
132
+ | Optimizer | AdamW | AdamW |
133
+ | Optimizer Config | beta_1 = 0.9, beta_2 = 0.999, eps = 1.0E-8 | beta_1 = 0.9, beta_2 = 0.999, eps = 1.0E-8 |
134
+ | Weight Decay | 0.01 | 0.01 |
135
+ | Gradient Clipping | 1.0 | 1.0 |
136
+ | Sequence Length | 3,072 | 4,096 |
137
+ | MLM Probability | 0.3 | 0.5 -> 0.3 |
138
+ | Replace Masked-token Probability | 0.8 | 0.8 |
139
+ | Replace Random-token Probability | 0.1 | 0.1 |
140
+
141
+ 学習には[Megatron-LM](https://arxiv.org/abs/1909.08053)をベースに,独自の変更を加えたコードベースを使用しています。
142
+
143
+ ## 評価
144
+
145
+
146
+ 評価指標として、単語のマスクされた単語の予測正解率を用いた。
147
+ 実験設定の詳細は[工藤 et al. (2025)](https://www.anlp.jp/proceedings/annual_meeting/2025/pdf_dir/Q8-5.pdf) を参照してください。
148
+ 評価結果は以下の通りです。
149
+
150
+ | | ichikara | wiki |
151
+ |--------------------------------|----------|------|
152
+ | tohoku-nlp/bybert-jp-100m | 58.0 | 26.3 |
153
+ | tohoku-nlp/bybert-jp-200m | 60.5 | 33.0 |
154
+ | tohoku-nlp/bybert-jp-400m | 67.4 | 38.5 |
155
+ | tohoku-nlp/bybert-jp-next-100m | 63.4 | 40.5 |
156
+
157
+ その他,
158
+ - モデルアーキテクチャ探索
159
+ - ハイパーパラメータ探索
160
+ - 内部機序等のパフォーマンス以外の側面からの分析
161
+ についても[工藤 et al. (2025)](https://www.anlp.jp/proceedings/annual_meeting/2025/pdf_dir/Q8-5.pdf) を参照してください。
162
+
163
+
164
+
165
+ ## ライセンス
166
+
167
+ このモデルは Apache License 2.0 の下で配布しています。
168
+
169
+ # 免責事項
170
+
171
+ 本モデルの作者は本モデルを作成するにあたって、その内容、機能等について細心の注意を払っておりますが、モデルの出力が正確であるかどうか、安全なものであるか等について保証をするものではなく、何らの責任を負うものではありません。
172
+ 本モデルの利用により、万一、利用者に何らかの不都合や損害が発生したとしても、モデルやデータセットの作者や作者の所属組織は何らの責任を負うものではありません。
173
+
174
+ ## 謝辞
175
+
176
+ このモデルの学習にあたり様々な面でご協力いただきました [Tohoku NLP Group](https://www.nlp.ecei.tohoku.ac.jp/) の皆様に感謝いたします。
177
+
178
+ ## 作成者
179
+ - [Keito Kudo](https://x.com/k8kudo)
180
+ - [Go Kamoda](https://x.com/go2oo2)
181
+ - [Daiki Shiono](https://x.com/onely7_deep)
182
+ - [Jun Suzuki](https://x.com/drJunSuzuki)
183
+
184
+
185
+ <br>
186
+ <br>
187
+ <br>
188
+ <br>
189
+
190
+
191
+
192
+ ---
193
+ license: apache-2.0
194
+ language:
195
+ - ja
196
+ ---
197
+
198
+ (English part follows Japanese one.)
199
+
200
+ # byBERT-JP 100M
201
+
202
+ A Japanese [BERT](https://aclanthology.org/N19-1423/) model that adopts a byte-level tokenizer.
203
+
204
+ ## Usage
205
+
206
+ ```python
207
+ import argparse
208
+
209
+ import torch
210
+ from transformers import AutoModelForMaskedLM, AutoTokenizer
211
+
212
+ MASK_PLACEHOLDER = "<mask>"
213
+ SAMPLE_INPUT_TEXTS = [
214
+ f"東北大学は宮城県{MASK_PLACEHOLDER * 6}市にある大学です。", # 6 bytes mask
215
+ f"日本一高い山は{MASK_PLACEHOLDER * 9}です。", # 9 bytes mask
216
+ ]
217
+
218
+
219
+ def main(args):
220
+ torch.manual_seed(args.seed)
221
+ device = torch.device("cuda")
222
+
223
+ tokenizer = AutoTokenizer.from_pretrained(
224
+ args.model_name_or_path,
225
+ trust_remote_code=True,
226
+ )
227
+ model = AutoModelForMaskedLM.from_pretrained(
228
+ args.model_name_or_path,
229
+ dtype=torch.bfloat16,
230
+ trust_remote_code=True,
231
+ )
232
+ model.to(device)
233
+ model.eval()
234
+
235
+ input_texts = [
236
+ s.replace(MASK_PLACEHOLDER, tokenizer.mask_token)
237
+ for s in SAMPLE_INPUT_TEXTS
238
+ ]
239
+ batch = tokenizer(input_texts, return_tensors="pt", padding="longest")
240
+
241
+ batch = batch.to(device)
242
+ outputs = model(**batch)
243
+ decoded_ids = torch.argmax(outputs.logits, dim=-1)
244
+ is_pad = batch.input_ids == tokenizer.pad_token_id
245
+ decoded_ids[is_pad] = tokenizer.pad_token_id
246
+ decoded_texts = tokenizer.batch_decode(decoded_ids, skip_special_tokens=False)
247
+
248
+
249
+ for input_ids, decoded_text in zip(batch.input_ids, decoded_texts):
250
+ input_text = tokenizer.decode(input_ids, skip_special_tokens=False)
251
+ print("===")
252
+ print(f"Input: {input_text}")
253
+ print(f"Decoded: {decoded_text}")
254
+
255
+
256
+ if __name__ == "__main__":
257
+ parser = argparse.ArgumentParser(allow_abbrev=False)
258
+ parser.add_argument(
259
+ "--model_name_or_path",
260
+ "-m",
261
+ type=str,
262
+ default="tohoku-nlp/bybert-jp-next-100m",
263
+ help="Path to the model or model identifier from huggingface.co/models."
264
+ )
265
+ parser.add_argument("--seed", "-s", type=int, help="Random seed", default=42)
266
+ args = parser.parse_args()
267
+ main(args)
268
+ ```
269
+
270
+ We have confirmed operation with [transformers version 4.56.1](https://github.com/huggingface/transformers/releases/tag/v4.56.1).
271
+
272
+
273
+ ## Model Architecture
274
+
275
+ Based on the [Llama](https://arxiv.org/abs/2302.13971) architecture, we use it as an Encoder-type language model by removing the Causal Attention Mask.
276
+ Specifically, we adopt the following modules:
277
+
278
+ - [SwiGLU](https://arxiv.org/abs/2002.05202)
279
+ - [Rotary Positional Embeddings (RoPE)](https://arxiv.org/abs/2104.09864)
280
+ - [Grouped Query Attention (GQA)](https://aclanthology.org/2023.emnlp-main.298/)
281
+
282
+
283
+ ## Training Data
284
+
285
+ We used a subset of Japanese corpora (ja_cc, ja_warp_html, ja_warp_pdf, ja_wiki, kaken) from [llm-jp-corpus-v3](https://gitlab.llm-jp.nii.ac.jp/datasets/llm-jp-corpus-v3).
286
+ Additionally, we implemented Whole Word Masking during training.
287
+ For the Whole Word Masking word segmenter, we used [vibrato](https://github.com/daac-tools/vibrato).
288
+ We used the [bccwj-suw+unidic-cwj-3_1_1](https://github.com/daac-tools/vibrato/releases#:~:text=Compact%2Ddual-,bccwj%2Dsuw%2Bunidic%2Dcwj%2D3_1_1,-618%20MB) dictionary.
289
+
290
+
291
+ ## Training Configuration
292
+
293
+ We trained the Llama architecture-based Encoder model with initialized weights from scratch.
294
+ The training configuration for each model is as follows:
295
+
296
+ | | Params. | Tokens | Steps | Batch Size (tokens) |
297
+ | --- | --- | --- | --- | --- |
298
+ | tohoku-nlp/bybert-jp-100m | 107 M | 623 B | 198,000 | 3,145,728 |
299
+ | tohoku-nlp/bybert-jp-200m | 205 M | 637 B | 270,000 | 2,359,296 |
300
+ | tohoku-nlp/bybert-jp-400m | 397 M | 1.23 T | 308,000 | 3,981,312 |
301
+ | tohoku-nlp/bybert-jp-next-100m | 114 M | 2.76 T | 330,000 | 8,388,608 |
302
+
303
+
304
+ Training was performed using only Masked Language Modeling (MLM), without Next Sentence Prediction (NSP).
305
+ Additionally, for tohoku-nlp/bybert-jp-next-100m:
306
+
307
+ - Increased training data volume to 2.85T tokens
308
+ - Adopted proprietary format for unicode encoding
309
+ - Trained with 50% mask rate, then reduced to 30%
310
+ - Added bias term to QKV linear transformations
311
+ - Introduced batch size warmup
312
+
313
+ Through these improvements, we achieved relatively high performance despite being a small-scale model.
314
+
315
+
316
+ ### Detailed Training Configuration
317
+
318
+ | | bybert-jp-100,200,400m | bybert-jp-next-100m |
319
+ | ---- | ---- | ---- |
320
+ | Max Learning Rate | 1.0E-3 | 1.0E-3 |
321
+ | Min Learning Rate | 1.0E-6 | 1.0E-6 |
322
+ | Learning Rate Warmup Steps | 2,000 | 2,000 |
323
+ | Scheduler | cosine | cosine |
324
+ | Optimizer | AdamW | AdamW |
325
+ | Optimizer Config | beta_1 = 0.9, beta_2 = 0.999, eps = 1.0E-8 | beta_1 = 0.9, beta_2 = 0.999, eps = 1.0E-8 |
326
+ | Weight Decay | 0.01 | 0.01 |
327
+ | Gradient Clipping | 1.0 | 1.0 |
328
+ | Sequence Length | 3,072 | 4,096 |
329
+ | MLM Probability | 0.3 | 0.5 -> 0.3 |
330
+ | Replace Masked-token Probability | 0.8 | 0.8 |
331
+ | Replace Random-token Probability | 0.1 | 0.1 |
332
+
333
+ For training, we use a codebase based on [Megatron-LM](https://arxiv.org/abs/1909.08053) with our own modifications.
334
+
335
+ ## Evaluation
336
+
337
+
338
+ We used the prediction accuracy of masked words as the evaluation metric.
339
+ For details of the experimental setup, please refer to [Kudo et al. (2025)](https://www.anlp.jp/proceedings/annual_meeting/2025/pdf_dir/Q8-5.pdf).
340
+ The evaluation results are as follows:
341
+
342
+ | | ichikara | wiki |
343
+ |--------------------------------|----------|------|
344
+ | tohoku-nlp/bybert-jp-100m | 58.0 | 26.3 |
345
+ | tohoku-nlp/bybert-jp-200m | 60.5 | 33.0 |
346
+ | tohoku-nlp/bybert-jp-400m | 67.4 | 38.5 |
347
+ | tohoku-nlp/bybert-jp-next-100m | 63.4 | 40.5 |
348
+
349
+ For other aspects including:
350
+ - Model architecture exploration
351
+ - Hyperparameter exploration
352
+ - Analysis from non-performance perspectives such as internal mechanisms
353
+
354
+ Please refer to [Kudo et al. (2025)](https://www.anlp.jp/proceedings/annual_meeting/2025/pdf_dir/Q8-5.pdf).
355
+
356
+
357
+
358
+ ## License
359
+
360
+ This model is distributed under the Apache License 2.0.
361
+
362
+ # Disclaimer
363
+
364
+ While the authors of this model have paid careful attention to its content and functionality in creating this model, they do not warrant that the model's output is accurate or safe, and assume no responsibility whatsoever.
365
+ The authors of the model and dataset and their affiliated organizations assume no responsibility for any inconvenience or damage that may occur to users through the use of this model.
366
+
367
+ ## Acknowledgments
368
+
369
+ We would like to thank everyone at [Tohoku NLP Group](https://www.nlp.ecei.tohoku.ac.jp/) for their cooperation in various aspects of training this model.
370
+
371
+ ## Creators
372
+ - [Keito Kudo](https://x.com/k8kudo)
373
+ - [Go Kamoda](https://x.com/go2oo2)
374
+ - [Daiki Shiono](https://x.com/onely7_deep)
375
+ - [Jun Suzuki](https://x.com/drJunSuzuki)
added_tokens.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "<extra_id_0>": 262,
3
+ "<extra_id_10>": 272,
4
+ "<extra_id_11>": 273,
5
+ "<extra_id_12>": 274,
6
+ "<extra_id_13>": 275,
7
+ "<extra_id_14>": 276,
8
+ "<extra_id_15>": 277,
9
+ "<extra_id_16>": 278,
10
+ "<extra_id_17>": 279,
11
+ "<extra_id_18>": 280,
12
+ "<extra_id_19>": 281,
13
+ "<extra_id_1>": 263,
14
+ "<extra_id_20>": 282,
15
+ "<extra_id_21>": 283,
16
+ "<extra_id_22>": 284,
17
+ "<extra_id_23>": 285,
18
+ "<extra_id_24>": 286,
19
+ "<extra_id_25>": 287,
20
+ "<extra_id_2>": 264,
21
+ "<extra_id_3>": 265,
22
+ "<extra_id_4>": 266,
23
+ "<extra_id_5>": 267,
24
+ "<extra_id_6>": 268,
25
+ "<extra_id_7>": 269,
26
+ "<extra_id_8>": 270,
27
+ "<extra_id_9>": 271
28
+ }
config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "None",
3
+ "architectures": [
4
+ "LlamaEncForMaskedLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_llama_enc.LlamaEncConfig",
10
+ "AutoModel": "modeling_llama_enc.LlamaEncModel",
11
+ "AutoModelForMaskedLM": "modeling_llama_enc.LlamaEncForMaskedLM",
12
+ "AutoModelForQuestionAnswering": "modeling_llama_enc.LlamaEncForQuestionAnswering",
13
+ "AutoModelForSequenceClassification": "modeling_llama_enc.LlamaEncForSequenceClassification",
14
+ "AutoModelForTokenClassification": "modeling_llama_enc.LlamaEncForTokenClassification"
15
+ },
16
+ "bos_token_id": 2,
17
+ "eos_token_id": 1,
18
+ "hidden_act": "silu",
19
+ "hidden_size": 768,
20
+ "initializer_range": 0.02,
21
+ "intermediate_size": 3072,
22
+ "label_smoothing": 0.0,
23
+ "max_position_embeddings": 3072,
24
+ "mlp_bias": false,
25
+ "model_type": "llama_enc",
26
+ "num_attention_heads": 16,
27
+ "num_hidden_layers": 12,
28
+ "num_key_value_heads": 8,
29
+ "pretraining_tp": 1,
30
+ "rms_norm_eps": 1e-06,
31
+ "rope_scaling": null,
32
+ "rope_theta": 10000.0,
33
+ "tie_word_embeddings": false,
34
+ "torch_dtype": "float32",
35
+ "transformers_version": "4.41.2",
36
+ "trust_remote_code": true,
37
+ "use_cache": true,
38
+ "vocab_size": 288,
39
+ "window_size_left": -1,
40
+ "window_size_right": -1
41
+ }
configuration_llama_enc.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ LLaMA model configuration"""
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+
29
+ class LlamaEncConfig(PretrainedConfig):
30
+ r"""
31
+ This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
32
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
33
+ defaults will yield a similar configuration to that of the LLaMA-7B.
34
+
35
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+
38
+
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 32000):
41
+ Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
42
+ `inputs_ids` passed when calling [`LlamaModel`]
43
+ hidden_size (`int`, *optional*, defaults to 4096):
44
+ Dimension of the hidden representations.
45
+ intermediate_size (`int`, *optional*, defaults to 11008):
46
+ Dimension of the MLP representations.
47
+ num_hidden_layers (`int`, *optional*, defaults to 32):
48
+ Number of hidden layers in the Transformer decoder.
49
+ num_attention_heads (`int`, *optional*, defaults to 32):
50
+ Number of attention heads for each attention layer in the Transformer decoder.
51
+ num_key_value_heads (`int`, *optional*):
52
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
53
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
54
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
55
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
56
+ by meanpooling all the original heads within that group. For more details checkout [this
57
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
58
+ `num_attention_heads`.
59
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
60
+ The non-linear activation function (function or string) in the decoder.
61
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
62
+ The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
63
+ Llama 2 up to 4096, CodeLlama up to 16384.
64
+ initializer_range (`float`, *optional*, defaults to 0.02):
65
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
66
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
67
+ The epsilon used by the rms normalization layers.
68
+ use_cache (`bool`, *optional*, defaults to `True`):
69
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
70
+ relevant if `config.is_decoder=True`.
71
+ pad_token_id (`int`, *optional*):
72
+ Padding token id.
73
+ bos_token_id (`int`, *optional*, defaults to 1):
74
+ Beginning of stream token id.
75
+ eos_token_id (`int`, *optional*, defaults to 2):
76
+ End of stream token id.
77
+ pretraining_tp (`int`, *optional*, defaults to 1):
78
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
79
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to understand more about it. This value is
80
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
81
+ issue](https://github.com/pytorch/pytorch/issues/76232).
82
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
83
+ Whether to tie weight embeddings
84
+ rope_theta (`float`, *optional*, defaults to 10000.0):
85
+ The base period of the RoPE embeddings.
86
+ rope_scaling (`Dict`, *optional*):
87
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
88
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
89
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
90
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
91
+ these scaling strategies behave:
92
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
93
+ experimental feature, subject to breaking API changes in future versions.
94
+ attention_bias (`bool`, *optional*, defaults to `False`):
95
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
96
+ attention_dropout (`float`, *optional*, defaults to 0.0):
97
+ The dropout ratio for the attention probabilities.
98
+ mlp_bias (`bool`, *optional*, defaults to `False`):
99
+ Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
100
+
101
+ ```python
102
+ >>> from transformers import LlamaModel, LlamaConfig
103
+
104
+ >>> # Initializing a LLaMA llama-7b style configuration
105
+ >>> configuration = LlamaConfig()
106
+
107
+ >>> # Initializing a model from the llama-7b style configuration
108
+ >>> model = LlamaModel(configuration)
109
+
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+ model_type = "llama_enc"
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
+ mlp_bias=False,
139
+ label_smoothing=0.0,
140
+ window_size_left=-1,
141
+ window_size_right=-1,
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.mlp_bias = mlp_bias
167
+ self.label_smoothing = label_smoothing
168
+ self.window_size_left = window_size_left
169
+ self.window_size_right = window_size_right
170
+ super().__init__(
171
+ pad_token_id=pad_token_id,
172
+ bos_token_id=bos_token_id,
173
+ eos_token_id=eos_token_id,
174
+ tie_word_embeddings=tie_word_embeddings,
175
+ **kwargs,
176
+ )
177
+
178
+ def _rope_scaling_validation(self):
179
+ """
180
+ Validate the `rope_scaling` configuration.
181
+ """
182
+ if self.rope_scaling is None:
183
+ return
184
+
185
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
186
+ raise ValueError(
187
+ "`rope_scaling` must be a dictionary with two fields, `type` and `factor`, " f"got {self.rope_scaling}"
188
+ )
189
+ rope_scaling_type = self.rope_scaling.get("type", None)
190
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
191
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
192
+ raise ValueError(
193
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
194
+ )
195
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
196
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9cf4579b7a0093b4ab69c32cbe0d400f8c9934c1726b1558f9456da92f467ac5
3
+ size 426531816
modeling_llama_enc.py ADDED
@@ -0,0 +1,1302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Encodr model."""
21
+
22
+ import math
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPast,
34
+ CausalLMOutputWithPast,
35
+ QuestionAnsweringModelOutput,
36
+ SequenceClassifierOutputWithPast,
37
+ )
38
+ from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask_for_sdpa
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
+ from .configuration_llama_enc import LlamaEncConfig
50
+
51
+ if is_flash_attn_2_available():
52
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
53
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
54
+
55
+
56
+ logger = logging.get_logger(__name__)
57
+
58
+ _CONFIG_FOR_DOC = "LlamaEncConfig"
59
+
60
+
61
+ def _get_unpad_data(attention_mask):
62
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
63
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
64
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
65
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
66
+ return (
67
+ indices,
68
+ cu_seqlens,
69
+ max_seqlen_in_batch,
70
+ )
71
+
72
+
73
+ class LlamaEncRMSNorm(nn.Module):
74
+ def __init__(self, hidden_size, eps=1e-6):
75
+ """
76
+ LlamaEncRMSNorm is equivalent to T5LayerNorm
77
+ """
78
+ super().__init__()
79
+ self.weight = nn.Parameter(torch.ones(hidden_size))
80
+ self.variance_epsilon = eps
81
+
82
+ def forward(self, hidden_states):
83
+ input_dtype = hidden_states.dtype
84
+ hidden_states = hidden_states.to(torch.float32)
85
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
86
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
87
+ return self.weight * hidden_states.to(input_dtype)
88
+
89
+
90
+ ALL_LAYERNORM_LAYERS.append(LlamaEncRMSNorm)
91
+
92
+
93
+ class LlamaEncRotaryEmbedding(nn.Module):
94
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
95
+ super().__init__()
96
+ self.scaling_factor = scaling_factor
97
+ self.dim = dim
98
+ self.max_position_embeddings = max_position_embeddings
99
+ self.base = base
100
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
101
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
102
+ # For BC we register cos and sin cached
103
+ self.max_seq_len_cached = max_position_embeddings
104
+
105
+ @torch.no_grad()
106
+ def forward(self, x, position_ids):
107
+ # x: [bs, num_attention_heads, seq_len, head_size]
108
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
109
+ position_ids_expanded = position_ids[:, None, :].float()
110
+ # Force float32 since bfloat16 loses precision on long contexts
111
+ # See https://github.com/huggingface/transformers/pull/29285
112
+ device_type = x.device.type
113
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
114
+ with torch.autocast(device_type=device_type, enabled=False):
115
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
116
+ emb = torch.cat((freqs, freqs), dim=-1)
117
+ cos = emb.cos()
118
+ sin = emb.sin()
119
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
120
+
121
+
122
+ class LlamaEncLinearScalingRotaryEmbedding(LlamaEncRotaryEmbedding):
123
+ """LlamaEncRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
124
+
125
+ def forward(self, x, position_ids):
126
+ # difference to the original RoPE: a scaling factor is aplied to the position ids
127
+ position_ids = position_ids.float() / self.scaling_factor
128
+ cos, sin = super().forward(x, position_ids)
129
+ return cos, sin
130
+
131
+
132
+ class LlamaEncDynamicNTKScalingRotaryEmbedding(LlamaEncRotaryEmbedding):
133
+ """LlamaEncRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
134
+
135
+ def forward(self, x, position_ids):
136
+ # difference to the original RoPE: inv_freq is recomputed when the sequence length > original length
137
+ seq_len = torch.max(position_ids) + 1
138
+ if seq_len > self.max_position_embeddings:
139
+ base = self.base * (
140
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
141
+ ) ** (self.dim / (self.dim - 2))
142
+ inv_freq = 1.0 / (
143
+ base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(x.device) / self.dim)
144
+ )
145
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: this may break with compilation
146
+
147
+ cos, sin = super().forward(x, position_ids)
148
+ return cos, sin
149
+
150
+
151
+ def rotate_half(x):
152
+ """Rotates half the hidden dims of the input."""
153
+ x1 = x[..., : x.shape[-1] // 2]
154
+ x2 = x[..., x.shape[-1] // 2 :]
155
+ return torch.cat((-x2, x1), dim=-1)
156
+
157
+
158
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
159
+ """Applies Rotary Position Embedding to the query and key tensors.
160
+
161
+ Args:
162
+ q (`torch.Tensor`): The query tensor.
163
+ k (`torch.Tensor`): The key tensor.
164
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
165
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
166
+ position_ids (`torch.Tensor`, *optional*):
167
+ Deprecated and unused.
168
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
169
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
170
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
171
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
172
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
173
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
174
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
175
+ Returns:
176
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
177
+ """
178
+ cos = cos.unsqueeze(unsqueeze_dim)
179
+ sin = sin.unsqueeze(unsqueeze_dim)
180
+ q_embed = (q * cos) + (rotate_half(q) * sin)
181
+ k_embed = (k * cos) + (rotate_half(k) * sin)
182
+ return q_embed, k_embed
183
+
184
+
185
+ class LlamaEncMLP(nn.Module):
186
+ def __init__(self, config):
187
+ super().__init__()
188
+ self.config = config
189
+ self.hidden_size = config.hidden_size
190
+ self.intermediate_size = config.intermediate_size
191
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
192
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
193
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
194
+ self.act_fn = ACT2FN[config.hidden_act]
195
+
196
+ def forward(self, x):
197
+ if self.config.pretraining_tp > 1:
198
+ slice = self.intermediate_size // self.config.pretraining_tp
199
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
200
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
201
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
202
+
203
+ gate_proj = torch.cat(
204
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
205
+ )
206
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
207
+
208
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
209
+ down_proj = [
210
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
211
+ ]
212
+ down_proj = sum(down_proj)
213
+ else:
214
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
215
+
216
+ return down_proj
217
+
218
+
219
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
220
+ """
221
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
222
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
223
+ """
224
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
225
+ if n_rep == 1:
226
+ return hidden_states
227
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
228
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
229
+
230
+
231
+ class LlamaEncAttention(nn.Module):
232
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
233
+
234
+ def __init__(self, config: LlamaEncConfig, layer_idx: Optional[int] = None):
235
+ super().__init__()
236
+ self.config = config
237
+ self.layer_idx = layer_idx
238
+ if layer_idx is None:
239
+ logger.warning_once(
240
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
241
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
242
+ "when creating this class."
243
+ )
244
+
245
+ self.attention_dropout = config.attention_dropout
246
+ self.hidden_size = config.hidden_size
247
+ self.num_heads = config.num_attention_heads
248
+ self.head_dim = self.hidden_size // self.num_heads
249
+ self.num_key_value_heads = config.num_key_value_heads
250
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
251
+ self.max_position_embeddings = config.max_position_embeddings
252
+ self.rope_theta = config.rope_theta
253
+ self.is_causal = False # Encoder model does not use causal attention
254
+ self.window_size = (config.window_size_left, config.window_size_right)
255
+
256
+ if (self.head_dim * self.num_heads) != self.hidden_size:
257
+ raise ValueError(
258
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
259
+ f" and `num_heads`: {self.num_heads})."
260
+ )
261
+
262
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
263
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
264
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
265
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
266
+ self._init_rope()
267
+
268
+ def _init_rope(self):
269
+ if self.config.rope_scaling is None:
270
+ self.rotary_emb = LlamaEncRotaryEmbedding(
271
+ self.head_dim,
272
+ max_position_embeddings=self.max_position_embeddings,
273
+ base=self.rope_theta,
274
+ )
275
+ else:
276
+ scaling_type = self.config.rope_scaling["type"]
277
+ scaling_factor = self.config.rope_scaling["factor"]
278
+ if scaling_type == "linear":
279
+ self.rotary_emb = LlamaEncLinearScalingRotaryEmbedding(
280
+ self.head_dim,
281
+ max_position_embeddings=self.max_position_embeddings,
282
+ scaling_factor=scaling_factor,
283
+ base=self.rope_theta,
284
+ )
285
+ elif scaling_type == "dynamic":
286
+ self.rotary_emb = LlamaEncDynamicNTKScalingRotaryEmbedding(
287
+ self.head_dim,
288
+ max_position_embeddings=self.max_position_embeddings,
289
+ scaling_factor=scaling_factor,
290
+ base=self.rope_theta,
291
+ )
292
+ else:
293
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
294
+
295
+ def forward(
296
+ self,
297
+ hidden_states: torch.Tensor,
298
+ attention_mask: Optional[torch.Tensor] = None,
299
+ position_ids: Optional[torch.LongTensor] = None,
300
+ output_attentions: bool = False,
301
+ **kwargs,
302
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
303
+ bsz, q_len, _ = hidden_states.size()
304
+
305
+ if self.config.pretraining_tp > 1:
306
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
307
+ query_slices = self.q_proj.weight.split(
308
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
309
+ )
310
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
311
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
312
+
313
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
314
+ query_states = torch.cat(query_states, dim=-1)
315
+
316
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
317
+ key_states = torch.cat(key_states, dim=-1)
318
+
319
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
320
+ value_states = torch.cat(value_states, dim=-1)
321
+
322
+ else:
323
+ query_states = self.q_proj(hidden_states)
324
+ key_states = self.k_proj(hidden_states)
325
+ value_states = self.v_proj(hidden_states)
326
+
327
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
328
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
329
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
330
+
331
+ cos, sin = self.rotary_emb(value_states, position_ids)
332
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
333
+
334
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
335
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
336
+
337
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
338
+
339
+ if attention_mask is not None: # no matter the length, we just slice it
340
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
341
+ attn_weights = attn_weights + causal_mask
342
+
343
+ # upcast attention to fp32
344
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
345
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
346
+ attn_output = torch.matmul(attn_weights, value_states)
347
+
348
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
349
+ raise ValueError(
350
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
351
+ f" {attn_output.size()}"
352
+ )
353
+
354
+ attn_output = attn_output.transpose(1, 2).contiguous()
355
+
356
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
357
+
358
+ if self.config.pretraining_tp > 1:
359
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
360
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
361
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
362
+ else:
363
+ attn_output = self.o_proj(attn_output)
364
+
365
+ if not output_attentions:
366
+ attn_weights = None
367
+
368
+ return attn_output, attn_weights
369
+
370
+
371
+ class LlamaEncFlashAttention2(LlamaEncAttention):
372
+ """
373
+ LlamaEnc flash attention module. This module inherits from `LlamaEncAttention` as the weights of the module stays
374
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
375
+ flash attention and deal with padding tokens in case the input contains any of them.
376
+ """
377
+
378
+ def __init__(self, *args, **kwargs):
379
+ super().__init__(*args, **kwargs)
380
+
381
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
382
+ # 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.
383
+ # 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).
384
+
385
+ def forward(
386
+ self,
387
+ hidden_states: torch.Tensor,
388
+ attention_mask: Optional[torch.LongTensor] = None,
389
+ position_ids: Optional[torch.LongTensor] = None,
390
+ output_attentions: bool = False,
391
+ **kwargs,
392
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
393
+ output_attentions = False
394
+
395
+ bsz, q_len, _ = hidden_states.size()
396
+
397
+ query_states = self.q_proj(hidden_states)
398
+ key_states = self.k_proj(hidden_states)
399
+ value_states = self.v_proj(hidden_states)
400
+
401
+ # Flash attention requires the input to have the shape
402
+ # batch_size x seq_length x head_dim x hidden_dim
403
+ # therefore we just need to keep the original shape
404
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
405
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
406
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
407
+
408
+ cos, sin = self.rotary_emb(value_states, position_ids)
409
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
410
+
411
+
412
+ # 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
413
+ # to be able to avoid many of these transpose/reshape/view.
414
+ query_states = query_states.transpose(1, 2)
415
+ key_states = key_states.transpose(1, 2)
416
+ value_states = value_states.transpose(1, 2)
417
+
418
+ dropout_rate = self.attention_dropout if self.training else 0.0
419
+
420
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
421
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
422
+ # cast them back in the correct dtype just to be sure everything works as expected.
423
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
424
+ # in fp32. (LlamaEncRMSNorm handles it correctly)
425
+
426
+ input_dtype = query_states.dtype
427
+ if input_dtype == torch.float32:
428
+ if torch.is_autocast_enabled():
429
+ target_dtype = torch.get_autocast_gpu_dtype()
430
+ # Handle the case where the model is quantized
431
+ elif hasattr(self.config, "_pre_quantization_dtype"):
432
+ target_dtype = self.config._pre_quantization_dtype
433
+ else:
434
+ target_dtype = self.q_proj.weight.dtype
435
+
436
+ logger.warning_once(
437
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
438
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
439
+ f" {target_dtype}."
440
+ )
441
+
442
+ query_states = query_states.to(target_dtype)
443
+ key_states = key_states.to(target_dtype)
444
+ value_states = value_states.to(target_dtype)
445
+
446
+ attn_output = self._flash_attention_forward(
447
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
448
+ )
449
+
450
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
451
+ attn_output = self.o_proj(attn_output)
452
+
453
+ if not output_attentions:
454
+ attn_weights = None
455
+
456
+ return attn_output, attn_weights
457
+
458
+ def _flash_attention_forward(
459
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
460
+ ):
461
+ """
462
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
463
+ first unpad the input, then computes the attention scores and pad the final attention scores.
464
+
465
+ Args:
466
+ query_states (`torch.Tensor`):
467
+ Input query states to be passed to Flash Attention API
468
+ key_states (`torch.Tensor`):
469
+ Input key states to be passed to Flash Attention API
470
+ value_states (`torch.Tensor`):
471
+ Input value states to be passed to Flash Attention API
472
+ attention_mask (`torch.Tensor`):
473
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
474
+ position of padding tokens and 1 for the position of non-padding tokens.
475
+ dropout (`float`):
476
+ Attention dropout
477
+ softmax_scale (`float`, *optional*):
478
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
479
+ """
480
+ causal = self.is_causal
481
+
482
+ # Contains at least one padding token in the sequence
483
+ if attention_mask is not None:
484
+ batch_size = query_states.shape[0]
485
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
486
+ query_states, key_states, value_states, attention_mask, query_length
487
+ )
488
+
489
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
490
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
491
+
492
+ attn_output_unpad = flash_attn_varlen_func(
493
+ query_states,
494
+ key_states,
495
+ value_states,
496
+ cu_seqlens_q=cu_seqlens_q,
497
+ cu_seqlens_k=cu_seqlens_k,
498
+ max_seqlen_q=max_seqlen_in_batch_q,
499
+ max_seqlen_k=max_seqlen_in_batch_k,
500
+ dropout_p=dropout,
501
+ softmax_scale=softmax_scale,
502
+ window_size=self.window_size,
503
+ causal=causal,
504
+ )
505
+
506
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
507
+ else:
508
+ attn_output = flash_attn_func(
509
+ query_states,
510
+ key_states,
511
+ value_states,
512
+ dropout,
513
+ softmax_scale=softmax_scale,
514
+ window_size=self.window_size,
515
+ causal=causal
516
+ )
517
+
518
+ return attn_output
519
+
520
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
521
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
522
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
523
+
524
+ key_layer = index_first_axis(
525
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
526
+ )
527
+ value_layer = index_first_axis(
528
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
529
+ )
530
+ if query_length == kv_seq_len:
531
+ query_layer = index_first_axis(
532
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
533
+ )
534
+ cu_seqlens_q = cu_seqlens_k
535
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
536
+ indices_q = indices_k
537
+ elif query_length == 1:
538
+ max_seqlen_in_batch_q = 1
539
+ cu_seqlens_q = torch.arange(
540
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
541
+ ) # There is a memcpy here, that is very bad.
542
+ indices_q = cu_seqlens_q[:-1]
543
+ query_layer = query_layer.squeeze(1)
544
+ else:
545
+ # The -q_len: slice assumes left padding.
546
+ attention_mask = attention_mask[:, -query_length:]
547
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
548
+
549
+ return (
550
+ query_layer,
551
+ key_layer,
552
+ value_layer,
553
+ indices_q,
554
+ (cu_seqlens_q, cu_seqlens_k),
555
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
556
+ )
557
+
558
+ class LlamaEncSdpaAttention(LlamaEncAttention):
559
+ """
560
+ LlamaEnc attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
561
+ `LlamaEncAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
562
+ SDPA API.
563
+ """
564
+
565
+ # Adapted from LlamaEncAttention.forward
566
+ def forward(
567
+ self,
568
+ hidden_states: torch.Tensor,
569
+ attention_mask: Optional[torch.Tensor] = None,
570
+ position_ids: Optional[torch.LongTensor] = None,
571
+ output_attentions: bool = False,
572
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
573
+ if output_attentions:
574
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
575
+ logger.warning_once(
576
+ "LlamaEncModel is using LlamaEncSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
577
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
578
+ )
579
+ return super().forward(
580
+ hidden_states=hidden_states,
581
+ attention_mask=attention_mask,
582
+ position_ids=position_ids,
583
+ output_attentions=output_attentions,
584
+ )
585
+
586
+ bsz, q_len, _ = hidden_states.size()
587
+
588
+ query_states = self.q_proj(hidden_states)
589
+ key_states = self.k_proj(hidden_states)
590
+ value_states = self.v_proj(hidden_states)
591
+
592
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
593
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
594
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
595
+
596
+ cos, sin = self.rotary_emb(value_states, position_ids)
597
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
598
+
599
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
600
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
601
+
602
+ causal_mask = attention_mask
603
+ if attention_mask is not None:
604
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
605
+
606
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
607
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
608
+ if query_states.device.type == "cuda" and causal_mask is not None:
609
+ query_states = query_states.contiguous()
610
+ key_states = key_states.contiguous()
611
+ value_states = value_states.contiguous()
612
+
613
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this if statement instead of an
614
+ # inline conditional assignment to support both torch.compile's `dynamic=True` and `fullgraph=True`
615
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
616
+ query_states,
617
+ key_states,
618
+ value_states,
619
+ attn_mask=causal_mask,
620
+ dropout_p=self.attention_dropout if self.training else 0.0,
621
+ is_causal=False,
622
+ )
623
+
624
+ attn_output = attn_output.transpose(1, 2).contiguous()
625
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
626
+
627
+ attn_output = self.o_proj(attn_output)
628
+
629
+ return attn_output, None
630
+
631
+
632
+ LLAMAENC_ATTENTION_CLASSES = {
633
+ "eager": LlamaEncAttention,
634
+ "flash_attention_2": LlamaEncFlashAttention2,
635
+ "sdpa": LlamaEncSdpaAttention,
636
+ }
637
+
638
+
639
+ class LlamaEncDecoderLayer(nn.Module):
640
+ def __init__(self, config: LlamaEncConfig, layer_idx: int):
641
+ super().__init__()
642
+ self.hidden_size = config.hidden_size
643
+
644
+ self.self_attn = LLAMAENC_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
645
+
646
+ self.mlp = LlamaEncMLP(config)
647
+ self.input_layernorm = LlamaEncRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
648
+ self.post_attention_layernorm = LlamaEncRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
649
+
650
+ def forward(
651
+ self,
652
+ hidden_states: torch.Tensor,
653
+ attention_mask: Optional[torch.Tensor] = None,
654
+ position_ids: Optional[torch.LongTensor] = None,
655
+ output_attentions: Optional[bool] = False,
656
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
657
+ """
658
+ Args:
659
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
660
+ attention_mask (`torch.FloatTensor`, *optional*):
661
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
662
+ query_sequence_length, key_sequence_length)` if default attention is used.
663
+ output_attentions (`bool`, *optional*):
664
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
665
+ returned tensors for more detail.
666
+ use_cache (`bool`, *optional*):
667
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
668
+ (see `past_key_values`).
669
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
670
+ """
671
+ residual = hidden_states
672
+
673
+ hidden_states = self.input_layernorm(hidden_states)
674
+
675
+ # Self Attention
676
+ hidden_states, self_attn_weights = self.self_attn(
677
+ hidden_states=hidden_states,
678
+ attention_mask=attention_mask,
679
+ position_ids=position_ids,
680
+ output_attentions=output_attentions,
681
+ )
682
+ hidden_states = residual + hidden_states
683
+
684
+ # Fully Connected
685
+ residual = hidden_states
686
+ hidden_states = self.post_attention_layernorm(hidden_states)
687
+ hidden_states = self.mlp(hidden_states)
688
+ hidden_states = residual + hidden_states
689
+
690
+ outputs = (hidden_states,)
691
+
692
+ if output_attentions:
693
+ outputs += (self_attn_weights,)
694
+
695
+ return outputs
696
+
697
+
698
+ LLAMAENC_START_DOCSTRING = r"""
699
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
700
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
701
+ etc.)
702
+
703
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
704
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
705
+ and behavior.
706
+
707
+ Parameters:
708
+ config ([`LlamaEncConfig`]):
709
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
710
+ load the weights associated with the model, only the configuration. Check out the
711
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
712
+ """
713
+
714
+
715
+ @add_start_docstrings(
716
+ "The bare LlamaEnc Model outputting raw hidden-states without any specific head on top.",
717
+ LLAMAENC_START_DOCSTRING,
718
+ )
719
+ class LlamaEncPreTrainedModel(PreTrainedModel):
720
+ config_class = LlamaEncConfig
721
+ base_model_prefix = "model"
722
+ supports_gradient_checkpointing = True
723
+ _no_split_modules = ["LlamaEncDecoderLayer"]
724
+ _skip_keys_device_placement = ["past_key_values"]
725
+ _supports_flash_attn_2 = True
726
+ _supports_sdpa = True
727
+ _supports_cache_class = True
728
+ _supports_static_cache = True
729
+
730
+ def _init_weights(self, module):
731
+ std = self.config.initializer_range
732
+ if isinstance(module, nn.Linear):
733
+ module.weight.data.normal_(mean=0.0, std=std)
734
+ if module.bias is not None:
735
+ module.bias.data.zero_()
736
+ elif isinstance(module, nn.Embedding):
737
+ module.weight.data.normal_(mean=0.0, std=std)
738
+ if module.padding_idx is not None:
739
+ module.weight.data[module.padding_idx].zero_()
740
+
741
+
742
+ LLAMAENC_INPUTS_DOCSTRING = r"""
743
+ Args:
744
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
745
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
746
+ it.
747
+
748
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
749
+ [`PreTrainedTokenizer.__call__`] for details.
750
+
751
+ [What are input IDs?](../glossary#input-ids)
752
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
753
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
754
+
755
+ - 1 for tokens that are **not masked**,
756
+ - 0 for tokens that are **masked**.
757
+
758
+ [What are attention masks?](../glossary#attention-mask)
759
+
760
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
761
+ [`PreTrainedTokenizer.__call__`] for details.
762
+
763
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
764
+ `past_key_values`).
765
+
766
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
767
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
768
+ information on the default strategy.
769
+
770
+ - 1 indicates the head is **not masked**,
771
+ - 0 indicates the head is **masked**.
772
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
773
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
774
+ config.n_positions - 1]`.
775
+
776
+ [What are position IDs?](../glossary#position-ids)
777
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
778
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
779
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
780
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
781
+
782
+ Two formats are allowed:
783
+ - a [`~cache_utils.Cache`] instance;
784
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
785
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
786
+ cache format.
787
+
788
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
789
+ legacy cache format will be returned.
790
+
791
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
792
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
793
+ of shape `(batch_size, sequence_length)`.
794
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
795
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
796
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
797
+ model's internal embedding lookup matrix.
798
+ use_cache (`bool`, *optional*):
799
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
800
+ `past_key_values`).
801
+ output_attentions (`bool`, *optional*):
802
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
803
+ tensors for more detail.
804
+ output_hidden_states (`bool`, *optional*):
805
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
806
+ more detail.
807
+ return_dict (`bool`, *optional*):
808
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
809
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
810
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
811
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
812
+ the complete sequence length.
813
+ """
814
+
815
+
816
+ @add_start_docstrings(
817
+ "The bare LlamaEnc Model outputting raw hidden-states without any specific head on top.",
818
+ LLAMAENC_START_DOCSTRING,
819
+ )
820
+ class LlamaEncModel(LlamaEncPreTrainedModel):
821
+ """
822
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaEncDecoderLayer`]
823
+
824
+ Args:
825
+ config: LlamaEncConfig
826
+ """
827
+
828
+ def __init__(self, config: LlamaEncConfig):
829
+ super().__init__(config)
830
+ self.padding_idx = config.pad_token_id
831
+ self.vocab_size = config.vocab_size
832
+
833
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
834
+ self.layers = nn.ModuleList(
835
+ [LlamaEncDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
836
+ )
837
+ self.norm = LlamaEncRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
838
+ self.gradient_checkpointing = False
839
+
840
+ # Initialize weights and apply final processing
841
+ self.post_init()
842
+
843
+ def get_input_embeddings(self):
844
+ return self.embed_tokens
845
+
846
+ def set_input_embeddings(self, value):
847
+ self.embed_tokens = value
848
+
849
+ @add_start_docstrings_to_model_forward(LLAMAENC_INPUTS_DOCSTRING)
850
+ def forward(
851
+ self,
852
+ input_ids: torch.LongTensor = None,
853
+ attention_mask: Optional[torch.Tensor] = None,
854
+ position_ids: Optional[torch.LongTensor] = None,
855
+ inputs_embeds: Optional[torch.FloatTensor] = None,
856
+ output_attentions: Optional[bool] = None,
857
+ output_hidden_states: Optional[bool] = None,
858
+ return_dict: Optional[bool] = None,
859
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
860
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
861
+ output_hidden_states = (
862
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
863
+ )
864
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
865
+
866
+ if (input_ids is None) ^ (inputs_embeds is not None):
867
+ raise ValueError(
868
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
869
+ )
870
+
871
+ if inputs_embeds is None:
872
+ inputs_embeds = self.embed_tokens(input_ids)
873
+
874
+ if position_ids is None:
875
+ position_ids = torch.arange(
876
+ 0, inputs_embeds.shape[1], device=inputs_embeds.device
877
+ ).unsqueeze(0)
878
+
879
+ causal_mask = self._update_causal_mask(
880
+ attention_mask, inputs_embeds, output_attentions
881
+ )
882
+
883
+ # embed positions
884
+ hidden_states = inputs_embeds
885
+
886
+ # decoder layers
887
+ all_hidden_states = () if output_hidden_states else None
888
+ all_self_attns = () if output_attentions else None
889
+
890
+ for decoder_layer in self.layers:
891
+ if output_hidden_states:
892
+ all_hidden_states += (hidden_states,)
893
+
894
+ if self.gradient_checkpointing and self.training:
895
+ layer_outputs = self._gradient_checkpointing_func(
896
+ decoder_layer.__call__,
897
+ hidden_states,
898
+ causal_mask,
899
+ position_ids,
900
+ output_attentions,
901
+ )
902
+ else:
903
+ layer_outputs = decoder_layer(
904
+ hidden_states,
905
+ attention_mask=causal_mask,
906
+ position_ids=position_ids,
907
+ output_attentions=output_attentions,
908
+ )
909
+
910
+ hidden_states = layer_outputs[0]
911
+
912
+
913
+ if output_attentions:
914
+ all_self_attns += (layer_outputs[1],)
915
+
916
+ if output_hidden_states:
917
+ all_hidden_states += (hidden_states,)
918
+ hidden_states = self.norm(hidden_states)
919
+
920
+ # add hidden states from the last decoder layer
921
+ if output_hidden_states:
922
+ all_hidden_states += (hidden_states,)
923
+
924
+
925
+ if not return_dict:
926
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attns] if v is not None)
927
+ return BaseModelOutputWithPast(
928
+ last_hidden_state=hidden_states,
929
+ hidden_states=all_hidden_states,
930
+ attentions=all_self_attns,
931
+ )
932
+
933
+ def _update_causal_mask(
934
+ self,
935
+ attention_mask: torch.Tensor,
936
+ input_tensor: torch.Tensor,
937
+ output_attentions: bool,
938
+ ):
939
+ # 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
940
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
941
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
942
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
943
+ if attention_mask is None:
944
+ return None
945
+
946
+ if self.config._attn_implementation == "flash_attention_2":
947
+ if 0.0 in attention_mask:
948
+ return attention_mask
949
+ return None
950
+
951
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
952
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
953
+ # to infer the attention mask.
954
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
955
+
956
+ if self.config._attn_implementation == "sdpa" and not output_attentions:
957
+ # No padding
958
+ if attention_mask.all():
959
+ return None
960
+
961
+ if attention_mask.dim() == 2:
962
+ return _prepare_4d_attention_mask_for_sdpa(
963
+ attention_mask, input_tensor.dtype, attention_mask.shape[-1]
964
+ )
965
+ if attention_mask is not None and attention_mask.dim() == 4:
966
+ # in this case we assume that the mask comes already in inverted form and requires no inversion or slicing
967
+ if attention_mask.max() != 0:
968
+ raise ValueError("Custom 4D attention mask should be passed in inverted form with max==0`")
969
+ return attention_mask
970
+
971
+ return self.get_extended_attention_mask(
972
+ attention_mask, input_tensor.shape,
973
+ )
974
+
975
+
976
+ class LlamaEncForMaskedLM(LlamaEncPreTrainedModel):
977
+ _tied_weights_keys = ["lm_head.weight"]
978
+
979
+ def __init__(self, config):
980
+ super().__init__(config)
981
+ self.model = LlamaEncModel(config)
982
+ self.vocab_size = config.vocab_size
983
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
984
+
985
+ # Initialize weights and apply final processing
986
+ self.post_init()
987
+
988
+ def get_input_embeddings(self):
989
+ return self.model.embed_tokens
990
+
991
+ def set_input_embeddings(self, value):
992
+ self.model.embed_tokens = value
993
+
994
+ def get_output_embeddings(self):
995
+ return self.lm_head
996
+
997
+ def set_output_embeddings(self, new_embeddings):
998
+ self.lm_head = new_embeddings
999
+
1000
+ def set_decoder(self, decoder):
1001
+ self.model = decoder
1002
+
1003
+ def get_decoder(self):
1004
+ return self.model
1005
+
1006
+ @add_start_docstrings_to_model_forward(LLAMAENC_INPUTS_DOCSTRING)
1007
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1008
+ def forward(
1009
+ self,
1010
+ input_ids: torch.LongTensor = None,
1011
+ attention_mask: Optional[torch.Tensor] = None,
1012
+ position_ids: Optional[torch.LongTensor] = None,
1013
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1014
+ labels: Optional[torch.LongTensor] = None,
1015
+ output_attentions: Optional[bool] = None,
1016
+ output_hidden_states: Optional[bool] = None,
1017
+ return_dict: Optional[bool] = None,
1018
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1019
+ r"""
1020
+ Args:
1021
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1022
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1023
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1024
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1025
+
1026
+ Returns:
1027
+
1028
+ Example:
1029
+
1030
+ ```python
1031
+ >>> from transformers import AutoTokenizer, LlamaEncForCausalLM
1032
+
1033
+ >>> model = LlamaEncForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
1034
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
1035
+
1036
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1037
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1038
+
1039
+ >>> # Generate
1040
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1041
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1042
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1043
+ ```"""
1044
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1045
+ output_hidden_states = (
1046
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1047
+ )
1048
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1049
+
1050
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1051
+ outputs = self.model(
1052
+ input_ids=input_ids,
1053
+ attention_mask=attention_mask,
1054
+ position_ids=position_ids,
1055
+ inputs_embeds=inputs_embeds,
1056
+ output_attentions=output_attentions,
1057
+ output_hidden_states=output_hidden_states,
1058
+ return_dict=return_dict,
1059
+ )
1060
+
1061
+ hidden_states = outputs[0]
1062
+ if self.config.pretraining_tp > 1:
1063
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1064
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1065
+ logits = torch.cat(logits, dim=-1)
1066
+ else:
1067
+ logits = self.lm_head(hidden_states)
1068
+ logits = logits.float()
1069
+
1070
+ loss = None
1071
+ if labels is not None:
1072
+ loss_fct = CrossEntropyLoss(label_smoothing=self.config.label_smoothing)
1073
+ loss = loss_fct(
1074
+ logits.view(-1, self.config.vocab_size),
1075
+ labels.to(logits.device).view(-1)
1076
+ )
1077
+
1078
+ if not return_dict:
1079
+ output = (logits,) + outputs[1:]
1080
+ return (loss,) + output if loss is not None else output
1081
+
1082
+ return CausalLMOutputWithPast(
1083
+ loss=loss,
1084
+ logits=logits,
1085
+ hidden_states=outputs.hidden_states,
1086
+ attentions=outputs.attentions,
1087
+ )
1088
+
1089
+ @add_start_docstrings(
1090
+ """
1091
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
1092
+
1093
+ [`LlamaEncForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1094
+ (e.g. GPT-2) do.
1095
+
1096
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1097
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1098
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1099
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1100
+ each row of the batch).
1101
+ """,
1102
+ LLAMAENC_START_DOCSTRING,
1103
+ )
1104
+ class LlamaEncForSequenceClassification(LlamaEncPreTrainedModel):
1105
+ def __init__(self, config):
1106
+ super().__init__(config)
1107
+ self.num_labels = config.num_labels
1108
+ self.model = LlamaEncModel(config)
1109
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1110
+
1111
+ # Initialize weights and apply final processing
1112
+ self.post_init()
1113
+
1114
+ def get_input_embeddings(self):
1115
+ return self.model.embed_tokens
1116
+
1117
+ def set_input_embeddings(self, value):
1118
+ self.model.embed_tokens = value
1119
+
1120
+ @add_start_docstrings_to_model_forward(LLAMAENC_INPUTS_DOCSTRING)
1121
+ def forward(
1122
+ self,
1123
+ input_ids: torch.LongTensor = None,
1124
+ attention_mask: Optional[torch.Tensor] = None,
1125
+ position_ids: Optional[torch.LongTensor] = None,
1126
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1127
+ labels: Optional[torch.LongTensor] = None,
1128
+ output_attentions: Optional[bool] = None,
1129
+ output_hidden_states: Optional[bool] = None,
1130
+ return_dict: Optional[bool] = None,
1131
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1132
+ r"""
1133
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1134
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1135
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1136
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1137
+ """
1138
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1139
+
1140
+ transformer_outputs = self.model(
1141
+ input_ids,
1142
+ attention_mask=attention_mask,
1143
+ position_ids=position_ids,
1144
+ inputs_embeds=inputs_embeds,
1145
+ output_attentions=output_attentions,
1146
+ output_hidden_states=output_hidden_states,
1147
+ return_dict=return_dict,
1148
+ )
1149
+ hidden_states = transformer_outputs[0]
1150
+ logits = self.score(hidden_states)
1151
+
1152
+ if input_ids is not None:
1153
+ batch_size = input_ids.shape[0]
1154
+ else:
1155
+ batch_size = inputs_embeds.shape[0]
1156
+
1157
+ if self.config.pad_token_id is None and batch_size != 1:
1158
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1159
+ if self.config.pad_token_id is None:
1160
+ sequence_lengths = -1
1161
+ else:
1162
+ if input_ids is not None:
1163
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1164
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1165
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1166
+ sequence_lengths = sequence_lengths.to(logits.device)
1167
+ else:
1168
+ sequence_lengths = -1
1169
+
1170
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1171
+
1172
+ loss = None
1173
+ if labels is not None:
1174
+ labels = labels.to(logits.device)
1175
+ if self.config.problem_type is None:
1176
+ if self.num_labels == 1:
1177
+ self.config.problem_type = "regression"
1178
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1179
+ self.config.problem_type = "single_label_classification"
1180
+ else:
1181
+ self.config.problem_type = "multi_label_classification"
1182
+
1183
+ if self.config.problem_type == "regression":
1184
+ loss_fct = MSELoss()
1185
+ if self.num_labels == 1:
1186
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1187
+ else:
1188
+ loss = loss_fct(pooled_logits, labels)
1189
+ elif self.config.problem_type == "single_label_classification":
1190
+ loss_fct = CrossEntropyLoss()
1191
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1192
+ elif self.config.problem_type == "multi_label_classification":
1193
+ loss_fct = BCEWithLogitsLoss()
1194
+ loss = loss_fct(pooled_logits, labels)
1195
+ if not return_dict:
1196
+ output = (pooled_logits,) + transformer_outputs[1:]
1197
+ return ((loss,) + output) if loss is not None else output
1198
+
1199
+ return SequenceClassifierOutputWithPast(
1200
+ loss=loss,
1201
+ logits=pooled_logits,
1202
+ past_key_values=transformer_outputs.past_key_values,
1203
+ hidden_states=transformer_outputs.hidden_states,
1204
+ attentions=transformer_outputs.attentions,
1205
+ )
1206
+
1207
+
1208
+ @add_start_docstrings(
1209
+ """
1210
+ The LlamaEnc Model transformer with a span classification head on top for extractive question-answering tasks like
1211
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1212
+ """,
1213
+ LLAMAENC_START_DOCSTRING,
1214
+ )
1215
+ class LlamaEncForQuestionAnswering(LlamaEncPreTrainedModel):
1216
+ base_model_prefix = "transformer"
1217
+
1218
+ # Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->LlamaEnc
1219
+ def __init__(self, config):
1220
+ super().__init__(config)
1221
+ self.transformer = LlamaEncModel(config)
1222
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1223
+
1224
+ # Initialize weights and apply final processing
1225
+ self.post_init()
1226
+
1227
+ def get_input_embeddings(self):
1228
+ return self.transformer.embed_tokens
1229
+
1230
+ def set_input_embeddings(self, value):
1231
+ self.transformer.embed_tokens = value
1232
+
1233
+ @add_start_docstrings_to_model_forward(LLAMAENC_INPUTS_DOCSTRING)
1234
+ def forward(
1235
+ self,
1236
+ input_ids: Optional[torch.LongTensor] = None,
1237
+ attention_mask: Optional[torch.FloatTensor] = None,
1238
+ position_ids: Optional[torch.LongTensor] = None,
1239
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1240
+ start_positions: Optional[torch.LongTensor] = None,
1241
+ end_positions: Optional[torch.LongTensor] = None,
1242
+ output_attentions: Optional[bool] = None,
1243
+ output_hidden_states: Optional[bool] = None,
1244
+ return_dict: Optional[bool] = None,
1245
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1246
+ r"""
1247
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1248
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1249
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1250
+ are not taken into account for computing the loss.
1251
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1252
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1253
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1254
+ are not taken into account for computing the loss.
1255
+ """
1256
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1257
+
1258
+ outputs = self.transformer(
1259
+ input_ids,
1260
+ attention_mask=attention_mask,
1261
+ position_ids=position_ids,
1262
+ inputs_embeds=inputs_embeds,
1263
+ output_attentions=output_attentions,
1264
+ output_hidden_states=output_hidden_states,
1265
+ return_dict=return_dict,
1266
+ )
1267
+
1268
+ sequence_output = outputs[0]
1269
+
1270
+ logits = self.qa_outputs(sequence_output)
1271
+ start_logits, end_logits = logits.split(1, dim=-1)
1272
+ start_logits = start_logits.squeeze(-1).contiguous()
1273
+ end_logits = end_logits.squeeze(-1).contiguous()
1274
+
1275
+ total_loss = None
1276
+ if start_positions is not None and end_positions is not None:
1277
+ # If we are on multi-GPU, split add a dimension
1278
+ if len(start_positions.size()) > 1:
1279
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1280
+ if len(end_positions.size()) > 1:
1281
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1282
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1283
+ ignored_index = start_logits.size(1)
1284
+ start_positions = start_positions.clamp(0, ignored_index)
1285
+ end_positions = end_positions.clamp(0, ignored_index)
1286
+
1287
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1288
+ start_loss = loss_fct(start_logits, start_positions)
1289
+ end_loss = loss_fct(end_logits, end_positions)
1290
+ total_loss = (start_loss + end_loss) / 2
1291
+
1292
+ if not return_dict:
1293
+ output = (start_logits, end_logits) + outputs[2:]
1294
+ return ((total_loss,) + output) if total_loss is not None else output
1295
+
1296
+ return QuestionAnsweringModelOutput(
1297
+ loss=total_loss,
1298
+ start_logits=start_logits,
1299
+ end_logits=end_logits,
1300
+ hidden_states=outputs.hidden_states,
1301
+ attentions=outputs.attentions,
1302
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<extra_id_0>",
4
+ "<extra_id_1>",
5
+ "<extra_id_2>",
6
+ "<extra_id_3>",
7
+ "<extra_id_4>",
8
+ "<extra_id_5>",
9
+ "<extra_id_6>",
10
+ "<extra_id_7>",
11
+ "<extra_id_8>",
12
+ "<extra_id_9>",
13
+ "<extra_id_10>",
14
+ "<extra_id_11>",
15
+ "<extra_id_12>",
16
+ "<extra_id_13>",
17
+ "<extra_id_14>",
18
+ "<extra_id_15>",
19
+ "<extra_id_16>",
20
+ "<extra_id_17>",
21
+ "<extra_id_18>",
22
+ "<extra_id_19>",
23
+ "<extra_id_20>",
24
+ "<extra_id_21>",
25
+ "<extra_id_22>",
26
+ "<extra_id_23>",
27
+ "<extra_id_24>",
28
+ "<extra_id_25>"
29
+ ],
30
+ "bos_token": {
31
+ "content": "<s>",
32
+ "lstrip": false,
33
+ "normalized": true,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ },
37
+ "cls_token": {
38
+ "content": "<cls>",
39
+ "lstrip": false,
40
+ "normalized": true,
41
+ "rstrip": false,
42
+ "single_word": false
43
+ },
44
+ "eos_token": {
45
+ "content": "</s>",
46
+ "lstrip": false,
47
+ "normalized": true,
48
+ "rstrip": false,
49
+ "single_word": false
50
+ },
51
+ "mask_token": {
52
+ "content": "<mask>",
53
+ "lstrip": false,
54
+ "normalized": true,
55
+ "rstrip": false,
56
+ "single_word": false
57
+ },
58
+ "pad_token": {
59
+ "content": "<pad>",
60
+ "lstrip": false,
61
+ "normalized": true,
62
+ "rstrip": false,
63
+ "single_word": false
64
+ },
65
+ "sep_token": {
66
+ "content": "<sep>",
67
+ "lstrip": false,
68
+ "normalized": true,
69
+ "rstrip": false,
70
+ "single_word": false
71
+ }
72
+ }
tokenization_byte.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 T5 Authors and HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization class for model ByT5."""
16
+
17
+ import warnings
18
+ from typing import List, Optional, Tuple
19
+
20
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
21
+ from transformers.utils import logging
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class ByteTokenizer(PreTrainedTokenizer):
27
+ """
28
+ Construct a ByT5 tokenizer. ByT5 simply uses raw bytes utf-8 encoding.
29
+
30
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
31
+ this superclass for more information regarding those methods.
32
+
33
+ Args:
34
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
35
+ The end of sequence token.
36
+
37
+ <Tip>
38
+
39
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
40
+ The token used is the `sep_token`.
41
+
42
+ </Tip>
43
+
44
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
45
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
46
+ token instead.
47
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
48
+ The token used for padding, for example when batching sequences of different lengths.
49
+ extra_ids (`int`, *optional*, defaults to 125):
50
+ Add a number of extra ids added to the end of the vocabulary for use as sentinels. These tokens are
51
+ accessible as "<extra_id_{%d}>" where "{%d}" is a number between 0 and extra_ids-1. Extra tokens are
52
+ indexed from the end of the vocabulary up to beginning ("<extra_id_0>" is the last token in the vocabulary
53
+ like in ByT5 preprocessing see
54
+ [here](https://github.com/google-research/text-to-text-transfer-transformer/blob/9fd7b14a769417be33bc6c850f9598764913c833/t5/data/preprocessors.py#L2117)).
55
+ additional_special_tokens (`List[str]`, *optional*):
56
+ Additional special tokens used by the tokenizer.
57
+ """
58
+
59
+ model_input_names = ["input_ids", "attention_mask"]
60
+
61
+ def __init__(
62
+ self,
63
+ bos_token="<s>",
64
+ eos_token="</s>",
65
+ pad_token="<pad>",
66
+ cls_token="<cls>",
67
+ sep_token="<sep>",
68
+ mask_token="<mask>",
69
+ extra_ids=26,
70
+ additional_special_tokens=None,
71
+ **kwargs,
72
+ ) -> None:
73
+ # Add extra_ids to the special token list
74
+ if extra_ids > 0 and additional_special_tokens is None:
75
+ additional_special_tokens = [f"<extra_id_{i}>" for i in range(extra_ids)]
76
+ elif extra_ids > 0 and additional_special_tokens is not None and len(additional_special_tokens) > 0:
77
+ # Check that we have the right number of extra_id special tokens
78
+ extra_tokens = len(set(filter(lambda x: bool("extra_id" in str(x)), additional_special_tokens)))
79
+ if extra_tokens != extra_ids:
80
+ raise ValueError(
81
+ f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"
82
+ " provided to ByteTokenizer. In this case the additional_special_tokens must include the"
83
+ " extra_ids tokens"
84
+ )
85
+
86
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
87
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
88
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
89
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
90
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
91
+ mask_token = AddedToken(mask_token, lstrip=False, rstrip=False) if isinstance(mask_token, str) else mask_token
92
+
93
+ # unk token needs to be in the vocab with correct index
94
+ self._added_tokens_decoder = {0: pad_token, 1: eos_token, 2: bos_token, 3: cls_token, 4: sep_token, 5: mask_token}
95
+ self.offset = len(self._added_tokens_decoder)
96
+ self._utf_vocab_size = 2**8 # utf is 8 bits
97
+ super().__init__(
98
+ bos_token=bos_token,
99
+ eos_token=eos_token,
100
+ pad_token=pad_token,
101
+ cls_token=cls_token,
102
+ sep_token=sep_token,
103
+ mask_token=mask_token,
104
+ extra_ids=0,
105
+ additional_special_tokens=additional_special_tokens, # TODO extra ids are not used :sweatywmile:
106
+ **kwargs,
107
+ )
108
+
109
+ @property
110
+ def vocab_size(self):
111
+ return self._utf_vocab_size
112
+
113
+ def get_vocab(self):
114
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size + self.offset)}
115
+ vocab.update(self.added_tokens_encoder)
116
+ return vocab
117
+
118
+ def _add_eos_if_not_present(self, token_ids: List[int]) -> List[int]:
119
+ """Do not add eos again if user already added it."""
120
+ if len(token_ids) > 0 and token_ids[-1] == self.eos_token_id:
121
+ warnings.warn(
122
+ f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated"
123
+ " eos tokens being added."
124
+ )
125
+ return token_ids
126
+ else:
127
+ return token_ids + [self.eos_token_id]
128
+
129
+
130
+ def _add_bos_if_not_present(self, token_ids: List[int]) -> List[int]:
131
+ """Do not add bos again if user already added it."""
132
+ if len(token_ids) > 0 and token_ids[0] == self.bos_token_id:
133
+ warnings.warn(
134
+ f"This sequence already has {self.bos_token}. In future versions this behavior may lead to duplicated"
135
+ " bos tokens being added."
136
+ )
137
+ return token_ids
138
+ else:
139
+ return [self.bos_token_id] + token_ids
140
+
141
+
142
+ def build_inputs_with_special_tokens(
143
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
144
+ ) -> List[int]:
145
+ """
146
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
147
+ adding special tokens. A sequence has the following format:
148
+
149
+ - single sequence: `X </s>`
150
+ - pair of sequences: `A </s> B </s>`
151
+
152
+ Args:
153
+ token_ids_0 (`List[int]`):
154
+ List of IDs to which the special tokens will be added.
155
+ token_ids_1 (`List[int]`, *optional*):
156
+ Optional second list of IDs for sequence pairs.
157
+
158
+ Returns:
159
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
160
+ """
161
+ token_ids_0 = self._add_bos_if_not_present(token_ids_0)
162
+ token_ids_0 = self._add_eos_if_not_present(token_ids_0)
163
+ if token_ids_1 is None:
164
+ return token_ids_0
165
+ else:
166
+ token_ids_1 = self._add_bos_if_not_present(token_ids_1)
167
+ token_ids_1 = self._add_eos_if_not_present(token_ids_1)
168
+ return token_ids_0 + token_ids_1
169
+
170
+ def _tokenize(self, text: str) -> List[str]:
171
+ """Take as input a string and return a list of strings (tokens) for words/sub-words"""
172
+ tokens = [chr(i) for i in text.encode("utf-8")]
173
+ return tokens
174
+
175
+ def _convert_token_to_id(self, token):
176
+ """Converts a token (str) in an id using the vocab."""
177
+
178
+ if len(token) != 1:
179
+ token_id = None
180
+ else:
181
+ token_id = ord(token) + self.offset
182
+
183
+ return token_id
184
+
185
+ def _convert_id_to_token(self, index):
186
+ """Converts an index (integer) in a token (str) using the vocab."""
187
+ token = chr(index - self.offset)
188
+ return token
189
+
190
+ def convert_tokens_to_string(self, tokens):
191
+ """Converts a sequence of tokens (string) in a single string."""
192
+ bstring = b""
193
+ for token in tokens:
194
+ if token in self.added_tokens_decoder:
195
+ tok_string = self.added_tokens_decoder[token].encode("utf-8")
196
+ elif token in self.added_tokens_encoder:
197
+ tok_string = token.encode("utf-8")
198
+ else:
199
+ tok_string = bytes([ord(token)])
200
+ bstring += tok_string
201
+ string = bstring.decode("utf-8", errors="ignore")
202
+ return string
203
+
204
+ # ByteTokenizer has no vocab file
205
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
206
+ return ()
tokenizer_config.json ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<pad>",
5
+ "lstrip": false,
6
+ "normalized": true,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "</s>",
13
+ "lstrip": false,
14
+ "normalized": true,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "<s>",
21
+ "lstrip": false,
22
+ "normalized": true,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "<cls>",
29
+ "lstrip": false,
30
+ "normalized": true,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "4": {
36
+ "content": "<sep>",
37
+ "lstrip": false,
38
+ "normalized": true,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ },
43
+ "5": {
44
+ "content": "<mask>",
45
+ "lstrip": false,
46
+ "normalized": true,
47
+ "rstrip": false,
48
+ "single_word": false,
49
+ "special": true
50
+ },
51
+ "262": {
52
+ "content": "<extra_id_0>",
53
+ "lstrip": false,
54
+ "normalized": false,
55
+ "rstrip": false,
56
+ "single_word": false,
57
+ "special": true
58
+ },
59
+ "263": {
60
+ "content": "<extra_id_1>",
61
+ "lstrip": false,
62
+ "normalized": false,
63
+ "rstrip": false,
64
+ "single_word": false,
65
+ "special": true
66
+ },
67
+ "264": {
68
+ "content": "<extra_id_2>",
69
+ "lstrip": false,
70
+ "normalized": false,
71
+ "rstrip": false,
72
+ "single_word": false,
73
+ "special": true
74
+ },
75
+ "265": {
76
+ "content": "<extra_id_3>",
77
+ "lstrip": false,
78
+ "normalized": false,
79
+ "rstrip": false,
80
+ "single_word": false,
81
+ "special": true
82
+ },
83
+ "266": {
84
+ "content": "<extra_id_4>",
85
+ "lstrip": false,
86
+ "normalized": false,
87
+ "rstrip": false,
88
+ "single_word": false,
89
+ "special": true
90
+ },
91
+ "267": {
92
+ "content": "<extra_id_5>",
93
+ "lstrip": false,
94
+ "normalized": false,
95
+ "rstrip": false,
96
+ "single_word": false,
97
+ "special": true
98
+ },
99
+ "268": {
100
+ "content": "<extra_id_6>",
101
+ "lstrip": false,
102
+ "normalized": false,
103
+ "rstrip": false,
104
+ "single_word": false,
105
+ "special": true
106
+ },
107
+ "269": {
108
+ "content": "<extra_id_7>",
109
+ "lstrip": false,
110
+ "normalized": false,
111
+ "rstrip": false,
112
+ "single_word": false,
113
+ "special": true
114
+ },
115
+ "270": {
116
+ "content": "<extra_id_8>",
117
+ "lstrip": false,
118
+ "normalized": false,
119
+ "rstrip": false,
120
+ "single_word": false,
121
+ "special": true
122
+ },
123
+ "271": {
124
+ "content": "<extra_id_9>",
125
+ "lstrip": false,
126
+ "normalized": false,
127
+ "rstrip": false,
128
+ "single_word": false,
129
+ "special": true
130
+ },
131
+ "272": {
132
+ "content": "<extra_id_10>",
133
+ "lstrip": false,
134
+ "normalized": false,
135
+ "rstrip": false,
136
+ "single_word": false,
137
+ "special": true
138
+ },
139
+ "273": {
140
+ "content": "<extra_id_11>",
141
+ "lstrip": false,
142
+ "normalized": false,
143
+ "rstrip": false,
144
+ "single_word": false,
145
+ "special": true
146
+ },
147
+ "274": {
148
+ "content": "<extra_id_12>",
149
+ "lstrip": false,
150
+ "normalized": false,
151
+ "rstrip": false,
152
+ "single_word": false,
153
+ "special": true
154
+ },
155
+ "275": {
156
+ "content": "<extra_id_13>",
157
+ "lstrip": false,
158
+ "normalized": false,
159
+ "rstrip": false,
160
+ "single_word": false,
161
+ "special": true
162
+ },
163
+ "276": {
164
+ "content": "<extra_id_14>",
165
+ "lstrip": false,
166
+ "normalized": false,
167
+ "rstrip": false,
168
+ "single_word": false,
169
+ "special": true
170
+ },
171
+ "277": {
172
+ "content": "<extra_id_15>",
173
+ "lstrip": false,
174
+ "normalized": false,
175
+ "rstrip": false,
176
+ "single_word": false,
177
+ "special": true
178
+ },
179
+ "278": {
180
+ "content": "<extra_id_16>",
181
+ "lstrip": false,
182
+ "normalized": false,
183
+ "rstrip": false,
184
+ "single_word": false,
185
+ "special": true
186
+ },
187
+ "279": {
188
+ "content": "<extra_id_17>",
189
+ "lstrip": false,
190
+ "normalized": false,
191
+ "rstrip": false,
192
+ "single_word": false,
193
+ "special": true
194
+ },
195
+ "280": {
196
+ "content": "<extra_id_18>",
197
+ "lstrip": false,
198
+ "normalized": false,
199
+ "rstrip": false,
200
+ "single_word": false,
201
+ "special": true
202
+ },
203
+ "281": {
204
+ "content": "<extra_id_19>",
205
+ "lstrip": false,
206
+ "normalized": false,
207
+ "rstrip": false,
208
+ "single_word": false,
209
+ "special": true
210
+ },
211
+ "282": {
212
+ "content": "<extra_id_20>",
213
+ "lstrip": false,
214
+ "normalized": false,
215
+ "rstrip": false,
216
+ "single_word": false,
217
+ "special": true
218
+ },
219
+ "283": {
220
+ "content": "<extra_id_21>",
221
+ "lstrip": false,
222
+ "normalized": false,
223
+ "rstrip": false,
224
+ "single_word": false,
225
+ "special": true
226
+ },
227
+ "284": {
228
+ "content": "<extra_id_22>",
229
+ "lstrip": false,
230
+ "normalized": false,
231
+ "rstrip": false,
232
+ "single_word": false,
233
+ "special": true
234
+ },
235
+ "285": {
236
+ "content": "<extra_id_23>",
237
+ "lstrip": false,
238
+ "normalized": false,
239
+ "rstrip": false,
240
+ "single_word": false,
241
+ "special": true
242
+ },
243
+ "286": {
244
+ "content": "<extra_id_24>",
245
+ "lstrip": false,
246
+ "normalized": false,
247
+ "rstrip": false,
248
+ "single_word": false,
249
+ "special": true
250
+ },
251
+ "287": {
252
+ "content": "<extra_id_25>",
253
+ "lstrip": false,
254
+ "normalized": false,
255
+ "rstrip": false,
256
+ "single_word": false,
257
+ "special": true
258
+ }
259
+ },
260
+ "additional_special_tokens": [
261
+ "<extra_id_0>",
262
+ "<extra_id_1>",
263
+ "<extra_id_2>",
264
+ "<extra_id_3>",
265
+ "<extra_id_4>",
266
+ "<extra_id_5>",
267
+ "<extra_id_6>",
268
+ "<extra_id_7>",
269
+ "<extra_id_8>",
270
+ "<extra_id_9>",
271
+ "<extra_id_10>",
272
+ "<extra_id_11>",
273
+ "<extra_id_12>",
274
+ "<extra_id_13>",
275
+ "<extra_id_14>",
276
+ "<extra_id_15>",
277
+ "<extra_id_16>",
278
+ "<extra_id_17>",
279
+ "<extra_id_18>",
280
+ "<extra_id_19>",
281
+ "<extra_id_20>",
282
+ "<extra_id_21>",
283
+ "<extra_id_22>",
284
+ "<extra_id_23>",
285
+ "<extra_id_24>",
286
+ "<extra_id_25>"
287
+ ],
288
+ "auto_map": {
289
+ "AutoTokenizer": [
290
+ "tokenization_byte.ByteTokenizer",
291
+ null
292
+ ]
293
+ },
294
+ "bos_token": "<s>",
295
+ "clean_up_tokenization_spaces": true,
296
+ "cls_token": "<cls>",
297
+ "eos_token": "</s>",
298
+ "extra_ids": 0,
299
+ "mask_token": "<mask>",
300
+ "model_max_length": 1000000000000000019884624838656,
301
+ "pad_token": "<pad>",
302
+ "sep_token": "<sep>",
303
+ "tokenizer_class": "ByteTokenizer"
304
+ }