quockhangdev commited on
Commit
f5c1628
·
verified ·
1 Parent(s): 18e5878

PhysicsLM4.2-8B

Browse files
.gitattributes CHANGED
@@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ PhysicsLM4.2-8B/plots/curve-mmlu.png filter=lfs diff=lfs merge=lfs -text
37
+ PhysicsLM4.2-8B/plots/model-training-time.png filter=lfs diff=lfs merge=lfs -text
38
+ PhysicsLM4.2-8B/plots/table-params.png filter=lfs diff=lfs merge=lfs -text
39
+ PhysicsLM4.2-8B/plots/table-performance.png filter=lfs diff=lfs merge=lfs -text
PhysicsLM4.2-8B/.gitattributes ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ plots/curve-mmlu.png filter=lfs diff=lfs merge=lfs -text
37
+ plots/model-evaluation-cropped.png filter=lfs diff=lfs merge=lfs -text
38
+ plots/model-evaluation.png filter=lfs diff=lfs merge=lfs -text
39
+ plots/model-training-time.png filter=lfs diff=lfs merge=lfs -text
40
+ plots/table-params.png filter=lfs diff=lfs merge=lfs -text
41
+ plots/table-performance.png filter=lfs diff=lfs merge=lfs -text
PhysicsLM4.2-8B/README.md ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ extra_gated_fields:
4
+ First Name: text
5
+ Last Name: text
6
+ Date of birth: date_picker
7
+ Country: country
8
+ Affiliation: text
9
+ Job title:
10
+ type: select
11
+ options:
12
+ - Student
13
+ - Research Graduate
14
+ - AI researcher
15
+ - AI developer/engineer
16
+ - Reporter
17
+ - Other
18
+ geo: ip_location
19
+ By clicking Submit below I accept the terms of the license and acknowledge that the information I provide will be collected stored processed and shared in accordance with the Meta Privacy Policy: checkbox
20
+ extra_gated_description: >-
21
+ The information you provide will be collected, stored, processed and shared in
22
+ accordance with the [Meta Privacy
23
+ Policy](https://www.facebook.com/privacy/policy/).
24
+ extra_gated_button_content: Submit
25
+ language:
26
+ - en
27
+ tags:
28
+ - <relevant tags to be included in HF filters>
29
+ ---
30
+
31
+ [![Static Badge](https://img.shields.io/badge/Project_Page-215650)](https://physics.allen-zhu.com/part-4-architecture-design/part-4-1)
32
+ [![Static Badge](https://img.shields.io/badge/Part_4.1-ssrn.5240330-b31b1b?logo=ssrn)](https://ssrn.com/abstract=5240330)
33
+ [![Static Badge](https://img.shields.io/badge/Part_4.1-2512.17351-b31b1b?logo=arxiv)](https://arxiv.org/abs/2512.17351)
34
+ [![Static Badge](https://img.shields.io/badge/Part_4.2-PhysicsLM4-181717?logo=github)](https://github.com/facebookresearch/PhysicsLM4)
35
+ [![Static Badge](https://img.shields.io/badge/HF-PhysicsLM4.2-FFD21E?logo=huggingface)](../../)
36
+
37
+ # Physics of Language Models: Part 4.2, Canon Layers at Scale where Synthetic Pretraining Resonates in Reality
38
+ ## Transformer Model vs. Canon Layers --- LlamaCanon Release
39
+
40
+ Our released paper, [*Physics of Language Models: Part 4.1, Architecture Design and the Magic of Canon Layers*](https://ssrn.com/abstract=5240330), demonstrates that the Canon layer is a powerful architecture add-on that improves language model performance on multiple fronts using a synthetic pretraining playground, perhaps for *every* possible architecture (original Transformer or linear models).
41
+
42
+ In this release, we provide code and pre-trained models to showcase how these findings extend to real-world pretraining. Specifically, we compare the vanilla *Llama architecture* with our modified *LlamaCanon* variant, both pretrained under the same *controlled settings*.
43
+
44
+ <div align="center">
45
+ <img src="plots/model-training-time.png" style="object-fit: contain; display:inline-block;" />
46
+ <em><b>Figure 1:</b> Quick illustration of performance vs. model size/training time.</em>
47
+ </div>
48
+
49
+ ## ✨Highlights of the Release
50
+
51
+ 1. **Broad Model Availability**: We release **16 base models** (1B, 3B, and 8B) pretrained on the open-sourced [Nemotron-CC](https://research.nvidia.com/labs/adlr/Nemotron-CC/) dataset for 1T or 2T tokens.
52
+ 2. **Controlled Experiment**: In each setting, we pretrain two versions of LlamaCanon (using two learning rates) and compare them against two corresponding versions of the original Llama pretrained with identical hyperparameters. This ensures a rigorous architectural comparison.
53
+ 3. **Performance Gain**: LlamaCanon consistently surpasses Llama in all eight controlled comparisons, achieving, for instance, a 2% gain in the MMLU benchmark.
54
+ 4. **Comparison to Open Models**: Our experiments are benchmarked against open-sourced models trained on similar datasets, ensuring that we study a *realistic pretraining setup* rather than an artificial scenario.
55
+
56
+ ## ⚙️Model Configurations
57
+
58
+ A quick summary of the 16 models we release along with their parameters can be seen below:
59
+ <div align="center">
60
+ <img src="plots/table-params.png" style="object-fit: contain; width: 80%; "/>
61
+ <em><b>Figure 2:</b> Names and parameters of the released models.</em>
62
+ </div>
63
+
64
+ ## 🔗Links
65
+
66
+ <div style="
67
+ display: inline-block;
68
+ transform: scale(0.9);
69
+ transform-origin: top left;
70
+ width: fit-content;
71
+ white-space: nowrap;
72
+ ">
73
+ <a href="https://huggingface.co/facebook/PhysicsLM4.2__Llama-1B-Nemo-1T-lr0.002">
74
+ <img src="https://img.shields.io/badge/Llama-1B--Nemo--1T--lr0.002-white">
75
+ </a>
76
+ <a href="https://huggingface.co/facebook/PhysicsLM4.2__LlamaCanon-1B-Nemo-1T-lr0.002">
77
+ <img src="https://img.shields.io/badge/LlamaCanon-1B--Nemo--1T--lr0.002-white">
78
+ </a>
79
+ <a href="https://huggingface.co/facebook/PhysicsLM4.2__Llama-1B-Nemo-1T-lr0.003">
80
+ <img src="https://img.shields.io/badge/Llama-1B--Nemo--1T--lr0.003-white">
81
+ </a>
82
+ <a href="https://huggingface.co/facebook/PhysicsLM4.2__LlamaCanon-1B-Nemo-1T-lr0.003">
83
+ <img src="https://img.shields.io/badge/LlamaCanon-1B--Nemo--1T--lr0.003-white">
84
+ </a>
85
+ <br/>
86
+ <a href="https://huggingface.co/facebook/PhysicsLM4.2__Llama-1B-Nemo-2T-lr0.003">
87
+ <img src="https://img.shields.io/badge/Llama-1B--Nemo--2T--lr0.003-white">
88
+ </a>
89
+ <a href="https://huggingface.co/facebook/PhysicsLM4.2__LlamaCanon-1B-Nemo-2T-lr0.003">
90
+ <img src="https://img.shields.io/badge/LlamaCanon-1B--Nemo--2T--lr0.003-white">
91
+ </a>
92
+ <a href="https://huggingface.co/facebook/PhysicsLM4.2__Llama-1B-Nemo-2T-lr0.005">
93
+ <img src="https://img.shields.io/badge/Llama-1B--Nemo--2T--lr0.005-white">
94
+ </a>
95
+ <a href="https://huggingface.co/facebook/PhysicsLM4.2__LlamaCanon-1B-Nemo-2T-lr0.005">
96
+ <img src="https://img.shields.io/badge/LlamaCanon-1B--Nemo--2T--lr0.005-white">
97
+ </a>
98
+ <br/>
99
+ <a href="https://huggingface.co/facebook/PhysicsLM4.2__Llama-3B-Nemo-1T-lr0.002">
100
+ <img src="https://img.shields.io/badge/Llama-3B--Nemo--1T--lr0.002-white">
101
+ </a>
102
+ <a href="https://huggingface.co/facebook/PhysicsLM4.2__LlamaCanon-3B-Nemo-1T-lr0.002">
103
+ <img src="https://img.shields.io/badge/LlamaCanon-3B--Nemo--1T--lr0.002-white">
104
+ </a>
105
+ <a href="https://huggingface.co/facebook/PhysicsLM4.2__Llama-3B-Nemo-1T-lr0.003">
106
+ <img src="https://img.shields.io/badge/Llama-3B--Nemo--1T--lr0.003-white">
107
+ </a>
108
+ <a href="https://huggingface.co/facebook/PhysicsLM4.2__LlamaCanon-3B-Nemo-1T-lr0.003">
109
+ <img src="https://img.shields.io/badge/LlamaCanon-3B--Nemo--1T--lr0.003-white">
110
+ </a>
111
+ <br/>
112
+ <a href="https://huggingface.co/facebook/PhysicsLM4.2__Llama-8B-Nemo-1T-lr0.002">
113
+ <img src="https://img.shields.io/badge/Llama-8B--Nemo--1T--lr0.002-white">
114
+ </a>
115
+ <a href="https://huggingface.co/facebook/PhysicsLM4.2__LlamaCanon-8B-Nemo-1T-lr0.002">
116
+ <img src="https://img.shields.io/badge/LlamaCanon-8B--Nemo--1T--lr0.002-white">
117
+ </a>
118
+ <a href="https://huggingface.co/facebook/PhysicsLM4.2__Llama-8B-Nemo-1T-lr0.003">
119
+ <img src="https://img.shields.io/badge/Llama-8B--Nemo--1T--lr0.003-white">
120
+ </a>
121
+ <a href="https://huggingface.co/facebook/PhysicsLM4.2__LlamaCanon-8B-Nemo-1T-lr0.003">
122
+ <img src="https://img.shields.io/badge/LlamaCanon-8B--Nemo--1T--lr0.003-white">
123
+ </a>
124
+ </div>
125
+
126
+ ## 📊Performance Metrics
127
+
128
+ The table below illustrates how LlamaCanon performs in comparison to vanilla Llama models, as well as some open-sourced pretraining benchmarks.
129
+ <div align="center">
130
+ <img src="plots/table-performance.png" style="object-fit: contain;"/>
131
+ <em><b>Figure 3:</b> Cross-benchmark performance evaluation of the released models.</em>
132
+ </div>
133
+
134
+ ### 📈Training Curves
135
+
136
+ To further showcase the advantage of Canon layers over the entirety of the pretraining process, we provide detailed training-time performance curves. Interactive versions and additional benchmark metrics are available in our [GitHub repository](https://github.com/facebookresearch/PhysicsLM4/tree/main/lingua_results).
137
+ <div align="center">
138
+ <img src="plots/curve-mmlu.png" style="object-fit: contain;"/>
139
+ <em><b>Figure 4:</b> MMLU accuracy vs. training tokens.</em>
140
+ </div>
141
+
142
+ ## 📌Model Details
143
+
144
+ - **Model Type:** Llama Transformer + LlamaCanon Transformer
145
+ - **Language:** English
146
+ - **License:** Apache 2.0
147
+ - **Type:** Base model without any instruction fine-tuning or post-training.
148
+ - **Context length:** 4096 tokens (+ ~50% for LlamaCanon).
149
+ - *Note*: The models were pretrained with context length 4096. However, unlike traditional RoPE transformers, LlamaCanon demonstrates strong length generalization, extending to ~50% more tokens (as detailed in [our paper](https://ssrn.com/abstract=5240330)). While long-context fine-tuning could further enhance this capability, we have deliberately avoided it to maintain a clean and controlled comparison of base-model pretraining, highlighting the effectiveness of Canon layers.
150
+
151
+ ## 🧩Installation and Dependencies
152
+
153
+ It is highly recommended to `pip install causal-conv1d` for CUDA efficiency, as our implementation of Canon layers relies on depth-wise `conv1d`.
154
+ The code is tested with `transformers==4.47.1` and `4.53.3` but should be compatible with many earlier versions. Ensure you enable `trust_remote_code=True` to download the architecture code automatically.
155
+
156
+ ## ▶️Demo
157
+
158
+ The following sample demonstrates how to use our pre-trained models:
159
+
160
+ ```python
161
+ from transformers import AutoTokenizer, AutoModelForCausalLM
162
+
163
+ # Choose any of our 16 released models
164
+ # model_name = "facebook/PhysicsLM4.2__LlamaCanon-8B-Nemo-1T-lr0.003"
165
+ model_name = "facebook/PhysicsLM4.2__LlamaCanon-1B-Nemo-2T-lr0.005"
166
+ # model_name = "facebook/PhysicsLM4.2__Llama-3B-Nemo-1T-lr0.003"
167
+
168
+ # Below is simply a wrapper of either the Llama2 tokenizer (for <=3B models)
169
+ # or Llama3 (for 8B models); alternatively, you can download your own
170
+ # Huggingface llama2/3 tokenizers and use that instead
171
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
172
+
173
+ model = AutoModelForCausalLM.from_pretrained(model_name, trust_remote_code=True).cuda()
174
+
175
+ input_text = "Galileo Galilei climbed the Leaning Tower of Pisa to conduct a controlled experiment."
176
+ inputs = tokenizer(input_text, return_tensors="pt")
177
+ output_ids = model.generate(inputs['input_ids'].cuda(), max_new_tokens=50)
178
+ print(tokenizer.decode(output_ids[0], skip_special_tokens=True))
179
+ ```
180
+
181
+ ## ⚠️Bias, Risks, and Limitations
182
+
183
+ The models are released for research purposes only (mainly for controlled experiments comparing Llama and LlamaCanon) and are not intended for applications requiring high factual accuracy, safety-critical use cases, or medical/health contexts. The models were pretrained on open datasets and are not safety- or alignment-tuned, meaning:
184
+
185
+ - They may generate content that is factually incorrect, biased, harmful, or offensive.
186
+ - Outputs may include objectionable content even if such outcomes weren't explicitly intended.
187
+ - Users are responsible for ensuring appropriate evaluation and implementing additional filtering or safety mechanisms suitable for their specific use cases.
188
+
189
+ ---
190
+
191
+ ## 📖Citation
192
+
193
+ Please cite the following if you use our models or findings in your research:
194
+ ```bibtex
195
+ @inproceedings{Allen2025-canon,
196
+ author = {{Allen-Zhu}, Zeyuan},
197
+ title = {{Physics of Language Models: Part 4.1, Architecture Design and the Magic of Canon Layers}},
198
+ year = {2025},
199
+ booktitle = {Proceedings of the 39th Conference on Neural Information Processing Systems},
200
+ series = {NeurIPS~'25},
201
+ note = {Full version available at \url{https://ssrn.com/abstract=5240330}}
202
+ }
203
+ @misc{Allen2025-resonate,
204
+ title = {{Physics of Language Models: Part 4.2, Canon Layers at Scale where Synthetic Pretraining Resonates in Reality}},
205
+ author = {{Allen-Zhu}, Zeyuan},
206
+ year = {2025},
207
+ url = {https://physics.allen-zhu.com/part-4-architecture-design/part-4-2},
208
+ note = {Code released at \url{https://github.com/facebookresearch/PhysicsLM4}},
209
+ }
210
+ ```
211
+
212
+ ## Additional Resources
213
+
214
+ - [GitHub Repository](https://github.com/facebookresearch/PhysicsLM4) includes
215
+ - Full training recipes, model configurations, and interactive plots (on all benchmarks).
216
+
217
+ ## Model Card Author
218
+
219
+ - Zeyuan Allen-Zhu
PhysicsLM4.2-8B/config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "LlamaCanon",
3
+ "auto_map": {
4
+ "AutoConfig": "merged_llama_canon.LlamaCanonConfig",
5
+ "AutoModelForCausalLM": "merged_llama_canon.LlamaCanonForCausalLM",
6
+ "AutoTokenizer": [
7
+ "tokenization_llama_canon.LlamaCanonTokenizer",
8
+ "tokenization_llama_canon.LlamaCanonTokenizer"
9
+ ]
10
+ }
11
+ }
PhysicsLM4.2-8B/default/consolidated.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:27d1e6ccc1d63373caa8095970c86ba353c0abd643895643cca4b294af435598
3
+ size 32143201275
PhysicsLM4.2-8B/default/params.json ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "comment": "Note: this is not the full params file used for training (see our github repo), but sufficient for model loading",
3
+ "data": {
4
+ "add_bos": true,
5
+ "add_eos": true,
6
+ "batch_size": 3,
7
+ "load_async": true,
8
+ "n_views": 2,
9
+ "prefetch_size": 1024,
10
+ "root_dir": "<zeyuan_placeholder>",
11
+ "seed": 42,
12
+ "seq_len": 4096,
13
+ "sources": {
14
+ "original_shuffled4": 1.0
15
+ },
16
+ "tokenizer": {
17
+ "name": "tiktoken",
18
+ "path": "<zeyuan_placeholder>"
19
+ }
20
+ },
21
+ "model": {
22
+ "attn_impl": "sdpa",
23
+ "canon_activation": false,
24
+ "canon_bias": false,
25
+ "canon_kernel": 4,
26
+ "canon_residual": true,
27
+ "canon_set": "ABCD",
28
+ "dim": 4096,
29
+ "ffn_dim_multiplier": 1.0,
30
+ "head_dim": null,
31
+ "hidden_dim": 14336,
32
+ "init_base_std": null,
33
+ "init_std_factor": "disabled",
34
+ "max_seqlen": 4096,
35
+ "multiple_of": 256,
36
+ "n_heads": 32,
37
+ "n_kv_heads": 8,
38
+ "n_layers": 32,
39
+ "norm_eps": 1e-05,
40
+ "qk_norm": false,
41
+ "rope_dim": 32,
42
+ "rope_theta": 100000.0,
43
+ "seed": 42,
44
+ "sliding_window": null,
45
+ "vocab_size": 128256,
46
+ "weight_tying": false,
47
+ "z_loss": false
48
+ }
49
+ }
PhysicsLM4.2-8B/merged_llama_canon.py ADDED
@@ -0,0 +1,1546 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ''' This code merges canon_helper.py, configuration_llama_canon.py and modeling_llama_canon.py into a single file to avoid relative imports.'''
2
+
3
+ # configuration_llama_canon.py begins here
4
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
5
+ #
6
+ # This code is modified from the huggingface v4.47-release on the Llama model config
7
+ # Namely: https://github.com/huggingface/transformers/blob/v4.47-release/src/transformers/models/llama/configuration_llama.py
8
+ #
9
+ # Zeyuan's edit note: added support for canon layers, see "Part 4.1, Architecture Design and the Magic of Canon Layers" (https://ssrn.com/abstract=5240330)
10
+ #
11
+ # Zeyuan's edit note: added support for qk_norm, see for instance "Scaling Vision Transformers to 22 Billion Parameters" (arxiv.org/abs/2302.05442)
12
+ #
13
+ # Zeyuan's edit note: added support for rope_dim, which means only rope_dim of head_dim will be used for rotary position embeddings, if None, then all head_dim will be used
14
+ # PS: GPTNeoXModel on HF defaults this to 25% of the head_dim, while Llama model sets this to None
15
+ #
16
+ # Zeyuan's edit note: the lingua codebase has slightly different RoPE implementation (for which coordinates are real/imaginary), and it is not compatible with the huggingface implementation
17
+ # so we added a field to specify the version of RoPE, which is a string that can be either 'huggingface' or 'lingua'
18
+ # When loading a checkpoint trained using the lingua codebase, must set `rope_version='lingua'`
19
+ #
20
+ """LLaMA Canon model configuration"""
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.modeling_rope_utils import rope_config_validation
24
+
25
+
26
+ class LlamaCanonConfig(PretrainedConfig):
27
+
28
+ model_type = "LlamaCanon"
29
+ keys_to_ignore_at_inference = ["past_key_values"]
30
+ # Default tensor parallel plan for base model `LlamaModel`
31
+ base_model_tp_plan = {
32
+ "layers.*.self_attn.q_proj": "colwise",
33
+ "layers.*.self_attn.k_proj": "colwise",
34
+ "layers.*.self_attn.v_proj": "colwise",
35
+ "layers.*.self_attn.o_proj": "rowwise",
36
+ "layers.*.mlp.gate_proj": "colwise",
37
+ "layers.*.mlp.up_proj": "colwise",
38
+ "layers.*.mlp.down_proj": "rowwise",
39
+ }
40
+
41
+ def __init__(
42
+ self,
43
+ vocab_size=32000,
44
+ hidden_size=4096,
45
+ intermediate_size=11008,
46
+ num_hidden_layers=32,
47
+ num_attention_heads=32,
48
+ num_key_value_heads=None,
49
+ hidden_act="silu",
50
+ max_position_embeddings=2048,
51
+ initializer_range=0.02,
52
+ rms_norm_eps=1e-6,
53
+ use_cache=True,
54
+ pad_token_id=None,
55
+ bos_token_id=1,
56
+ eos_token_id=2,
57
+ pretraining_tp=1,
58
+ tie_word_embeddings=False,
59
+ rope_theta=10000.0,
60
+ rope_scaling=None,
61
+ attention_bias=False,
62
+ attention_dropout=0.0,
63
+ mlp_bias=False,
64
+ head_dim=None,
65
+ rope_version='huggingface',
66
+ **kwargs,
67
+ ):
68
+ self.vocab_size = vocab_size
69
+ self.max_position_embeddings = max_position_embeddings
70
+ self.hidden_size = hidden_size
71
+ self.intermediate_size = intermediate_size
72
+ self.num_hidden_layers = num_hidden_layers
73
+ self.num_attention_heads = num_attention_heads
74
+
75
+ # for backward compatibility
76
+ if num_key_value_heads is None:
77
+ num_key_value_heads = num_attention_heads
78
+
79
+ self.num_key_value_heads = num_key_value_heads
80
+ self.hidden_act = hidden_act
81
+ self.initializer_range = initializer_range
82
+ self.rms_norm_eps = rms_norm_eps
83
+ self.pretraining_tp = pretraining_tp
84
+ self.use_cache = use_cache
85
+ self.rope_theta = rope_theta
86
+ self.rope_scaling = rope_scaling
87
+ self.attention_bias = attention_bias
88
+ self.attention_dropout = attention_dropout
89
+ self.mlp_bias = mlp_bias
90
+ self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
91
+ # Validate the correctness of rotary position embeddings parameters
92
+ # BC: if there is a 'type' field, copy it it to 'rope_type'.
93
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
94
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
95
+ rope_config_validation(self)
96
+
97
+ # Zeyuan's edit note: added support for canon layers, see "Part 4.1, Architecture Design and the Magic of Canon Layers" (https://ssrn.com/abstract=5240330)
98
+ self.canon_set = kwargs.pop("canon_set", "")
99
+ self.canon_bias = kwargs.pop("canon_bias", False)
100
+ self.canon_activation = kwargs.pop("canon_activation", False)
101
+ self.canon_kernel = kwargs.pop("canon_kernel", 4)
102
+ self.canon_residual = kwargs.pop("canon_residual", True)
103
+
104
+ # Zeyuan's edit note: added support for qk_norm, see for instance "Scaling Vision Transformers to 22 Billion Parameters" (arxiv.org/abs/2302.05442)
105
+ self.qk_norm = kwargs.pop("qk_norm", False)
106
+
107
+ # Zeyuan's edit note: added support for rope_dim, which means only rope_dim of head_dim will be used for rotary position embeddings, if None, then all head_dim will be used
108
+ # PS: GPTNeoXModel on HF defaults this to 25% of the head_dim, while Llama model sets this to None
109
+ self.rope_dim = kwargs.pop("rope_dim", None)
110
+ if self.rope_dim is not None:
111
+ self.partial_rotary_factor = self.rope_dim / self.head_dim
112
+
113
+ # Zeyuan's edit note: the lingua codebase has slightly different RoPE implementation (for which coordinates are real/imaginary), and it is not compatible with the huggingface implementation
114
+ # so we added a field to specify the version of RoPE, which is a string that can be either 'huggingface' or 'lingua'
115
+ self.rope_version = rope_version
116
+
117
+ super().__init__(
118
+ pad_token_id=pad_token_id,
119
+ bos_token_id=bos_token_id,
120
+ eos_token_id=eos_token_id,
121
+ tie_word_embeddings=tie_word_embeddings,
122
+ **kwargs,
123
+ )
124
+
125
+
126
+ # canon_helper.py begins here
127
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
128
+ #
129
+ from typing import Any, Dict, List, Optional, Tuple
130
+ import torch
131
+
132
+ import warnings
133
+ from typing import Optional, Tuple
134
+
135
+ import torch.nn as nn
136
+ import torch.nn.functional as F
137
+ from einops import rearrange
138
+
139
+ from transformers.activations import ACT2FN
140
+
141
+ try:
142
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
143
+ except ImportError:
144
+ causal_conv1d_fn = None
145
+ causal_conv1d_update = None
146
+
147
+ import torch._dynamo
148
+
149
+ @torch._dynamo.disable
150
+ def causal_conv1d_fn_safe(*args, **kwargs):
151
+ return causal_conv1d_fn(*args, **kwargs)
152
+
153
+ ## This is an exact copy of `fla.modules.ShortConvolution` with no modification
154
+ ## The purpose is to make sure you don't need to install fla-org, which is not a stable package yet.
155
+ class ShortConvolution(nn.Conv1d):
156
+ """
157
+ Simple wrapper around `nn.Conv1d` that accepts dimension last.
158
+ """
159
+
160
+ def __init__(
161
+ self,
162
+ hidden_size: int,
163
+ kernel_size: int,
164
+ bias: bool = False,
165
+ activation: Optional[str] = 'silu',
166
+ use_fast_conv1d: Optional[bool] = True,
167
+ device: Optional[torch.device] = None,
168
+ dtype: Optional[torch.dtype] = None,
169
+ ):
170
+ super().__init__(
171
+ in_channels=hidden_size,
172
+ out_channels=hidden_size,
173
+ kernel_size=kernel_size,
174
+ groups=hidden_size,
175
+ bias=bias,
176
+ padding=kernel_size - 1,
177
+ device=device,
178
+ dtype=dtype,
179
+ )
180
+
181
+ self.hidden_size = hidden_size
182
+ self.activation = None
183
+ if activation is not None:
184
+ assert activation in ['silu', 'swish'], f"Activation `{activation}` not supported yet."
185
+ self.activation = activation
186
+
187
+ if causal_conv1d_fn is None:
188
+ if use_fast_conv1d:
189
+ raise RuntimeError(
190
+ "Please either install `causal-conv1d>=1.4.0` to enable fast causal short convolution CUDA kernel "
191
+ "or set `use_fast_conv1d` to False"
192
+ )
193
+ else:
194
+ warnings.warn(
195
+ "The naive Pytorch verison is very slow in practice, "
196
+ "please run `pip install causal-conv1d>=1.4.0` to install fast causal short convolution CUDA kernel",
197
+ category=ImportWarning
198
+ )
199
+ self.use_fast_conv1d = use_fast_conv1d
200
+
201
+ def __repr__(self): # THIS helps TorchDynamo avoid collisions
202
+ return f"CanonLayerCustom(hidden_size={self.hidden_size})"
203
+
204
+ def extra_repr(self):
205
+ s = ('{in_channels}, {out_channels}, kernel_size={kernel_size}'
206
+ ', stride={stride}')
207
+ if self.padding != (0,) * len(self.padding):
208
+ s += ', padding={padding}'
209
+ if self.dilation != (1,) * len(self.dilation):
210
+ s += ', dilation={dilation}'
211
+ if self.output_padding != (0,) * len(self.output_padding):
212
+ s += ', output_padding={output_padding}'
213
+ if self.groups != 1:
214
+ s += ', groups={groups}'
215
+ if self.bias is None:
216
+ s += ', bias=False'
217
+ if self.padding_mode != 'zeros':
218
+ s += ', padding_mode={padding_mode}'
219
+ if self.activation is not None:
220
+ s += ', activation={activation}'
221
+ if not self.use_fast_conv1d:
222
+ s += ', use_fast_conv1d={use_fast_conv1d}'
223
+ return s.format(**self.__dict__)
224
+
225
+ def forward(
226
+ self,
227
+ x: torch.Tensor,
228
+ mask: Optional[torch.Tensor] = None,
229
+ cache: Optional[torch.Tensor] = None,
230
+ output_final_state: bool = False,
231
+ seq_idx: Optional[torch.Tensor] = None,
232
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
233
+ """
234
+ Args:
235
+ x (`torch.Tensor`):
236
+ Tensor of shape `[batch_size, seq_len, hidden_size]`
237
+ mask (`Optional[torch.Tensor]`):
238
+ Attention mask dealing with padded positions.
239
+ cache (`Optional[torch.Tensor]`):
240
+ Previous cache tensor of shape `[batch_size, hidden_size, kernel_size]`.
241
+ If provided, the cache is updated **inplace**.
242
+ output_final_state (Optional[bool]):
243
+ Whether to output the final state of shape `[batch_size, hidden_size, kernel_size]`. Default: `False`.
244
+ seq_idx (Optional[torch.Tensor]):
245
+ Sequence index for each token. Used for varlen. Default: `None`.
246
+ Shape: [batch_size, seq_len]
247
+ Suppose a batch consists of two sequences with lengths 3 and 4, seq_idx=[0, 0, 0, 1, 1, 1, 1] for this batch.
248
+ Returns:
249
+ Tensor of shape `[batch_size, seq_len, hidden_size]`.
250
+ """
251
+
252
+ batch_size, _, hidden_size = x.shape
253
+ if mask is not None:
254
+ x = x.mul_(mask.unsqueeze(-1))
255
+ if output_final_state and cache is None:
256
+ cache = x.new_zeros(batch_size, hidden_size, self.kernel_size[0])
257
+ if cache is not None and x.shape[1] == 1:
258
+ return self.step(x, cache)
259
+ x = rearrange(x, "b t d -> b d t")
260
+ # Update state (B D W)
261
+ if cache is not None:
262
+ cache.copy_(F.pad(x, (self.kernel_size[0] - x.shape[-1], 0)))
263
+ if self.use_fast_conv1d:
264
+ x = causal_conv1d_fn_safe(
265
+ x=x,
266
+ weight=rearrange(self.weight, "d 1 w -> d w"),
267
+ bias=self.bias,
268
+ activation=self.activation,
269
+ seq_idx=seq_idx,
270
+ )
271
+ else:
272
+ x = self._conv_forward(x, self.weight, self.bias)[..., :x.shape[-1]]
273
+ if self.activation is not None:
274
+ x = ACT2FN[self.activation](x) # Note I'm using huggingface's ACT2FN here, not fla-org's original one, so that you don't need to install fla-org
275
+ return rearrange(x, "b d t -> b t d"), cache
276
+
277
+ def step(
278
+ self,
279
+ x: torch.Tensor,
280
+ cache: torch.Tensor
281
+ ):
282
+ assert x.shape[1] == 1, "Only support decoding with 1 token at a time for now"
283
+
284
+ x = x.squeeze(1)
285
+ if self.use_fast_conv1d:
286
+ x = causal_conv1d_update(
287
+ x=x,
288
+ conv_state=cache,
289
+ weight=rearrange(self.weight, "d 1 w -> d w"),
290
+ bias=self.bias,
291
+ activation=self.activation,
292
+ )
293
+ else:
294
+ dtype = x.dtype
295
+ cache.copy_(torch.roll(cache, shifts=-1, dims=-1))
296
+ cache[:, :, -1] = x
297
+ x = torch.sum(cache * rearrange(self.weight, "d 1 w -> d w"), dim=-1)
298
+ if self.bias is not None:
299
+ x = x + self.bias
300
+ if self.activation is not None:
301
+ x = ACT2FN[self.activation](x).to(dtype=dtype)
302
+ return x.unsqueeze(1), cache
303
+
304
+ @property
305
+ def state_size(self) -> int:
306
+ return self.hidden_size * self.kernel_size
307
+
308
+
309
+
310
+ def create_canon(dim, config):
311
+ canon = ShortConvolution(
312
+ hidden_size=dim,
313
+ kernel_size=config.canon_kernel,
314
+ bias=config.canon_bias,
315
+ activation='silu' if config.canon_activation else None,
316
+ use_fast_conv1d=causal_conv1d_fn is not None and config.canon_kernel in [2, 3, 4],
317
+ )
318
+ if config.canon_bias:
319
+ canon.bias.data = torch.zeros_like(canon.bias)
320
+ assert False, 'must put this into reset_parameters, as the bias default value may be overwritten by the model initialization'
321
+ canon._zeyuan_residual = config.canon_residual
322
+ return canon
323
+
324
+
325
+ # Note this attention_mask must be the 1/0 form (1 for not mask, and 0 for mask), 2D [batch_size, seq_len]
326
+ # This is incompatible with the HF GPT2Model's attention_mask, which is -inf for masked positions
327
+ def apply_canon(store_name, canon, hidden_states, cache, layer_idx, attention_mask):
328
+ if cache is not None and not hasattr(cache, store_name):
329
+ setattr(cache, store_name, [None] * 256) # if you train model deeper than 256 layers (which you shouldn't...), you need to change this number
330
+ conv_state = None
331
+ if cache is not None:
332
+ conv_state = getattr(cache, store_name)[layer_idx]
333
+ if attention_mask is not None:
334
+ print("Inside apply_canon, attention_mask", attention_mask.shape, attention_mask)
335
+ if attention_mask is None:
336
+ conv_mask = None
337
+ elif len(attention_mask.shape)==4:
338
+ assert False, "currently disabled, assuming attention_mask is 2D of the form [batch_size, seq_len]' with 0 and 1's"
339
+ else:
340
+ assert len(attention_mask.shape)==2
341
+ conv_mask = attention_mask[:, -hidden_states.shape[1] :] if attention_mask is not None else None
342
+ hidden_states2, conv_state = canon(x=hidden_states, mask=conv_mask, cache=conv_state, output_final_state=cache is not None)
343
+ if cache is not None:
344
+ getattr(cache, store_name)[layer_idx] = conv_state
345
+ if canon._zeyuan_residual: return hidden_states + hidden_states2
346
+ else: return hidden_states2
347
+
348
+ # modeling_llama_canon.py begins here
349
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
350
+ #
351
+ # This code is modified from the huggingface v4.47-release on the Llama model
352
+ # Namely: https://github.com/huggingface/transformers/blob/v4.47-release/src/transformers/models/llama/modeling_llama.py
353
+ #
354
+ # Zeyuan's edit note: added support for canon layers, see "Part 4.1, Architecture Design and the Magic of Canon Layers" (https://ssrn.com/abstract=5240330)
355
+ #
356
+ # Zeyuan's edit note: added support for qk_norm, see for instance "Scaling Vision Transformers to 22 Billion Parameters" (arxiv.org/abs/2302.05442)
357
+ #
358
+ # Zeyuan's edit note: added support for rope_dim, which means only rope_dim of head_dim will be used for rotary position embeddings, if None, then all head_dim will be used
359
+ # PS: GPTNeoXModel on HF defaults this to 25% of the head_dim, while Llama model sets this to None
360
+ #
361
+ # Zeyuan's edit note: the lingua codebase has slightly different RoPE implementation (for which coordinates are real/imaginary), and it is not compatible with the huggingface implementation
362
+ # so we added a field to specify the version of RoPE, which is a string that can be either 'huggingface' or 'lingua'
363
+ # When loading a checkpoint trained using the lingua codebase, must set `rope_version='lingua'`
364
+ #
365
+ import math
366
+ from typing import List, Optional, Tuple, Union
367
+
368
+ import torch
369
+ import torch.utils.checkpoint
370
+ from torch import nn
371
+
372
+ from transformers.activations import ACT2FN
373
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
374
+ from transformers.generation import GenerationMixin
375
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
376
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs, _flash_attention_forward
377
+ from transformers.modeling_outputs import (
378
+ BaseModelOutputWithPast,
379
+ CausalLMOutputWithPast,
380
+ QuestionAnsweringModelOutput,
381
+ SequenceClassifierOutputWithPast,
382
+ TokenClassifierOutput,
383
+ )
384
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
385
+ from transformers.modeling_utils import PreTrainedModel
386
+ from transformers.processing_utils import Unpack
387
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
388
+ from transformers.utils import (
389
+ LossKwargs,
390
+ add_code_sample_docstrings,
391
+ add_start_docstrings,
392
+ add_start_docstrings_to_model_forward,
393
+ is_flash_attn_greater_or_equal_2_10,
394
+ logging,
395
+ replace_return_docstrings,
396
+ )
397
+
398
+
399
+
400
+ logger = logging.get_logger(__name__)
401
+
402
+
403
+
404
+ class LlamaRMSNorm(nn.Module):
405
+ def __init__(self, hidden_size, eps=1e-6):
406
+ """
407
+ LlamaRMSNorm is equivalent to T5LayerNorm
408
+ """
409
+ super().__init__()
410
+ self.weight = nn.Parameter(torch.ones(hidden_size))
411
+ self.variance_epsilon = eps
412
+
413
+ def forward(self, hidden_states):
414
+ input_dtype = hidden_states.dtype
415
+ hidden_states = hidden_states.to(torch.float32)
416
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
417
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
418
+ return self.weight * hidden_states.to(input_dtype)
419
+
420
+ def extra_repr(self):
421
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
422
+
423
+
424
+ ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
425
+
426
+
427
+ class LlamaRotaryEmbedding(nn.Module):
428
+ def __init__(
429
+ self,
430
+ dim=None,
431
+ max_position_embeddings=2048,
432
+ base=10000,
433
+ device=None,
434
+ scaling_factor=1.0,
435
+ rope_type="default",
436
+ config: Optional[LlamaCanonConfig] = None,
437
+ ):
438
+ super().__init__()
439
+ # TODO (joao): remove the `if` below, only used for BC
440
+ self.rope_kwargs = {}
441
+ if config is None:
442
+ logger.warning_once(
443
+ "`LlamaRotaryEmbedding` can now be fully parameterized by passing the model config through the "
444
+ "`config` argument. All other arguments will be removed in v4.46"
445
+ )
446
+ self.rope_kwargs = {
447
+ "rope_type": rope_type,
448
+ "factor": scaling_factor,
449
+ "dim": dim,
450
+ "base": base,
451
+ "max_position_embeddings": max_position_embeddings,
452
+ }
453
+ self.rope_type = rope_type
454
+ self.max_seq_len_cached = max_position_embeddings
455
+ self.original_max_seq_len = max_position_embeddings
456
+ else:
457
+ # BC: "rope_type" was originally "type"
458
+ if config.rope_scaling is not None:
459
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
460
+ else:
461
+ self.rope_type = "default"
462
+ self.max_seq_len_cached = config.max_position_embeddings
463
+ self.original_max_seq_len = config.max_position_embeddings
464
+
465
+ self.config = config
466
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
467
+
468
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
469
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
470
+ self.original_inv_freq = self.inv_freq
471
+
472
+ def _dynamic_frequency_update(self, position_ids, device):
473
+ """
474
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
475
+ 1 - growing beyond the cached sequence length (allow scaling)
476
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
477
+ """
478
+ seq_len = torch.max(position_ids) + 1
479
+ if seq_len > self.max_seq_len_cached: # growth
480
+ inv_freq, self.attention_scaling = self.rope_init_fn(
481
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
482
+ )
483
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
484
+ self.max_seq_len_cached = seq_len
485
+
486
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
487
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
488
+ self.max_seq_len_cached = self.original_max_seq_len
489
+
490
+ @torch.no_grad()
491
+ def forward(self, x, position_ids):
492
+ if "dynamic" in self.rope_type:
493
+ self._dynamic_frequency_update(position_ids, device=x.device)
494
+
495
+ # Core RoPE block
496
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
497
+ position_ids_expanded = position_ids[:, None, :].float()
498
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
499
+ device_type = x.device.type
500
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
501
+ with torch.autocast(device_type=device_type, enabled=False):
502
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
503
+ emb = torch.cat((freqs, freqs), dim=-1)
504
+ cos = emb.cos()
505
+ sin = emb.sin()
506
+
507
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
508
+ cos = cos * self.attention_scaling
509
+ sin = sin * self.attention_scaling
510
+
511
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
512
+
513
+
514
+ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
515
+ """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
516
+
517
+ def __init__(self, *args, **kwargs):
518
+ logger.warning_once(
519
+ "`LlamaLinearScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use "
520
+ "`LlamaRotaryEmbedding`, which now also does linear scaling (simply pass the model config to __init__)."
521
+ )
522
+ kwargs["rope_type"] = "linear"
523
+ super().__init__(*args, **kwargs)
524
+
525
+
526
+ class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
527
+ """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
528
+
529
+ def __init__(self, *args, **kwargs):
530
+ logger.warning_once(
531
+ "`LlamaDynamicNTKScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use "
532
+ "`LlamaRotaryEmbedding`, which now also does dynamic ntk scaling (simply pass the model config to "
533
+ "__init__)."
534
+ )
535
+ kwargs["rope_type"] = "dynamic"
536
+ super().__init__(*args, **kwargs)
537
+
538
+
539
+
540
+ def rotate_half(x):
541
+ """Rotates half the hidden dims of the input."""
542
+ x1 = x[..., : x.shape[-1] // 2]
543
+ x2 = x[..., x.shape[-1] // 2 :]
544
+ return torch.cat((-x2, x1), dim=-1)
545
+
546
+
547
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1, rope_version='huggingface'):
548
+ """Applies Rotary Position Embedding to the query and key tensors.
549
+
550
+ Args:
551
+ q (`torch.Tensor`): The query tensor.
552
+ k (`torch.Tensor`): The key tensor.
553
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
554
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
555
+ position_ids (`torch.Tensor`, *optional*):
556
+ Deprecated and unused.
557
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
558
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
559
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
560
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
561
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
562
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
563
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
564
+ Returns:
565
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
566
+ """
567
+ if rope_version == 'huggingface':
568
+ cos = cos.unsqueeze(unsqueeze_dim)
569
+ sin = sin.unsqueeze(unsqueeze_dim)
570
+ q_embed = (q * cos) + (rotate_half(q) * sin)
571
+ k_embed = (k * cos) + (rotate_half(k) * sin)
572
+ elif rope_version == 'lingua':
573
+ B, H, S, D = q.shape
574
+ assert D % 2 == 0, "head_dim must be even"
575
+ half = D // 2
576
+
577
+ # 1) take just the first half of cos/sin
578
+ cos_h = cos[..., :half] # (B, S, half)
579
+ sin_h = sin[..., :half] # (B, S, half)
580
+
581
+ # 2) broadcast over heads
582
+ cos_h = cos_h.unsqueeze(unsqueeze_dim) # (B, 1, S, half)
583
+ sin_h = sin_h.unsqueeze(unsqueeze_dim)
584
+
585
+ # 3) group into (even,odd) pairs --- note q/k may have different number of heads, so -1 means the head dimension
586
+ q2 = q.view(B, -1, S, half, 2) # (B, H, S, half, 2)
587
+ k2 = k.view(B, -1, S, half, 2)
588
+
589
+ q_even, q_odd = q2[..., 0], q2[..., 1] # each (B, H, S, half)
590
+ k_even, k_odd = k2[..., 0], k2[..., 1]
591
+
592
+ # 4) apply [cos -sin; sin cos] to each pair
593
+ # out0 = x0*cos + x1*sin
594
+ # out1 = -x0*sin + x1*cos
595
+ q_rot_even = q_even * cos_h - q_odd * sin_h
596
+ q_rot_odd = q_even * sin_h + q_odd * cos_h
597
+ k_rot_even = k_even * cos_h - k_odd * sin_h
598
+ k_rot_odd = k_even * sin_h + k_odd * cos_h
599
+
600
+ # 5) re-interleave back to (B, H, S, D)
601
+ q_embed = torch.stack([q_rot_even, q_rot_odd], dim=-1).reshape(B, -1, S, D)
602
+ k_embed = torch.stack([k_rot_even, k_rot_odd], dim=-1).reshape(B, -1, S, D)
603
+
604
+ else:
605
+ assert False, f"Unknown rope version: {rope_version}. Supported versions are 'huggingface' and 'lingua'."
606
+ return q_embed, k_embed
607
+
608
+
609
+ class LlamaCanonMLP(nn.Module):
610
+ def __init__(self, config: LlamaCanonConfig):
611
+ super().__init__()
612
+ self.config = config
613
+ self.hidden_size = config.hidden_size
614
+ if config.intermediate_size is None:
615
+ # Use this default one so a d-dim hidden size will mean 8d^2 params for the GatedMLP
616
+ self.intermediate_size = config.hidden_size * 8 // 3
617
+ else:
618
+ self.intermediate_size = config.intermediate_size
619
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
620
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
621
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
622
+ self.act_fn = ACT2FN[config.hidden_act]
623
+ # optional canonD
624
+ if "D" in config.canon_set:
625
+ self.canonD = create_canon(self.intermediate_size * 2, config)
626
+ else:
627
+ self.canonD = None
628
+
629
+ def forward(self, x: torch.Tensor, old_attention_mask: Optional[torch.Tensor] = None, past_key_value: Optional[Cache] = None, layer_idx: Optional[int] = None):
630
+ x1 = self.gate_proj(x)
631
+ x3 = self.up_proj(x)
632
+ if self.canonD is not None:
633
+ cat = torch.cat([x1, x3], dim=-1)
634
+ x1, x3 = apply_canon("canonD", self.canonD, hidden_states=cat, cache=past_key_value, layer_idx=layer_idx, attention_mask=old_attention_mask).chunk(2, dim=-1)
635
+ return self.down_proj(self.act_fn(x1) * x3)
636
+
637
+
638
+
639
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
640
+ """
641
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
642
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
643
+ """
644
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
645
+ if n_rep == 1:
646
+ return hidden_states
647
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
648
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
649
+
650
+ class LlamaCanonAttention(nn.Module):
651
+ """Multi-headed attention with optional Q/K norm and canonB"""
652
+
653
+ def __init__(self, config: LlamaCanonConfig, layer_idx: Optional[int] = None):
654
+ super().__init__()
655
+ self.config = config
656
+ self.layer_idx = layer_idx
657
+ if layer_idx is None:
658
+ logger.warning_once(
659
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
660
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
661
+ "when creating this class."
662
+ )
663
+
664
+ self.attention_dropout = config.attention_dropout
665
+ self.hidden_size = config.hidden_size
666
+ self.num_heads = config.num_attention_heads
667
+ self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
668
+ self.num_key_value_heads = config.num_key_value_heads
669
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
670
+ self.max_position_embeddings = config.max_position_embeddings
671
+ self.rope_theta = config.rope_theta
672
+ self.is_causal = True
673
+
674
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
675
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
676
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
677
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
678
+
679
+ # TODO (joao): remove in v4.46 (RoPE is computed in the model, not in the decoder layers)
680
+ self.rotary_emb = LlamaRotaryEmbedding(config=self.config)
681
+
682
+ # optional Q/K normalization
683
+ if config.qk_norm:
684
+ self.q_norm = LlamaRMSNorm(
685
+ config.num_attention_heads * self.head_dim, eps=config.rms_norm_eps
686
+ )
687
+ self.k_norm = LlamaRMSNorm(
688
+ config.num_key_value_heads * self.head_dim, eps=config.rms_norm_eps
689
+ )
690
+ else:
691
+ self.q_norm = None
692
+ self.k_norm = None
693
+
694
+ # optional canonB
695
+ if "B" in config.canon_set:
696
+ total_dim = (
697
+ config.num_attention_heads * self.head_dim
698
+ + 2 * config.num_key_value_heads * self.head_dim
699
+ )
700
+ self.canonB = create_canon(total_dim, config)
701
+ else:
702
+ self.canonB = None
703
+
704
+
705
+ def forward(
706
+ self,
707
+ hidden_states: torch.Tensor,
708
+ attention_mask: Optional[torch.Tensor] = None,
709
+ old_attention_mask: Optional[torch.Tensor] = None,
710
+ position_ids: Optional[torch.LongTensor] = None,
711
+ past_key_value: Optional[Cache] = None,
712
+ output_attentions: bool = False,
713
+ use_cache: bool = False,
714
+ cache_position: Optional[torch.LongTensor] = None,
715
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
716
+ **kwargs,
717
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
718
+ bsz, q_len, _ = hidden_states.size()
719
+
720
+ query_states = self.q_proj(hidden_states)
721
+ key_states = self.k_proj(hidden_states)
722
+ value_states = self.v_proj(hidden_states)
723
+
724
+ # apply Q/K norm
725
+ if self.q_norm is not None:
726
+ query_states = self.q_norm(query_states)
727
+ if self.k_norm is not None:
728
+ key_states = self.k_norm(key_states)
729
+
730
+ # apply canonB
731
+ if self.canonB is not None:
732
+ qkv = apply_canon('canonB', self.canonB, hidden_states=torch.cat([query_states, key_states, value_states], dim=-1), cache=past_key_value, layer_idx=self.layer_idx, attention_mask=old_attention_mask)
733
+ sizes = [
734
+ self.config.num_attention_heads * self.head_dim,
735
+ self.config.num_key_value_heads * self.head_dim,
736
+ self.config.num_key_value_heads * self.head_dim,
737
+ ]
738
+ query_states, key_states, value_states = qkv.split(sizes, dim=-1)
739
+
740
+
741
+ # use -1 to infer num_heads and num_key_value_heads as they may vary if tensor parallel is used
742
+ query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
743
+ key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
744
+ value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
745
+
746
+ if position_embeddings is None:
747
+ logger.warning_once(
748
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
749
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
750
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
751
+ "removed and `position_embeddings` will be mandatory."
752
+ )
753
+ cos, sin = self.rotary_emb(value_states, position_ids)
754
+ else:
755
+ cos, sin = position_embeddings
756
+
757
+ # apply rotary with partial rope_dim
758
+ rope_dim = getattr(self.config, "rope_dim", None) or self.head_dim
759
+ if rope_dim < self.head_dim:
760
+ q_rope, q_pass = (
761
+ query_states[..., :rope_dim], query_states[..., rope_dim:]
762
+ )
763
+ k_rope, k_pass = (
764
+ key_states[..., :rope_dim], key_states[..., rope_dim:]
765
+ )
766
+ q_rope, k_rope = apply_rotary_pos_emb(
767
+ q_rope, k_rope, cos[..., :rope_dim], sin[..., :rope_dim], rope_version=self.config.rope_version
768
+ )
769
+ query_states = torch.cat([q_rope, q_pass], dim=-1)
770
+ key_states = torch.cat([k_rope, k_pass], dim=-1)
771
+ else:
772
+ query_states, key_states = apply_rotary_pos_emb(
773
+ query_states, key_states, cos, sin, rope_version=self.config.rope_version
774
+ )
775
+
776
+ if past_key_value is not None:
777
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
778
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
779
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
780
+
781
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
782
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
783
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
784
+
785
+ if attention_mask is not None: # no matter the length, we just slice it
786
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
787
+ attn_weights = attn_weights + causal_mask
788
+
789
+ # upcast attention to fp32
790
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
791
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
792
+ attn_output = torch.matmul(attn_weights, value_states)
793
+
794
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
795
+ raise ValueError(
796
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
797
+ f" {attn_output.size()}"
798
+ )
799
+
800
+ attn_output = attn_output.transpose(1, 2).contiguous()
801
+
802
+ attn_output = attn_output.reshape(bsz, q_len, -1)
803
+
804
+ attn_output = self.o_proj(attn_output)
805
+
806
+ if not output_attentions:
807
+ attn_weights = None
808
+
809
+ return attn_output, attn_weights, past_key_value
810
+
811
+
812
+
813
+ class LlamaCanonSdpaAttention(LlamaCanonAttention):
814
+ # Adapted from LlamaCanonAttention.forward
815
+ def forward(
816
+ self,
817
+ hidden_states: torch.Tensor,
818
+ attention_mask: Optional[torch.Tensor] = None,
819
+ old_attention_mask: Optional[torch.Tensor] = None,
820
+ position_ids: Optional[torch.LongTensor] = None,
821
+ past_key_value: Optional[Cache] = None,
822
+ output_attentions: bool = False,
823
+ use_cache: bool = False,
824
+ cache_position: Optional[torch.LongTensor] = None,
825
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
826
+ **kwargs,
827
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
828
+ if output_attentions:
829
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
830
+ logger.warning_once(
831
+ "LlamaModel is using LlamaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
832
+ '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.'
833
+ )
834
+ return super().forward(
835
+ hidden_states=hidden_states,
836
+ attention_mask=attention_mask,
837
+ position_ids=position_ids,
838
+ past_key_value=past_key_value,
839
+ output_attentions=output_attentions,
840
+ use_cache=use_cache,
841
+ cache_position=cache_position,
842
+ position_embeddings=position_embeddings,
843
+ )
844
+
845
+ bsz, q_len, _ = hidden_states.size()
846
+
847
+ query_states = self.q_proj(hidden_states)
848
+ key_states = self.k_proj(hidden_states)
849
+ value_states = self.v_proj(hidden_states)
850
+
851
+ # apply Q/K norm
852
+ if self.q_norm is not None:
853
+ query_states = self.q_norm(query_states)
854
+ if self.k_norm is not None:
855
+ key_states = self.k_norm(key_states)
856
+ # apply canonB
857
+ if self.canonB is not None:
858
+ qkv = apply_canon('canonB', self.canonB, hidden_states=torch.cat([query_states, key_states, value_states], dim=-1), cache=past_key_value, layer_idx=self.layer_idx, attention_mask=old_attention_mask)
859
+ sizes = [
860
+ self.config.num_attention_heads * self.head_dim,
861
+ self.config.num_key_value_heads * self.head_dim,
862
+ self.config.num_key_value_heads * self.head_dim,
863
+ ]
864
+ query_states, key_states, value_states = qkv.split(sizes, dim=-1)
865
+
866
+
867
+ # use -1 to infer num_heads and num_key_value_heads as they may vary if tensor parallel is used
868
+ query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
869
+ key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
870
+ value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
871
+
872
+ if position_embeddings is None:
873
+ logger.warning_once(
874
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
875
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
876
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
877
+ "removed and `position_embeddings` will be mandatory."
878
+ )
879
+ cos, sin = self.rotary_emb(value_states, position_ids)
880
+ else:
881
+ cos, sin = position_embeddings
882
+
883
+ # apply rotary with partial rope_dim
884
+ rope_dim = getattr(self.config, "rope_dim", None) or self.head_dim
885
+ if rope_dim < self.head_dim:
886
+ q_rope, q_pass = (
887
+ query_states[..., :rope_dim], query_states[..., rope_dim:]
888
+ )
889
+ k_rope, k_pass = (
890
+ key_states[..., :rope_dim], key_states[..., rope_dim:]
891
+ )
892
+ q_rope, k_rope = apply_rotary_pos_emb(
893
+ q_rope, k_rope, cos[..., :rope_dim], sin[..., :rope_dim], rope_version=self.config.rope_version
894
+ )
895
+ query_states = torch.cat([q_rope, q_pass], dim=-1)
896
+ key_states = torch.cat([k_rope, k_pass], dim=-1)
897
+ else:
898
+ # apply rotary with full rope_dim
899
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, rope_version=self.config.rope_version)
900
+
901
+ if past_key_value is not None:
902
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
903
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
904
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
905
+
906
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
907
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
908
+
909
+ causal_mask = attention_mask
910
+ if attention_mask is not None:
911
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
912
+ #print(f"Inside LlamaCanonSdpaAttention: attention_mask={causal_mask.shape if causal_mask is not None else None} and value = {causal_mask}")
913
+
914
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
915
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
916
+ if query_states.device.type == "cuda" and causal_mask is not None:
917
+ query_states = query_states.contiguous()
918
+ key_states = key_states.contiguous()
919
+ value_states = value_states.contiguous()
920
+
921
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
922
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
923
+ is_causal = True if causal_mask is None and q_len > 1 else False
924
+
925
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
926
+ query_states,
927
+ key_states,
928
+ value_states,
929
+ attn_mask=causal_mask,
930
+ dropout_p=self.attention_dropout if self.training else 0.0,
931
+ is_causal=is_causal,
932
+ )
933
+
934
+ attn_output = attn_output.transpose(1, 2).contiguous()
935
+ attn_output = attn_output.view(bsz, q_len, -1)
936
+
937
+ attn_output = self.o_proj(attn_output)
938
+
939
+ return attn_output, None, past_key_value
940
+
941
+
942
+
943
+ LLAMA_ATTENTION_CLASSES = {
944
+ "eager": LlamaCanonAttention,
945
+ "flash_attention_2": "too lazy to implement, sorry",
946
+ "sdpa": LlamaCanonSdpaAttention,
947
+ }
948
+
949
+
950
+
951
+ class LlamaCanonDecoderLayer(nn.Module):
952
+ def __init__(self, config: LlamaCanonConfig, layer_idx: int):
953
+ super().__init__()
954
+ self.hidden_size = config.hidden_size
955
+ self.layer_idx = layer_idx
956
+
957
+ self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
958
+
959
+ self.mlp = LlamaCanonMLP(config)
960
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
961
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
962
+
963
+ # optional canonA
964
+ if "A" in config.canon_set:
965
+ self.canonA = create_canon(config.hidden_size, config)
966
+ else:
967
+ self.canonA = None
968
+ # optional canonC
969
+ if "C" in config.canon_set:
970
+ self.canonC = create_canon(config.hidden_size, config)
971
+ else:
972
+ self.canonC = None
973
+
974
+
975
+ def forward(
976
+ self,
977
+ hidden_states: torch.Tensor,
978
+ attention_mask: Optional[torch.Tensor] = None,
979
+ old_attention_mask: Optional[torch.Tensor] = None,
980
+ position_ids: Optional[torch.LongTensor] = None,
981
+ past_key_value: Optional[Cache] = None,
982
+ output_attentions: Optional[bool] = False,
983
+ use_cache: Optional[bool] = False,
984
+ cache_position: Optional[torch.LongTensor] = None,
985
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
986
+ **kwargs,
987
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
988
+ if not use_cache:
989
+ assert past_key_value is None, "past_key_value should be None when use_cache is False"
990
+
991
+ residual = hidden_states
992
+
993
+ hidden_states = self.input_layernorm(hidden_states)
994
+ if self.canonA is not None:
995
+ hidden_states = apply_canon('canonA', self.canonA, hidden_states, cache=past_key_value, layer_idx=self.layer_idx, attention_mask=old_attention_mask)
996
+
997
+ # Self Attention
998
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
999
+ hidden_states=hidden_states,
1000
+ attention_mask=attention_mask,
1001
+ old_attention_mask=old_attention_mask,
1002
+ position_ids=position_ids,
1003
+ past_key_value=past_key_value,
1004
+ output_attentions=output_attentions,
1005
+ use_cache=use_cache,
1006
+ cache_position=cache_position,
1007
+ position_embeddings=position_embeddings,
1008
+ **kwargs,
1009
+ )
1010
+ hidden_states = residual + hidden_states
1011
+
1012
+ # Fully Connected
1013
+ residual = hidden_states
1014
+ hidden_states = self.post_attention_layernorm(hidden_states)
1015
+ if self.canonC is not None:
1016
+ hidden_states = apply_canon('canonC', self.canonC, hidden_states, cache=past_key_value, layer_idx=self.layer_idx, attention_mask=old_attention_mask)
1017
+ hidden_states = self.mlp(hidden_states, old_attention_mask=old_attention_mask, past_key_value=past_key_value, layer_idx=self.layer_idx)
1018
+ hidden_states = residual + hidden_states
1019
+
1020
+ outputs = (hidden_states,)
1021
+
1022
+ if output_attentions:
1023
+ outputs += (self_attn_weights,)
1024
+
1025
+ if use_cache:
1026
+ outputs += (present_key_value,)
1027
+
1028
+ return outputs
1029
+
1030
+
1031
+
1032
+ class LlamaCanonPreTrainedModel(PreTrainedModel):
1033
+ config_class = LlamaCanonConfig
1034
+ base_model_prefix = "model"
1035
+ supports_gradient_checkpointing = True
1036
+ _no_split_modules = ["LlamaCanonDecoderLayer"]
1037
+ _skip_keys_device_placement = ["past_key_values"]
1038
+ _supports_flash_attn_2 = True
1039
+ _supports_sdpa = True
1040
+ _supports_cache_class = True
1041
+ _supports_quantized_cache = True
1042
+ _supports_static_cache = True
1043
+
1044
+ def _init_weights(self, module):
1045
+ std = self.config.initializer_range
1046
+ if isinstance(module, nn.Linear):
1047
+ module.weight.data.normal_(mean=0.0, std=std)
1048
+ if module.bias is not None:
1049
+ module.bias.data.zero_()
1050
+ elif isinstance(module, nn.Embedding):
1051
+ module.weight.data.normal_(mean=0.0, std=std)
1052
+ if module.padding_idx is not None:
1053
+ module.weight.data[module.padding_idx].zero_()
1054
+ elif isinstance(module, ShortConvolution):
1055
+ module.reset_parameters() # Use Kaiming initialization
1056
+
1057
+
1058
+ class LlamaCanonModel(LlamaCanonPreTrainedModel):
1059
+ def __init__(self, config: LlamaCanonConfig):
1060
+ super().__init__(config)
1061
+ self.padding_idx = config.pad_token_id
1062
+ self.vocab_size = config.vocab_size
1063
+
1064
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1065
+ self.layers = nn.ModuleList(
1066
+ [LlamaCanonDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1067
+ )
1068
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1069
+ self.rotary_emb = LlamaRotaryEmbedding(config=config)
1070
+
1071
+ self.gradient_checkpointing = False
1072
+ if getattr(config, "pretraining_tp", 1) != 1:
1073
+ logger.warn("`pretraining_tp` is deprecated, please use `model.tensor_parallel` instead.")
1074
+
1075
+ # Initialize weights and apply final processing
1076
+ self.post_init()
1077
+
1078
+ def get_input_embeddings(self):
1079
+ return self.embed_tokens
1080
+
1081
+ def set_input_embeddings(self, value):
1082
+ self.embed_tokens = value
1083
+
1084
+ def forward(
1085
+ self,
1086
+ input_ids: torch.LongTensor = None,
1087
+ attention_mask: Optional[torch.Tensor] = None,
1088
+ position_ids: Optional[torch.LongTensor] = None,
1089
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1090
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1091
+ use_cache: Optional[bool] = None,
1092
+ output_attentions: Optional[bool] = None,
1093
+ output_hidden_states: Optional[bool] = None,
1094
+ return_dict: Optional[bool] = None,
1095
+ cache_position: Optional[torch.LongTensor] = None,
1096
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
1097
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1098
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1099
+ output_hidden_states = (
1100
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1101
+ )
1102
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1103
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1104
+
1105
+ if (input_ids is None) ^ (inputs_embeds is not None):
1106
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1107
+
1108
+ if self.gradient_checkpointing and self.training and use_cache:
1109
+ logger.warning_once(
1110
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
1111
+ )
1112
+ use_cache = False
1113
+
1114
+ if inputs_embeds is None:
1115
+ inputs_embeds = self.embed_tokens(input_ids)
1116
+
1117
+ # kept for BC (non `Cache` `past_key_values` inputs)
1118
+ return_legacy_cache = False
1119
+ if use_cache and not isinstance(past_key_values, Cache):
1120
+ return_legacy_cache = True
1121
+ if past_key_values is None:
1122
+ past_key_values = DynamicCache()
1123
+ else:
1124
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1125
+ logger.warning_once(
1126
+ "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
1127
+ "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
1128
+ "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
1129
+ )
1130
+
1131
+ if cache_position is None:
1132
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1133
+ cache_position = torch.arange(
1134
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1135
+ )
1136
+ if position_ids is None:
1137
+ position_ids = cache_position.unsqueeze(0)
1138
+
1139
+ if attention_mask is not None:
1140
+ assert len(attention_mask.shape)==2 and (attention_mask>=0).all() and (attention_mask<=1).all(), f"attention_mask should be a 2D tensor with values in [0, 1], but got {attention_mask.shape} and values {attention_mask}"
1141
+ # Canon layers / causal_conv1d support more complex forms of attention masks but I'm too lazy to implement it.
1142
+ #print(f"Before _update_causal_mask: attention_mask={attention_mask.shape if attention_mask is not None else None} and value = {attention_mask}")
1143
+ causal_mask = self._update_causal_mask(
1144
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
1145
+ )
1146
+ #print(f"After _update_causal_mask: attention_mask={causal_mask.shape if causal_mask is not None else None} and value = {causal_mask}")
1147
+ if attention_mask is not None and (attention_mask==1).all():
1148
+ attention_mask = None
1149
+ hidden_states = inputs_embeds
1150
+
1151
+ # create position embeddings to be shared across the decoder layers
1152
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
1153
+
1154
+ # decoder layers
1155
+ all_hidden_states = () if output_hidden_states else None
1156
+ all_self_attns = () if output_attentions else None
1157
+ next_decoder_cache = None
1158
+
1159
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
1160
+ if output_hidden_states:
1161
+ all_hidden_states += (hidden_states,)
1162
+
1163
+ if self.gradient_checkpointing and self.training:
1164
+ layer_outputs = self._gradient_checkpointing_func(
1165
+ decoder_layer.__call__,
1166
+ hidden_states,
1167
+ causal_mask,
1168
+ position_ids,
1169
+ past_key_values,
1170
+ output_attentions,
1171
+ use_cache,
1172
+ cache_position,
1173
+ position_embeddings,
1174
+ )
1175
+ else:
1176
+ layer_outputs = decoder_layer(
1177
+ hidden_states,
1178
+ attention_mask=causal_mask,
1179
+ old_attention_mask=attention_mask,
1180
+ position_ids=position_ids,
1181
+ past_key_value=past_key_values,
1182
+ output_attentions=output_attentions,
1183
+ use_cache=use_cache,
1184
+ cache_position=cache_position,
1185
+ position_embeddings=position_embeddings,
1186
+ **flash_attn_kwargs,
1187
+ )
1188
+
1189
+ hidden_states = layer_outputs[0]
1190
+
1191
+ if use_cache:
1192
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1193
+
1194
+ if output_attentions:
1195
+ all_self_attns += (layer_outputs[1],)
1196
+
1197
+ hidden_states = self.norm(hidden_states)
1198
+
1199
+ # add hidden states from the last decoder layer
1200
+ if output_hidden_states:
1201
+ all_hidden_states += (hidden_states,)
1202
+
1203
+ next_cache = next_decoder_cache if use_cache else None
1204
+ if return_legacy_cache:
1205
+ next_cache = next_cache.to_legacy_cache()
1206
+
1207
+ if not return_dict:
1208
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1209
+ return BaseModelOutputWithPast(
1210
+ last_hidden_state=hidden_states,
1211
+ past_key_values=next_cache,
1212
+ hidden_states=all_hidden_states,
1213
+ attentions=all_self_attns,
1214
+ )
1215
+
1216
+ def _update_causal_mask(
1217
+ self,
1218
+ attention_mask: torch.Tensor,
1219
+ input_tensor: torch.Tensor,
1220
+ cache_position: torch.Tensor,
1221
+ past_key_values: Cache,
1222
+ output_attentions: bool,
1223
+ ):
1224
+ if self.config._attn_implementation == "flash_attention_2":
1225
+ if attention_mask is not None and 0.0 in attention_mask:
1226
+ return attention_mask
1227
+ return None
1228
+
1229
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1230
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1231
+ # to infer the attention mask.
1232
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1233
+ using_static_cache = isinstance(past_key_values, StaticCache)
1234
+
1235
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1236
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1237
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1238
+ attention_mask,
1239
+ inputs_embeds=input_tensor,
1240
+ past_key_values_length=past_seen_tokens,
1241
+ is_training=self.training,
1242
+ ):
1243
+ return None
1244
+
1245
+ dtype, device = input_tensor.dtype, input_tensor.device
1246
+ sequence_length = input_tensor.shape[1]
1247
+ if using_static_cache:
1248
+ target_length = past_key_values.get_max_cache_shape()
1249
+ else:
1250
+ target_length = (
1251
+ attention_mask.shape[-1]
1252
+ if isinstance(attention_mask, torch.Tensor)
1253
+ else past_seen_tokens + sequence_length + 1
1254
+ )
1255
+
1256
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1257
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
1258
+ attention_mask,
1259
+ sequence_length=sequence_length,
1260
+ target_length=target_length,
1261
+ dtype=dtype,
1262
+ device=device,
1263
+ cache_position=cache_position,
1264
+ batch_size=input_tensor.shape[0],
1265
+ )
1266
+
1267
+ if (
1268
+ self.config._attn_implementation == "sdpa"
1269
+ and attention_mask is not None
1270
+ and attention_mask.device.type == "cuda"
1271
+ and not output_attentions
1272
+ ):
1273
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1274
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1275
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1276
+ min_dtype = torch.finfo(dtype).min
1277
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1278
+
1279
+ return causal_mask
1280
+
1281
+
1282
+
1283
+ @staticmethod
1284
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1285
+ attention_mask: torch.Tensor,
1286
+ sequence_length: int,
1287
+ target_length: int,
1288
+ dtype: torch.dtype,
1289
+ device: torch.device,
1290
+ cache_position: torch.Tensor,
1291
+ batch_size: int,
1292
+ **kwargs,
1293
+ ):
1294
+ """
1295
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1296
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1297
+
1298
+ Args:
1299
+ attention_mask (`torch.Tensor`):
1300
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
1301
+ `(batch_size, 1, query_length, key_value_length)`.
1302
+ sequence_length (`int`):
1303
+ The sequence length being processed.
1304
+ target_length (`int`):
1305
+ The target length: when generating with static cache, the mask should be as long as the static cache,
1306
+ to account for the 0 padding, the part of the cache that is not filled yet.
1307
+ dtype (`torch.dtype`):
1308
+ The dtype to use for the 4D attention mask.
1309
+ device (`torch.device`):
1310
+ The device to plcae the 4D attention mask on.
1311
+ cache_position (`torch.Tensor`):
1312
+ Indices depicting the position of the input sequence tokens in the sequence.
1313
+ batch_size (`torch.Tensor`):
1314
+ Batch size.
1315
+ """
1316
+ if attention_mask is not None and attention_mask.dim() == 4:
1317
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1318
+ causal_mask = attention_mask
1319
+ else:
1320
+ min_dtype = torch.finfo(dtype).min
1321
+ causal_mask = torch.full(
1322
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1323
+ )
1324
+ if sequence_length != 1:
1325
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1326
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1327
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1328
+ if attention_mask is not None:
1329
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1330
+ mask_length = attention_mask.shape[-1]
1331
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
1332
+ padding_mask = padding_mask == 0
1333
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1334
+ padding_mask, min_dtype
1335
+ )
1336
+
1337
+ return causal_mask
1338
+
1339
+
1340
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
1341
+
1342
+
1343
+ class LlamaCanonForCausalLM(LlamaCanonPreTrainedModel, GenerationMixin):
1344
+ _tied_weights_keys = ["lm_head.weight"]
1345
+ _tp_plan = {"lm_head": "colwise_rep"}
1346
+
1347
+ def __init__(self, config: LlamaCanonConfig):
1348
+ super().__init__(config)
1349
+ self.config = config
1350
+ self.model = LlamaCanonModel(config)
1351
+ self.vocab_size = config.vocab_size
1352
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1353
+
1354
+ # Initialize weights and apply final processing
1355
+ self.post_init()
1356
+
1357
+ def get_input_embeddings(self):
1358
+ return self.model.embed_tokens
1359
+
1360
+ def set_input_embeddings(self, value):
1361
+ self.model.embed_tokens = value
1362
+
1363
+ def get_output_embeddings(self):
1364
+ return self.lm_head
1365
+
1366
+ def set_output_embeddings(self, new_embeddings):
1367
+ self.lm_head = new_embeddings
1368
+
1369
+ def set_decoder(self, decoder):
1370
+ self.model = decoder
1371
+
1372
+ def get_decoder(self):
1373
+ return self.model
1374
+
1375
+
1376
+ def forward(
1377
+ self,
1378
+ input_ids: torch.LongTensor = None,
1379
+ attention_mask: Optional[torch.Tensor] = None,
1380
+ position_ids: Optional[torch.LongTensor] = None,
1381
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1382
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1383
+ labels: Optional[torch.LongTensor] = None,
1384
+ use_cache: Optional[bool] = None,
1385
+ output_attentions: Optional[bool] = None,
1386
+ output_hidden_states: Optional[bool] = None,
1387
+ return_dict: Optional[bool] = None,
1388
+ cache_position: Optional[torch.LongTensor] = None,
1389
+ num_logits_to_keep: int = 0,
1390
+ **kwargs: Unpack[KwargsForCausalLM],
1391
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1392
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1393
+ output_hidden_states = (
1394
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1395
+ )
1396
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1397
+
1398
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1399
+ outputs = self.model(
1400
+ input_ids=input_ids,
1401
+ attention_mask=attention_mask,
1402
+ position_ids=position_ids,
1403
+ past_key_values=past_key_values,
1404
+ inputs_embeds=inputs_embeds,
1405
+ use_cache=use_cache,
1406
+ output_attentions=output_attentions,
1407
+ output_hidden_states=output_hidden_states,
1408
+ return_dict=return_dict,
1409
+ cache_position=cache_position,
1410
+ **kwargs,
1411
+ )
1412
+ hidden_states = outputs[0]
1413
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1414
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
1415
+
1416
+ loss = None
1417
+ if labels is not None:
1418
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
1419
+
1420
+ if not return_dict:
1421
+ output = (logits,) + outputs[1:]
1422
+ return (loss,) + output if loss is not None else output
1423
+
1424
+ return CausalLMOutputWithPast(
1425
+ loss=loss,
1426
+ logits=logits,
1427
+ past_key_values=outputs.past_key_values,
1428
+ hidden_states=outputs.hidden_states,
1429
+ attentions=outputs.attentions,
1430
+ )
1431
+
1432
+
1433
+ def load_from_lingua_state(self, state_dict: dict, strict: bool = True):
1434
+ assert self.config.rope_version=='lingua', f"Lingua uses different rope indexing comparing to Huggingface default, must have initialized with `rope_version='lingua'` but got {self.config.rope_version}"
1435
+ mapped = {}
1436
+ for k, v in state_dict.items():
1437
+ if k.startswith("layers."):
1438
+ parts = k.split('.')
1439
+ idx = parts[1]
1440
+ name = parts[2:]
1441
+ if name[0] == 'attention':
1442
+ sub = name[1]
1443
+ if sub in ['wq','wk','wv','wo']:
1444
+ proj_map = {'wq':'q_proj','wk':'k_proj','wv':'v_proj','wo':'o_proj'}
1445
+ newk = f"model.layers.{idx}.self_attn.{proj_map[sub]}.weight"
1446
+ elif sub in ['q_norm','k_norm','canonB']:
1447
+ newk = f"model.layers.{idx}.self_attn.{sub}.weight"
1448
+ else:
1449
+ continue
1450
+ elif name[0] == 'feed_forward':
1451
+ sub = name[1]
1452
+ mp = {'w1':'gate_proj','w3':'up_proj','w2':'down_proj','canonD':'canonD'}
1453
+ if sub in mp:
1454
+ newk = f"model.layers.{idx}.mlp.{mp[sub]}.weight"
1455
+ else:
1456
+ continue
1457
+ elif name[0] == 'canonA':
1458
+ newk = f"model.layers.{idx}.canonA.weight"
1459
+ elif name[0] == 'canonC':
1460
+ newk = f"model.layers.{idx}.canonC.weight"
1461
+ elif name[0] == 'attention_norm':
1462
+ newk = f"model.layers.{idx}.input_layernorm.weight"
1463
+ elif name[0] == 'ffn_norm':
1464
+ newk = f"model.layers.{idx}.post_attention_layernorm.weight"
1465
+ else:
1466
+ continue
1467
+ mapped[newk] = v
1468
+ elif k == 'tok_embeddings.weight':
1469
+ mapped['model.embed_tokens.weight'] = v
1470
+ elif k == 'norm.weight':
1471
+ mapped['model.norm.weight'] = v
1472
+ elif k == 'output.weight':
1473
+ mapped['lm_head.weight'] = v
1474
+ # print(f"Target has {len(self.state_dict())} keys: \n {list(self.state_dict().keys())}")
1475
+ # print(f"Mapped has {len(mapped)} keys: \n {list(mapped.keys())}")
1476
+ self.load_state_dict(mapped, strict=strict)
1477
+
1478
+
1479
+ @classmethod
1480
+ def from_pretrained(cls, pretrained_model_name_or_path, *model_args, variant="default", **kwargs):
1481
+ """
1482
+ Overrides HF default loader to use custom .pth and config from subfolder.
1483
+ """
1484
+
1485
+ def device_map_to_map_location(device_map):
1486
+ if device_map == "cpu":
1487
+ return "cpu"
1488
+ elif device_map == "auto":
1489
+ return None # Let torch figure it out
1490
+ elif isinstance(device_map, dict):
1491
+ # Could be a more complex mapping, may need custom handling
1492
+ return lambda storage, loc: loc # identity (as fallback)
1493
+ elif isinstance(device_map, str):
1494
+ return device_map # e.g., "cuda:0"
1495
+ else:
1496
+ return None
1497
+ device_map = kwargs.pop("device_map", None)
1498
+ map_location = device_map_to_map_location(device_map)
1499
+
1500
+ from huggingface_hub import hf_hub_download
1501
+ import os, json
1502
+ if os.path.isfile(os.path.join(pretrained_model_name_or_path, variant, "params.json")):
1503
+ config_path = os.path.join(pretrained_model_name_or_path, variant, "params.json")
1504
+ else:
1505
+ config_path = hf_hub_download(
1506
+ repo_id=pretrained_model_name_or_path,
1507
+ filename=f"{variant}/params.json",
1508
+ )
1509
+ with open(config_path, "r") as f:
1510
+ dd = json.load(f)
1511
+
1512
+ cfg = LlamaCanonConfig(vocab_size=dd['model']['vocab_size'],
1513
+ hidden_size=dd['model']['dim'],
1514
+ intermediate_size=dd['model']['hidden_dim'],
1515
+ num_hidden_layers=dd['model']['n_layers'],
1516
+ num_attention_heads=dd['model']['n_heads'],
1517
+ num_key_value_heads=dd['model']['n_kv_heads'] if 'n_kv_heads' in dd['model'] else None,
1518
+ qk_norm = dd['model'].get('qk_norm', False),
1519
+ rope_dim = dd['model'].get('rope_dim', None),
1520
+ canon_set = dd['model'].get('canon_set', ''),
1521
+ rope_theta = dd['model'].get('rope_theta'),
1522
+ rms_norm_eps = dd['model'].get('norm_eps'),
1523
+ max_position_embeddings=dd['data']['seq_len'],
1524
+ rope_version = 'lingua',
1525
+ )
1526
+ if dd['model']['hidden_dim'] is None:
1527
+ cfg.intermediate_size = 256 * ((dd['model']['dim'] * 8 + 3*256-1) // (3*256))
1528
+ cfg._attn_implementation = 'sdpa'
1529
+ if 'rope_dim' in dd['model'] and dd['model']['rope_dim'] is not None and dd['model']['rope_dim'] < dd['model']['dim'] // dd['model']['n_heads']:
1530
+ cfg.partial_rotary_factor = dd['model']['rope_dim'] / (dd['model']['dim'] // dd['model']['n_heads'])
1531
+ logger.info(f"Converted lingua params.json to Huggingface config; next creating Huggingface model")
1532
+ model = LlamaCanonForCausalLM(cfg)
1533
+
1534
+ if os.path.isfile(os.path.join(pretrained_model_name_or_path, variant, "consolidated.pth")):
1535
+ weights_path = os.path.join(pretrained_model_name_or_path, variant, "consolidated.pth")
1536
+ else:
1537
+ weights_path = hf_hub_download(
1538
+ repo_id=pretrained_model_name_or_path,
1539
+ filename=f"{variant}/consolidated.pth",
1540
+ )
1541
+ logger.info(f"Loading lingua model weights from {weights_path}")
1542
+ state = torch.load(weights_path, map_location=map_location, weights_only=True)
1543
+ model.load_from_lingua_state(state['model'])
1544
+ logger.info(f"Successfully converted lingua state to Huggingface state")
1545
+
1546
+ return model
PhysicsLM4.2-8B/plots/curve-mmlu.png ADDED

Git LFS Details

  • SHA256: f1b9f8f35decd0e7ab49f799c20345584f73cd786209c609606d2366dd2bb8cf
  • Pointer size: 131 Bytes
  • Size of remote file: 141 kB
PhysicsLM4.2-8B/plots/model-training-time.png ADDED

Git LFS Details

  • SHA256: b79a8095d5c5075c79f4281ee727951c071570aec16e64d1476c39aae2385d4e
  • Pointer size: 131 Bytes
  • Size of remote file: 859 kB
PhysicsLM4.2-8B/plots/table-params.png ADDED

Git LFS Details

  • SHA256: cbdea85f887490cb447a5897b9da2e688d163ad5aa21173577027c545fe568a9
  • Pointer size: 131 Bytes
  • Size of remote file: 234 kB
PhysicsLM4.2-8B/plots/table-performance.png ADDED

Git LFS Details

  • SHA256: 256ed2f0e36aba9033669421bfd5a352acfceaa03309083af1e3febf00614a4c
  • Pointer size: 131 Bytes
  • Size of remote file: 591 kB
PhysicsLM4.2-8B/tokenization_llama_canon.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # Zeyuan's edit note: this is nothing but a simple wrapper of either Llama2 or Llama3 tokenizer, depending on params.json
4
+ from transformers import PreTrainedTokenizerFast
5
+
6
+ class LlamaCanonTokenizer(PreTrainedTokenizerFast):
7
+ @classmethod
8
+ def from_pretrained(cls, pretrained_model_name_or_path, *args, variant="default", **kwargs):
9
+ from huggingface_hub import hf_hub_download
10
+ import os, json
11
+ if os.path.isfile(os.path.join(pretrained_model_name_or_path, variant, "params.json")):
12
+ config_path = os.path.join(pretrained_model_name_or_path, variant, "params.json")
13
+ else:
14
+ config_path = hf_hub_download(
15
+ repo_id=pretrained_model_name_or_path,
16
+ filename=f"{variant}/params.json",
17
+ )
18
+
19
+ print("Please ignore the tokenizer name mismatch warning; this LlamaCanonTokenizer is simply a wrapper of either Llama2 or Llama3 tokenizer, depending on params.json")
20
+ with open(config_path, "r") as f:
21
+ dd = json.load(f)
22
+ if dd['data']['tokenizer']['name']=='sp':
23
+ print("Using Llama2 tokenizer")
24
+ #return super().from_pretrained("meta-llama/Llama-2-7b-hf", *args, **kwargs)
25
+ return super().from_pretrained("NousResearch/Llama-2-7b-hf")
26
+ elif dd['data']['tokenizer']['name']=='tiktoken':
27
+ print("Using Llama3 tokenizer")
28
+ #return super().from_pretrained("meta-llama/Meta-Llama-3-8B", *args, **kwargs)
29
+ #return super().from_pretrained("Xenova/llama3-tokenizer")
30
+ return super().from_pretrained("nvidia/Llama-3.1-Nemotron-70B-Instruct-HF")
31
+ else:
32
+ raise ValueError(f"Unsupported tokenizer name: {dd['data']['tokenizer']['name']}")