JonasGeiping commited on
Commit
7bc967a
·
verified ·
1 Parent(s): fa79977

Upload RavenForCausalLM

Browse files
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation_checkpoint_impl": "per-iteration",
3
+ "architecture_class_name": "RecurrentGPT",
4
+ "architectures": [
5
+ "RavenForCausalLM"
6
+ ],
7
+ "auto_map": {
8
+ "AutoConfig": "raven_config_minimal.RavenConfig",
9
+ "AutoModelForCausalLM": "raven_modeling_minimal.RavenForCausalLM"
10
+ },
11
+ "bias": false,
12
+ "block_class_name": "SandwichBlock",
13
+ "block_size": 4096,
14
+ "effective_expected_depth": 132,
15
+ "head_dim": 96,
16
+ "init_orthogonal": false,
17
+ "init_strategy": "takase",
18
+ "init_values": {
19
+ "embed_scale": 72.6636084983398,
20
+ "embedding": 0.008703882797784892,
21
+ "out_proj": 0.0005356869554443541,
22
+ "std": 0.008703882797784892
23
+ },
24
+ "injection_type": "linear",
25
+ "intermediate_size": 17920,
26
+ "mean_backprop_depth": 8,
27
+ "mean_recurrence": 32,
28
+ "mlp_class_name": "GatedMLP",
29
+ "model_type": "huginn_raven",
30
+ "n_embd": 5280,
31
+ "n_heads": 55,
32
+ "n_layers": 8,
33
+ "n_layers_in_coda": 2,
34
+ "n_layers_in_prelude": 2,
35
+ "n_layers_in_recurrent_block": 4,
36
+ "nonlin_name": "SiLU",
37
+ "norm_class_name": "RMSNorm_llama",
38
+ "norm_eps": 1e-06,
39
+ "num_key_value_heads": 55,
40
+ "padded_vocab_size": 65536,
41
+ "padding_multiple": 4096,
42
+ "qk_bias": true,
43
+ "rope_base": 50000,
44
+ "sampling_scheme": "poisson-lognormal-filling",
45
+ "state_init": "like-init",
46
+ "tie_embeddings": true,
47
+ "torch_dtype": "float32",
48
+ "transformers_version": "4.44.2",
49
+ "vocab_size": 65536
50
+ }
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.44.2"
4
+ }
model-00001-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8db1d84a031ce6e5c09f5132bc7860400ea7fedcee5eb9334231bab6e9b0846d
3
+ size 4771970936
model-00002-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5ff411e149ff97b09d530751e7d6a3b54501bd3acffc2a9d54017e7a3dbc2679
3
+ size 4744780096
model-00003-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c43fba2a522df37ba80cbcd8f531f7f59a293b9a1833c7140fb4441a69a7af54
3
+ size 4744737616
model-00004-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b1d711eff653f3fb96edf96728db959a68ecfce91b3f2a43d653c872c93ca788
3
+ size 1384120448
model.safetensors.index.json ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 15645600384
4
+ },
5
+ "weight_map": {
6
+ "freqs_cis": "model-00001-of-00004.safetensors",
7
+ "lm_head.weight": "model-00004-of-00004.safetensors",
8
+ "transformer.adapter.weight": "model-00001-of-00004.safetensors",
9
+ "transformer.coda.0.attn.Wqkv.weight": "model-00003-of-00004.safetensors",
10
+ "transformer.coda.0.attn.proj.weight": "model-00003-of-00004.safetensors",
11
+ "transformer.coda.0.attn.qk_bias": "model-00003-of-00004.safetensors",
12
+ "transformer.coda.0.mlp.fc.weight": "model-00003-of-00004.safetensors",
13
+ "transformer.coda.0.mlp.proj.weight": "model-00003-of-00004.safetensors",
14
+ "transformer.coda.0.norm_1.weight": "model-00003-of-00004.safetensors",
15
+ "transformer.coda.0.norm_2.weight": "model-00003-of-00004.safetensors",
16
+ "transformer.coda.0.norm_3.weight": "model-00003-of-00004.safetensors",
17
+ "transformer.coda.0.norm_4.weight": "model-00003-of-00004.safetensors",
18
+ "transformer.coda.1.attn.Wqkv.weight": "model-00003-of-00004.safetensors",
19
+ "transformer.coda.1.attn.proj.weight": "model-00003-of-00004.safetensors",
20
+ "transformer.coda.1.attn.qk_bias": "model-00003-of-00004.safetensors",
21
+ "transformer.coda.1.mlp.fc.weight": "model-00003-of-00004.safetensors",
22
+ "transformer.coda.1.mlp.proj.weight": "model-00003-of-00004.safetensors",
23
+ "transformer.coda.1.norm_1.weight": "model-00003-of-00004.safetensors",
24
+ "transformer.coda.1.norm_2.weight": "model-00003-of-00004.safetensors",
25
+ "transformer.coda.1.norm_3.weight": "model-00003-of-00004.safetensors",
26
+ "transformer.coda.1.norm_4.weight": "model-00003-of-00004.safetensors",
27
+ "transformer.core_block.0.attn.Wqkv.weight": "model-00002-of-00004.safetensors",
28
+ "transformer.core_block.0.attn.proj.weight": "model-00002-of-00004.safetensors",
29
+ "transformer.core_block.0.attn.qk_bias": "model-00001-of-00004.safetensors",
30
+ "transformer.core_block.0.mlp.fc.weight": "model-00002-of-00004.safetensors",
31
+ "transformer.core_block.0.mlp.proj.weight": "model-00002-of-00004.safetensors",
32
+ "transformer.core_block.0.norm_1.weight": "model-00001-of-00004.safetensors",
33
+ "transformer.core_block.0.norm_2.weight": "model-00002-of-00004.safetensors",
34
+ "transformer.core_block.0.norm_3.weight": "model-00002-of-00004.safetensors",
35
+ "transformer.core_block.0.norm_4.weight": "model-00002-of-00004.safetensors",
36
+ "transformer.core_block.1.attn.Wqkv.weight": "model-00002-of-00004.safetensors",
37
+ "transformer.core_block.1.attn.proj.weight": "model-00002-of-00004.safetensors",
38
+ "transformer.core_block.1.attn.qk_bias": "model-00002-of-00004.safetensors",
39
+ "transformer.core_block.1.mlp.fc.weight": "model-00002-of-00004.safetensors",
40
+ "transformer.core_block.1.mlp.proj.weight": "model-00002-of-00004.safetensors",
41
+ "transformer.core_block.1.norm_1.weight": "model-00002-of-00004.safetensors",
42
+ "transformer.core_block.1.norm_2.weight": "model-00002-of-00004.safetensors",
43
+ "transformer.core_block.1.norm_3.weight": "model-00002-of-00004.safetensors",
44
+ "transformer.core_block.1.norm_4.weight": "model-00002-of-00004.safetensors",
45
+ "transformer.core_block.2.attn.Wqkv.weight": "model-00002-of-00004.safetensors",
46
+ "transformer.core_block.2.attn.proj.weight": "model-00002-of-00004.safetensors",
47
+ "transformer.core_block.2.attn.qk_bias": "model-00002-of-00004.safetensors",
48
+ "transformer.core_block.2.mlp.fc.weight": "model-00002-of-00004.safetensors",
49
+ "transformer.core_block.2.mlp.proj.weight": "model-00002-of-00004.safetensors",
50
+ "transformer.core_block.2.norm_1.weight": "model-00002-of-00004.safetensors",
51
+ "transformer.core_block.2.norm_2.weight": "model-00002-of-00004.safetensors",
52
+ "transformer.core_block.2.norm_3.weight": "model-00002-of-00004.safetensors",
53
+ "transformer.core_block.2.norm_4.weight": "model-00002-of-00004.safetensors",
54
+ "transformer.core_block.3.attn.Wqkv.weight": "model-00003-of-00004.safetensors",
55
+ "transformer.core_block.3.attn.proj.weight": "model-00003-of-00004.safetensors",
56
+ "transformer.core_block.3.attn.qk_bias": "model-00002-of-00004.safetensors",
57
+ "transformer.core_block.3.mlp.fc.weight": "model-00003-of-00004.safetensors",
58
+ "transformer.core_block.3.mlp.proj.weight": "model-00003-of-00004.safetensors",
59
+ "transformer.core_block.3.norm_1.weight": "model-00002-of-00004.safetensors",
60
+ "transformer.core_block.3.norm_2.weight": "model-00003-of-00004.safetensors",
61
+ "transformer.core_block.3.norm_3.weight": "model-00003-of-00004.safetensors",
62
+ "transformer.core_block.3.norm_4.weight": "model-00003-of-00004.safetensors",
63
+ "transformer.ln_f.weight": "model-00003-of-00004.safetensors",
64
+ "transformer.prelude.0.attn.Wqkv.weight": "model-00001-of-00004.safetensors",
65
+ "transformer.prelude.0.attn.proj.weight": "model-00001-of-00004.safetensors",
66
+ "transformer.prelude.0.attn.qk_bias": "model-00001-of-00004.safetensors",
67
+ "transformer.prelude.0.mlp.fc.weight": "model-00001-of-00004.safetensors",
68
+ "transformer.prelude.0.mlp.proj.weight": "model-00001-of-00004.safetensors",
69
+ "transformer.prelude.0.norm_1.weight": "model-00001-of-00004.safetensors",
70
+ "transformer.prelude.0.norm_2.weight": "model-00001-of-00004.safetensors",
71
+ "transformer.prelude.0.norm_3.weight": "model-00001-of-00004.safetensors",
72
+ "transformer.prelude.0.norm_4.weight": "model-00001-of-00004.safetensors",
73
+ "transformer.prelude.1.attn.Wqkv.weight": "model-00001-of-00004.safetensors",
74
+ "transformer.prelude.1.attn.proj.weight": "model-00001-of-00004.safetensors",
75
+ "transformer.prelude.1.attn.qk_bias": "model-00001-of-00004.safetensors",
76
+ "transformer.prelude.1.mlp.fc.weight": "model-00001-of-00004.safetensors",
77
+ "transformer.prelude.1.mlp.proj.weight": "model-00001-of-00004.safetensors",
78
+ "transformer.prelude.1.norm_1.weight": "model-00001-of-00004.safetensors",
79
+ "transformer.prelude.1.norm_2.weight": "model-00001-of-00004.safetensors",
80
+ "transformer.prelude.1.norm_3.weight": "model-00001-of-00004.safetensors",
81
+ "transformer.prelude.1.norm_4.weight": "model-00001-of-00004.safetensors",
82
+ "transformer.wte.weight": "model-00001-of-00004.safetensors"
83
+ }
84
+ }
raven_config_minimal.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A HuggingFace-style model configuration."""
2
+
3
+ from transformers import PretrainedConfig
4
+ from math import sqrt
5
+
6
+
7
+ class RavenConfig(PretrainedConfig):
8
+ model_type = "huginn_raven"
9
+ keys_to_ignore_at_inference = [""]
10
+ attribute_map = {"num_attention_heads": "n_heads", "hidden_size": "n_embd", "num_hidden_layers": "n_layers"}
11
+
12
+ def __init__(
13
+ self,
14
+ n_embd: int = 5280,
15
+ n_heads: int = 55,
16
+ n_layers: int = 8, # total of prelude + recurrent + coda
17
+ block_size: int = 4096,
18
+ vocab_size: int = 65536,
19
+ padding_multiple: int = 4096,
20
+ tie_embeddings: bool = True,
21
+ intermediate_size: int = 17920,
22
+ bias: bool = False,
23
+ architecture_class_name: str = "RecurrentGPT",
24
+ block_class_name: str = "SandwichBlock",
25
+ norm_class_name: str = "RMSNorm_llama",
26
+ norm_eps: float = 0.000001,
27
+ mlp_class_name: str = "GatedMLP",
28
+ nonlin_name: str = "SiLU",
29
+ init_strategy: str = "takase",
30
+ init_orthogonal: bool = False,
31
+ state_init: str = "like-init",
32
+ injection_type: str = "linear",
33
+ n_layers_in_recurrent_block: int = 4,
34
+ mean_recurrence: int = 32,
35
+ sampling_scheme: str = "poisson-lognormal-filling",
36
+ mean_backprop_depth: int = 8,
37
+ n_layers_in_prelude: int = 2,
38
+ n_layers_in_coda: int = 2,
39
+ qk_bias: bool = True,
40
+ activation_checkpoint_impl: str = "per-iteration",
41
+ rope_base: float = 50_000,
42
+ torch_dtype: str = "bfloat16",
43
+ transformers_version: str = "4.47.1",
44
+ **kwargs,
45
+ ):
46
+ self.n_embd = n_embd
47
+ self.n_heads = n_heads
48
+ self.n_layers = n_layers
49
+ self.block_size = block_size
50
+ self.vocab_size = self.padded_vocab_size = vocab_size
51
+ self.padding_multiple = padding_multiple
52
+ self.tie_embeddings = tie_embeddings
53
+ self.intermediate_size = intermediate_size
54
+ self.bias = bias
55
+ self.architecture_class_name = architecture_class_name
56
+ self.block_class_name = block_class_name
57
+ self.norm_class_name = norm_class_name
58
+ self.norm_eps = norm_eps
59
+ self.mlp_class_name = mlp_class_name
60
+ self.nonlin_name = nonlin_name
61
+ self.init_strategy = init_strategy
62
+ self.init_orthogonal = init_orthogonal
63
+ self.state_init = state_init
64
+ self.injection_type = injection_type
65
+ self.n_layers_in_recurrent_block = n_layers_in_recurrent_block
66
+ self.mean_recurrence = mean_recurrence
67
+ self.sampling_scheme = sampling_scheme
68
+ self.mean_backprop_depth = mean_backprop_depth
69
+ self.n_layers_in_prelude = n_layers_in_prelude
70
+ self.n_layers_in_coda = n_layers_in_coda
71
+ self.qk_bias = qk_bias
72
+ self.activation_checkpoint_impl = activation_checkpoint_impl
73
+ self.rope_base = rope_base
74
+ self.torch_dtype = torch_dtype # Added from JSON
75
+ self.transformers_version = transformers_version # Added from JSON
76
+ # Derived
77
+ self.num_key_value_heads = n_heads
78
+ self.num_attention_heads = n_heads
79
+ self.head_dim = n_embd // n_heads
80
+ self.effective_expected_depth = (
81
+ self.n_layers_in_prelude + self.n_layers_in_coda + self.n_layers_in_recurrent_block * self.mean_recurrence
82
+ )
83
+ self.init_values = {
84
+ "std": sqrt(2 / (5 * self.n_embd)),
85
+ "out_proj": sqrt(2 / (5 * self.n_embd)) / sqrt(2 * self.effective_expected_depth),
86
+ "embedding": sqrt(2 / (5 * self.n_embd)),
87
+ "embed_scale": sqrt(self.n_embd),
88
+ }
89
+
90
+ super().__init__(
91
+ # pad_token_id=65509,
92
+ # bos_token_id=65504,
93
+ # eos_token_id=65505,
94
+ tie_word_embeddings=tie_embeddings,
95
+ **kwargs,
96
+ )
raven_modeling_minimal.py ADDED
@@ -0,0 +1,972 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Minimal modeling.py file for HF compatibility and funny zero-shot experiments. Use only for inference."""
2
+
3
+ import torch
4
+ import math
5
+
6
+ from torch import Tensor
7
+ from dataclasses import dataclass
8
+ from typing import Optional, Union, Any
9
+
10
+ from .raven_config_minimal import RavenConfig
11
+ from transformers.cache_utils import Cache, DynamicCache
12
+
13
+ ###################### Huggingface Glue code I ##################################################################
14
+ from transformers import PreTrainedModel
15
+ from transformers.utils import ModelOutput
16
+ from transformers.generation.utils import GenerateDecoderOnlyOutput
17
+
18
+ import torch.nn.functional as F
19
+ from transformers import GenerationConfig
20
+
21
+
22
+ class RavenPreTrainedModel(PreTrainedModel):
23
+ config_class = RavenConfig
24
+ base_model_prefix = "model"
25
+ supports_gradient_checkpointing = True
26
+ _no_split_modules = ["SandwichBlock"]
27
+ _skip_keys_device_placement = ["past_key_values"]
28
+ _supports_flash_attn_2 = True
29
+ _supports_sdpa = True
30
+ _supports_cache_class = True
31
+ _supports_quantized_cache = False
32
+ _supports_static_cache = False
33
+
34
+ def _init_weights(self, module):
35
+ print("Random Initialization not implemented.")
36
+
37
+
38
+ @dataclass
39
+ class CausalLMOutputRecurrentLatents(ModelOutput):
40
+ loss: Optional[torch.Tensor] = None
41
+ log_ppl: Optional[torch.Tensor] = None
42
+ logits: Optional[torch.Tensor] = None
43
+ past_key_values: Optional[Cache] = None
44
+ latent_states: Optional[torch.Tensor] = None
45
+ hidden_states: Optional[torch.Tensor] = None
46
+ attention_maps: Optional[dict[int, torch.Tensor]] = None
47
+ stats: Optional[dict] = None
48
+
49
+
50
+ ###################### Minimal implementation from here ############################################################
51
+
52
+
53
+ class RMSNorm(torch.nn.Module):
54
+ """Saner dtype handling and slightly better for fusion"""
55
+
56
+ def __init__(self, dim: int, eps: float = 1e-6):
57
+ super().__init__()
58
+ self.eps = eps
59
+ self.weight = torch.nn.Parameter(torch.ones(dim))
60
+
61
+ def _norm(self, x):
62
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
63
+
64
+ def forward(self, x):
65
+ with torch.autocast(enabled=False, device_type=x.device.type):
66
+ return self._norm(x.float()).type_as(x) * self.weight
67
+
68
+ def reset_parameters(self) -> None:
69
+ torch.nn.init.ones_(self.weight)
70
+
71
+
72
+ class HuginnDynamicCache(DynamicCache):
73
+ def __init__(self, lookup_strategy: str = "full") -> None:
74
+ super().__init__()
75
+ self._seen_tokens = 0
76
+ self.key_cache: dict[int, dict[int, torch.Tensor]] = {}
77
+ self.value_cache: dict[int, dict[int, torch.Tensor]] = {}
78
+ # structure: cache[index_of_layer_or_recurrent_step][index_in_sequence]
79
+ # the cache is held uncoalesced because certain recurrent steps may be missing for some sequence ids if using
80
+ # per-token adaptive compute. In those cases, the "lookup_strategy" determines how to proceed
81
+ # Also, It is critical that the head indices do not overlap with the recurrent iteration indices
82
+ self.lookup_strategy = lookup_strategy
83
+
84
+ def update(
85
+ self,
86
+ key_states: torch.Tensor,
87
+ value_states: torch.Tensor,
88
+ step_idx: int,
89
+ lookup_strategy: Optional[str] = None,
90
+ ) -> tuple[torch.Tensor, torch.Tensor]:
91
+ lookup_strategy = self.lookup_strategy if lookup_strategy is None else lookup_strategy
92
+ if "compress-" in self.lookup_strategy and step_idx > 1: # hardcode for current model!
93
+ compression_stage = int(self.lookup_strategy.split("compress-")[1][1:])
94
+ if "compress-s" in self.lookup_strategy:
95
+ new_step_idx = (step_idx - 2) % compression_stage + 2
96
+ else:
97
+ new_step_idx = (step_idx - 2) // compression_stage + 2
98
+ # @ print(step_idx, new_step_idx, compression_stage)
99
+ step_idx = new_step_idx
100
+ # Init
101
+ if step_idx not in self.key_cache:
102
+ self.key_cache[step_idx] = {}
103
+ self.value_cache[step_idx] = {}
104
+ # Update the number of seen tokens, we assume that step_idx=0 (first prelude) is always hit
105
+ if step_idx == 0:
106
+ self._seen_tokens += key_states.shape[-2]
107
+ # Add entries to cache
108
+ for idx, entry in enumerate(key_states.unbind(dim=-2)):
109
+ if "compress-" not in self.lookup_strategy:
110
+ assert step_idx < 0 or self._seen_tokens - key_states.shape[-2] + idx not in self.key_cache[step_idx]
111
+ # print(f"Overwrote cache entry for step_idx {step_idx}") # likely the head
112
+ self.key_cache[step_idx][self._seen_tokens - key_states.shape[-2] + idx] = entry
113
+ for idx, entry in enumerate(value_states.unbind(dim=-2)):
114
+ self.value_cache[step_idx][self._seen_tokens - value_states.shape[-2] + idx] = entry
115
+
116
+ # Materialize past state based on lookup strategy:
117
+ if len(self.key_cache[step_idx]) == self._seen_tokens or self.lookup_strategy == "full":
118
+ # All entries are present, materialize cache as normal
119
+ return (
120
+ torch.stack(list(self.key_cache[step_idx].values()), dim=-2),
121
+ torch.stack(list(self.value_cache[step_idx].values()), dim=-2),
122
+ )
123
+ else: # some entries where not previously computed
124
+ # if lookup_strategy.startswith("latest"):
125
+ # latest_keys = []
126
+ # latest_values = []
127
+ # for token_pos in range(self._seen_tokens):
128
+ # # Find the latest step that has this token position
129
+ # max_step = max((s for s in range(step_idx + 1) if token_pos in self.key_cache[s]), default=None)
130
+ # if max_step is None:
131
+ # raise ValueError(f"No cache entry found for token position {token_pos}")
132
+ # latest_keys.append(self.key_cache[max_step][token_pos])
133
+ # latest_values.append(self.value_cache[max_step][token_pos])
134
+ # return torch.stack(latest_keys, dim=-2), torch.stack(latest_values, dim=-2)
135
+ if lookup_strategy.startswith("latest-m4"):
136
+ latest_keys = []
137
+ latest_values = []
138
+ for token_pos in range(self._seen_tokens):
139
+ # For steps >= 2, use modulo 4
140
+ if step_idx >= 2:
141
+ # Find valid steps for this token position
142
+ valid_steps = [s for s in range(step_idx + 1) if token_pos in self.key_cache[s]]
143
+ max_step = max([s for s in valid_steps if s >= 2 and s % 4 == step_idx % 4])
144
+ else:
145
+ max_step = step_idx if token_pos in self.key_cache[step_idx] else 0
146
+ if max_step is None:
147
+ raise ValueError(f"No cache entry found for token position {token_pos}")
148
+ latest_keys.append(self.key_cache[max_step][token_pos])
149
+ latest_values.append(self.value_cache[max_step][token_pos])
150
+ return torch.stack(latest_keys, dim=-2), torch.stack(latest_values, dim=-2)
151
+ elif lookup_strategy.startswith("skip"):
152
+ existing_keys = []
153
+ existing_values = []
154
+ for token_pos in range(self._seen_tokens):
155
+ if token_pos in self.key_cache[step_idx]:
156
+ existing_keys.append(self.key_cache[step_idx][token_pos])
157
+ existing_values.append(self.value_cache[step_idx][token_pos])
158
+ return torch.stack(existing_keys, dim=-2), torch.stack(existing_values, dim=-2)
159
+ elif lookup_strategy.startswith("randomized"): # sanity check
160
+ rand_keys = []
161
+ rand_values = []
162
+ for token_pos in range(self._seen_tokens):
163
+ if step_idx < 2: # For prelude steps
164
+ max_step = step_idx if token_pos in self.key_cache[step_idx] else 0
165
+ else: # Get all steps from same block position
166
+ curr_modulo = (step_idx - 2) % 4 + 2
167
+ valid_steps = [
168
+ s
169
+ for s in range(2, step_idx + 1)
170
+ if (s - 2) % 4 + 2 == curr_modulo and token_pos in self.key_cache[s]
171
+ ]
172
+ max_step = valid_steps[torch.randint(len(valid_steps), (1,))]
173
+ rand_keys.append(self.key_cache[max_step][token_pos])
174
+ rand_values.append(self.value_cache[max_step][token_pos])
175
+ return torch.stack(rand_keys, dim=-2), torch.stack(rand_values, dim=-2)
176
+ else:
177
+ raise ValueError(f"Unknown lookup strategy: {lookup_strategy}")
178
+
179
+ def reset(self) -> None:
180
+ """Reset the cache state."""
181
+ self._seen_tokens = 0
182
+ self.key_cache.clear()
183
+ self.value_cache.clear()
184
+
185
+ def get_seq_length(self, step_idx: int = 0) -> int:
186
+ return self._seen_tokens
187
+
188
+ def get_memory_usage(self) -> float:
189
+ total_bytes = 0
190
+ # For each recurrent step/layer index
191
+ for step_idx in self.key_cache:
192
+ # Get the sequence cache for this step
193
+ key_seq_cache = self.key_cache[step_idx]
194
+ for seq_idx in key_seq_cache:
195
+ key_tensor = key_seq_cache[seq_idx]
196
+ # Add memory for of key tensors, assuming value is the same
197
+ total_bytes += key_tensor.nelement() * key_tensor.element_size()
198
+ return total_bytes * 2 / (1024 * 1024)
199
+
200
+
201
+ class CausalSelfAttention(torch.nn.Module):
202
+ def __init__(self, config: RavenConfig) -> None:
203
+ super().__init__()
204
+ self.config = config
205
+ self.n_head = config.num_attention_heads
206
+ self.n_kv_heads = config.num_key_value_heads
207
+ self.head_dim = config.n_embd // self.n_head
208
+
209
+ shape = (self.n_head + 2 * self.n_kv_heads) * self.head_dim
210
+ self.chunks = [config.n_embd, self.n_kv_heads * self.head_dim, self.n_kv_heads * self.head_dim]
211
+ self.Wqkv = torch.nn.Linear(config.n_embd, shape, bias=False)
212
+ if config.qk_bias:
213
+ self.qk_bias = torch.nn.Parameter(torch.zeros(2, 1, self.n_head, self.head_dim))
214
+ self.proj = torch.nn.Linear(config.n_embd, config.n_embd, bias=False)
215
+
216
+ def forward(
217
+ self,
218
+ x: Tensor,
219
+ freqs_cis: Tensor,
220
+ step_idx: int,
221
+ mask: Optional[Tensor] = None,
222
+ past_key_values: Optional[Cache] = None,
223
+ return_attn: bool = False,
224
+ ) -> tuple[Tensor, Optional[Tensor]]:
225
+ B, S, E = x.shape # batch size, sequence length, embedding dimensionality (n_embd)
226
+ q, k, v = self.Wqkv(x).split(self.chunks, dim=2)
227
+ q = q.view(B, S, self.n_head, self.head_dim)
228
+ k = k.view(B, S, self.n_kv_heads, self.head_dim)
229
+ v = v.view(B, S, self.n_kv_heads, self.head_dim)
230
+ # bias?
231
+ if self.config.qk_bias:
232
+ q_bias, k_bias = self.qk_bias.split(1, dim=0)
233
+ q, k = (q + q_bias).to(q.dtype), (k + k_bias).to(q.dtype)
234
+ # apply rotary
235
+ q, k = apply_rotary_emb_complex_like(q, k, freqs_cis=freqs_cis)
236
+
237
+ q = q.transpose(1, 2) # (B, nh, S, hs)
238
+ k = k.transpose(1, 2)
239
+ v = v.transpose(1, 2)
240
+
241
+ if past_key_values is not None:
242
+ k, v = past_key_values.update(k, v, step_idx)
243
+
244
+ if return_attn:
245
+ y, attention_map = self.compute_eager_sdpa(q, k, v, attn_mask=mask)
246
+ else:
247
+ y = torch.nn.functional.scaled_dot_product_attention(
248
+ q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=q.shape[2] > 1
249
+ )
250
+ y = y.transpose(1, 2).reshape(B, S, E).contiguous() # reshape is a view if possible (it mostly is)
251
+ return self.proj(y), attention_map if return_attn else None
252
+
253
+ def compute_eager_sdpa(self, q, k, v, attn_mask):
254
+ scale = 1.0 / math.sqrt(self.head_dim)
255
+ scores = torch.matmul(q, k.transpose(-2, -1)) * scale
256
+
257
+ if attn_mask is not None:
258
+ scores = scores + attn_mask
259
+ if q.shape[2] > 1:
260
+ causal_mask = torch.triu(torch.ones(q.shape[2], q.shape[2]), diagonal=1).bool()
261
+ scores.masked_fill_(causal_mask.to(scores.device), float("-inf"))
262
+
263
+ attention_weights = torch.nn.functional.softmax(scores, dim=-1)
264
+ y = torch.matmul(attention_weights, v)
265
+ return y, attention_weights.max(dim=1)[0]
266
+
267
+
268
+ class GatedMLP(torch.nn.Module):
269
+ def __init__(self, config: RavenConfig, in_features: int = 0) -> None:
270
+ super().__init__()
271
+ in_features = config.n_embd if in_features == 0 else in_features
272
+ self.fc = torch.nn.Linear(in_features, config.intermediate_size * 2, bias=False)
273
+
274
+ self.proj = torch.nn.Linear(config.intermediate_size, config.n_embd, bias=False)
275
+ self.nonlin = torch.nn.SiLU()
276
+
277
+ def forward(self, x: Tensor) -> Tensor:
278
+ # modified to single FC layer to improve parallelism
279
+ x_fc_1, x_fc_2 = self.fc(x).chunk(2, dim=-1)
280
+ x = self.nonlin(x_fc_1) * x_fc_2
281
+ return self.proj(x)
282
+
283
+
284
+ class SandwichBlock(torch.nn.Module):
285
+ expanded = False
286
+
287
+ def __init__(self, config: RavenConfig, layer_id: int) -> None:
288
+ super().__init__()
289
+ self.norm_1 = RMSNorm(config.n_embd, eps=config.norm_eps)
290
+ self.attn = CausalSelfAttention(config)
291
+ self.norm_2 = RMSNorm(config.n_embd, eps=config.norm_eps)
292
+ self.mlp = GatedMLP(config)
293
+ self.norm_3 = RMSNorm(config.n_embd, eps=config.norm_eps)
294
+ self.norm_4 = RMSNorm(config.n_embd, eps=config.norm_eps)
295
+ self.layer_id = layer_id
296
+
297
+ def forward(
298
+ self,
299
+ x: Tensor,
300
+ freqs_cis: Tensor,
301
+ step_idx: int,
302
+ mask: Optional[Tensor] = None,
303
+ past_key_values: Optional[Cache] = None,
304
+ return_attn: bool = False,
305
+ ) -> tuple[Tensor, Optional[Tensor]]:
306
+ attn_out, attn_map = self.attn(self.norm_1(x), freqs_cis, step_idx, mask, past_key_values, return_attn)
307
+ x = self.norm_2(attn_out + x)
308
+ x = self.norm_4(self.mlp(self.norm_3(x)) + x)
309
+ return x, attn_map
310
+
311
+
312
+ class RavenForCausalLM(RavenPreTrainedModel):
313
+ def __init__(
314
+ self,
315
+ config: RavenConfig,
316
+ ) -> None:
317
+ super().__init__(config)
318
+ self.config = config
319
+
320
+ # Transformer layers
321
+ prelude = torch.nn.ModuleList(SandwichBlock(config, layer_id=i) for i in range(config.n_layers_in_prelude))
322
+ adapter = torch.nn.Linear(config.n_embd * 2, config.n_embd, bias=config.bias)
323
+ core_block = torch.nn.ModuleList(
324
+ SandwichBlock(config, layer_id=i + config.n_layers_in_prelude)
325
+ for i in range(config.n_layers_in_recurrent_block)
326
+ )
327
+ o = config.n_layers_in_prelude + config.n_layers_in_recurrent_block * config.mean_recurrence
328
+ coda = torch.nn.ModuleList(SandwichBlock(config, layer_id=i + o) for i in range(config.n_layers_in_coda))
329
+
330
+ self.transformer = torch.nn.ModuleDict(
331
+ dict(
332
+ wte=torch.nn.Embedding(config.padded_vocab_size, config.n_embd),
333
+ prelude=prelude,
334
+ adapter=adapter,
335
+ core_block=core_block,
336
+ coda=coda,
337
+ ln_f=RMSNorm(config.n_embd, eps=config.norm_eps), # used twice :>
338
+ )
339
+ )
340
+ self.emb_scale = config.init_values["embed_scale"]
341
+ # Head
342
+ self.lm_head = torch.nn.Linear(config.n_embd, config.padded_vocab_size, bias=False)
343
+ if self.config.tie_embeddings:
344
+ self.lm_head.weight = self.transformer.wte.weight
345
+ # rope
346
+ self.register_buffer("freqs_cis", self._precompute_freqs_cis(), persistent=True)
347
+
348
+ def _precompute_freqs_cis(self):
349
+ # can actually be a buffer now, and remains in fp32! (at least in the settings I tested)
350
+ freqs_cis = precompute_freqs_cis(
351
+ self.config.n_embd // self.config.num_attention_heads, self.config.block_size, self.config.rope_base, 1
352
+ )
353
+ return freqs_cis
354
+
355
+ def forward(
356
+ self,
357
+ input_ids: torch.Tensor,
358
+ input_embeds: Optional[torch.Tensor] = None,
359
+ input_states: Optional[torch.Tensor] = None,
360
+ attention_mask: Optional[torch.Tensor] = None,
361
+ position_ids: Optional[torch.Tensor] = None,
362
+ labels: Optional[torch.Tensor] = None,
363
+ num_steps: Optional[torch.Tensor] = None,
364
+ past_key_values: Optional[Cache] = None,
365
+ output_details: dict = {
366
+ "return_logits": True,
367
+ "return_latents": True,
368
+ "return_attention": False,
369
+ "return_head": False,
370
+ "return_stats": True,
371
+ },
372
+ use_cache: bool = False,
373
+ cache_position: Optional[torch.Tensor] = None,
374
+ **kwargs,
375
+ ) -> CausalLMOutputRecurrentLatents:
376
+ # Support multiple position formats:
377
+ if position_ids is None and cache_position is None:
378
+ freqs_cis = self.freqs_cis[:, : input_ids.shape[1]]
379
+ elif position_ids is not None:
380
+ freqs_cis = self.freqs_cis.index_select(1, position_ids.squeeze())
381
+ elif cache_position is not None:
382
+ freqs_cis = self.freqs_cis[:, cache_position]
383
+
384
+ if input_embeds is None:
385
+ input_embeds = self.transformer.wte(input_ids)
386
+
387
+ if self.emb_scale != 1:
388
+ input_embeds = input_embeds * self.emb_scale # type: ignore
389
+
390
+ if use_cache and past_key_values is None:
391
+ past_key_values = HuginnDynamicCache()
392
+ attn_maps = {}
393
+ return_attn = output_details["return_attention"]
394
+
395
+ # Non-recurrent prelude
396
+ for block_idx, block in enumerate(self.transformer.prelude):
397
+ input_embeds, attn_map = block(
398
+ input_embeds, freqs_cis, block_idx, attention_mask, past_key_values, return_attn
399
+ )
400
+ attn_maps[block_idx] = attn_map
401
+
402
+ # Main recurrence
403
+ x, num_steps_no_grad, num_steps_with_grad, xk, block_idx, attn_maps = self.iterate_forward(
404
+ input_embeds, # type: ignore
405
+ input_states,
406
+ freqs_cis,
407
+ block_idx,
408
+ attention_mask,
409
+ past_key_values,
410
+ num_steps,
411
+ attn_maps,
412
+ )
413
+ latent_states = x.clone().detach()
414
+
415
+ # Coda layers
416
+ for block_idx, block in enumerate(self.transformer.coda, start=1):
417
+ x, attn_map = block(x, freqs_cis, -block_idx, attention_mask, past_key_values, return_attn)
418
+ attn_maps[-block_idx] = attn_map
419
+ x = self.transformer.ln_f(x)
420
+
421
+ # Prediction head, assuming labels really are labels and not equal to input_ids
422
+ if labels is not None:
423
+ logits = self.lm_head(x).float()
424
+ loss = torch.nn.functional.cross_entropy(logits.view(-1, logits.shape[-1]), labels.view(-1))
425
+ log_ppl = loss.clone().detach()
426
+ else:
427
+ logits = self.lm_head(x).float()
428
+ loss, log_ppl = torch.as_tensor(0.0), torch.as_tensor(0.0)
429
+
430
+ return CausalLMOutputRecurrentLatents(
431
+ loss=loss,
432
+ log_ppl=log_ppl,
433
+ logits=logits if output_details["return_logits"] else None,
434
+ past_key_values=past_key_values,
435
+ hidden_states=x if output_details["return_head"] else None,
436
+ latent_states=latent_states if output_details["return_latents"] else None,
437
+ attention_maps=attn_maps if output_details["return_attention"] else None, # type: ignore
438
+ stats=self.get_stats(logits, x, latent_states, xk, input_embeds, num_steps_no_grad, num_steps_with_grad)
439
+ if output_details["return_stats"]
440
+ else None,
441
+ )
442
+
443
+ @torch._dynamo.disable(recursive=False) # type: ignore
444
+ def iterate_forward(
445
+ self,
446
+ input_embeds,
447
+ input_states,
448
+ freqs_cis,
449
+ block_idx,
450
+ mask,
451
+ past_key_values: Optional[Cache] = None,
452
+ num_steps: Optional[torch.Tensor] = None,
453
+ attn_maps: dict = {},
454
+ ):
455
+ x = xk = self.initialize_state(input_embeds) if input_states is None else input_states.clone()
456
+ if num_steps is None:
457
+ num_steps_no_grad, num_steps_with_grad = self.randomized_iteration_sampler() # type: ignore
458
+ elif hasattr(num_steps, "__len__") and len(num_steps) > 1:
459
+ num_steps_no_grad, num_steps_with_grad = num_steps
460
+ else:
461
+ num_steps_no_grad, num_steps_with_grad = num_steps, torch.tensor(0)
462
+
463
+ with torch.no_grad():
464
+ # ultra annoying in ddp due to
465
+ # https://discuss.pytorch.org/t/does-distributeddataparallel-work-with-torch-no-grad-and-find-unused-parameters-false/122594
466
+ # for now running with find_unused_params=True enabled even though the graph structure is (technically) clear
467
+ # and all parameters are always used
468
+ for step in range(num_steps_no_grad):
469
+ xk = x
470
+ x, block_idx, attn_maps = self.core_block_forward(
471
+ xk, input_embeds, freqs_cis, mask, past_key_values, block_idx, attn_maps
472
+ )
473
+
474
+ for step in range(num_steps_with_grad):
475
+ xk = x
476
+ x, block_idx, attn_maps = self.core_block_forward(
477
+ xk, input_embeds, freqs_cis, mask, past_key_values, block_idx, attn_maps
478
+ )
479
+ return self.transformer.ln_f(x), num_steps_no_grad, num_steps_with_grad, xk.detach(), block_idx, attn_maps
480
+
481
+ def core_block_forward(
482
+ self,
483
+ x,
484
+ input_embeds,
485
+ freqs_cis,
486
+ mask,
487
+ past_key_values,
488
+ block_idx: Union[torch.Tensor, int],
489
+ attn_maps: dict = {},
490
+ ):
491
+ x = self.transformer.adapter(torch.cat([x, input_embeds], dim=-1))
492
+ for idx, block in enumerate(self.transformer.core_block, start=1):
493
+ x, attn_map = block(x, freqs_cis, block_idx + idx, mask, past_key_values, return_attn=len(attn_maps) > 0)
494
+ attn_maps[block_idx + idx] = attn_map
495
+ return x, block_idx + idx, attn_maps
496
+
497
+ @torch.no_grad()
498
+ def iterate_one_step(
499
+ self,
500
+ input_embeds,
501
+ input_states,
502
+ position_ids: Optional[torch.Tensor] = None,
503
+ cache_position: Optional[torch.Tensor] = None,
504
+ block_idx: Union[torch.Tensor, int] = 0,
505
+ attention_mask: Optional[Tensor] = None,
506
+ past_key_values: Optional[Cache] = None,
507
+ attn_maps: dict = {},
508
+ ):
509
+ if position_ids is None and cache_position is None:
510
+ freqs_cis = self.freqs_cis[:, : input_embeds.shape[1]]
511
+ elif position_ids is not None:
512
+ freqs_cis = self.freqs_cis.index_select(1, position_ids.squeeze())
513
+ elif cache_position is not None:
514
+ freqs_cis = self.freqs_cis[:, cache_position]
515
+ x, block_idx, attn_maps = self.core_block_forward(
516
+ input_states, input_embeds, freqs_cis, attention_mask, past_key_values, block_idx, attn_maps
517
+ )
518
+ return x, block_idx, attn_maps
519
+
520
+ def predict_from_latents(
521
+ self,
522
+ latents,
523
+ attention_mask: Optional[torch.Tensor] = None,
524
+ position_ids: Optional[torch.Tensor] = None,
525
+ cache_position: Optional[torch.Tensor] = None,
526
+ past_key_values: Optional[Cache] = None,
527
+ return_attn: bool = False,
528
+ attn_maps: dict = {},
529
+ ):
530
+ if position_ids is None and cache_position is None:
531
+ freqs_cis = self.freqs_cis[:, : latents.shape[1]]
532
+ elif position_ids is not None:
533
+ freqs_cis = self.freqs_cis.index_select(1, position_ids.squeeze())
534
+ elif cache_position is not None:
535
+ freqs_cis = self.freqs_cis[:, cache_position]
536
+ x = self.transformer.ln_f(latents)
537
+ # Coda layers
538
+ for block_idx, block in enumerate(self.transformer.coda, start=1):
539
+ x, attn_map = block(x, freqs_cis, -block_idx, attention_mask, past_key_values)
540
+ attn_maps[block_idx] = attn_map
541
+ x = self.transformer.ln_f(x)
542
+
543
+ logits = self.lm_head(x).float()
544
+
545
+ return CausalLMOutputRecurrentLatents(
546
+ loss=torch.as_tensor(0.0),
547
+ log_ppl=torch.as_tensor(0.0),
548
+ logits=logits,
549
+ past_key_values=past_key_values,
550
+ attention_maps=attn_maps if len(attn_maps) > 0 else None,
551
+ )
552
+
553
+ def embed_inputs(
554
+ self,
555
+ input_ids: torch.Tensor,
556
+ attention_mask: Optional[torch.Tensor] = None,
557
+ position_ids: Optional[torch.Tensor] = None,
558
+ past_key_values: Optional[Cache] = None,
559
+ use_cache: bool = False,
560
+ cache_position: Optional[torch.Tensor] = None,
561
+ return_attn: bool = False,
562
+ **kwargs,
563
+ ) -> tuple[torch.Tensor, int, dict[int, Tensor]]:
564
+ # Support multiple position formats:
565
+ if position_ids is None and cache_position is None:
566
+ freqs_cis = self.freqs_cis[:, : input_ids.shape[1]]
567
+ elif position_ids is not None:
568
+ freqs_cis = self.freqs_cis.index_select(1, position_ids.squeeze())
569
+ elif cache_position is not None:
570
+ freqs_cis = self.freqs_cis[:, cache_position]
571
+
572
+ input_embeds = self.transformer.wte(input_ids)
573
+
574
+ if self.emb_scale != 1:
575
+ input_embeds = input_embeds * self.emb_scale # type: ignore
576
+
577
+ if use_cache and past_key_values is None:
578
+ past_key_values = HuginnDynamicCache()
579
+
580
+ # Non-recurrent prelude
581
+ attn_maps = {}
582
+ for block_idx, block in enumerate(self.transformer.prelude):
583
+ input_embeds, attn_maps = block(
584
+ input_embeds, freqs_cis, block_idx, attention_mask, past_key_values, return_attn
585
+ )
586
+ return input_embeds, block_idx, attn_maps
587
+
588
+ @torch._dynamo.disable(recursive=False) # type: ignore
589
+ def randomized_iteration_sampler(self) -> tuple[torch.Tensor, torch.Tensor]:
590
+ """Outputs are long tensors so that they can be passed through compiled functions"""
591
+ t = max(self.config.mean_recurrence - self.config.mean_backprop_depth, 0)
592
+ s = self.config.mean_backprop_depth
593
+ if self.training:
594
+ sigma = 0.5
595
+ mu = math.log(t + s) - (sigma**2 / 2)
596
+ rate = torch.zeros((1,)).log_normal_(mean=mu, std=sigma)
597
+ p = torch.poisson(torch.tensor([rate], dtype=torch.float)) + 1
598
+ n = torch.clamp(p - s, min=0)
599
+ k = torch.as_tensor(torch.minimum(torch.as_tensor(s), p))
600
+ else:
601
+ n, k = torch.as_tensor(self.config.mean_recurrence), torch.as_tensor(0)
602
+
603
+ return n.to(dtype=torch.long), k.to(dtype=torch.long)
604
+
605
+ def initialize_state(self, input_embeds, deterministic: bool = False):
606
+ x = torch.randn_like(input_embeds)
607
+ std = self.config.init_values["std"]
608
+ torch.nn.init.trunc_normal_(x, mean=0.0, std=std, a=-3 * std, b=3 * std)
609
+ if self.emb_scale != 1:
610
+ x = x * self.emb_scale
611
+ return x if not deterministic else x.zero_()
612
+
613
+ def prepare_inputs_for_generation(
614
+ self,
615
+ input_ids: torch.LongTensor,
616
+ past_key_values: Optional[Cache] = None,
617
+ attention_mask: Optional[torch.LongTensor] = None,
618
+ inputs_embeds: Optional[torch.FloatTensor] = None,
619
+ cache_position: Optional[torch.LongTensor] = None,
620
+ **kwargs,
621
+ ):
622
+ model_inputs = {}
623
+ model_inputs["cache_position"] = cache_position
624
+ current_input_length = input_ids.shape[1]
625
+ if past_key_values is not None:
626
+ if type(past_key_values) == DynamicCache:
627
+ # Need to use custom cache, detect and replace HF dynamic cache if generate injects it
628
+ assert past_key_values.get_seq_length() == 0
629
+ past_key_values = HuginnDynamicCache()
630
+ model_inputs["past_key_values"] = past_key_values if kwargs["use_cache"] else None
631
+ input_ids = input_ids[:, cache_position] # type: ignore
632
+ model_inputs["input_ids"] = input_ids.clone(memory_format=torch.contiguous_format)
633
+
634
+ if cache_position is None:
635
+ position_ids = torch.arange(current_input_length)[None, :].to(input_ids.device)
636
+ model_inputs["position_ids"] = position_ids[:, -current_input_length:].clone(
637
+ memory_format=torch.contiguous_format
638
+ ) # some form of position_ids is a critical argument for the model to correctly apply rope!
639
+
640
+ # forward all other entries
641
+ for key, value in kwargs.items():
642
+ if key not in model_inputs:
643
+ model_inputs[key] = value
644
+ return model_inputs
645
+
646
+ @torch.no_grad()
647
+ def generate_minimal(
648
+ self,
649
+ input_ids: torch.LongTensor,
650
+ generation_config: Optional[GenerationConfig] = None, # type: ignore
651
+ tokenizer=None,
652
+ streamer=None,
653
+ continuous_compute=False, # warm-start state / continuous CoT
654
+ cache_kwargs: dict = {},
655
+ **model_kwargs,
656
+ ) -> Union[torch.Tensor, dict[str, Any]]:
657
+ """Minimal single-sequence generation. Template for more complicated generate tasks"""
658
+ # Setup
659
+ if generation_config is None:
660
+ generation_config: GenerationConfig = self.generation_config # type: ignore
661
+ model_kwargs["past_key_values"] = HuginnDynamicCache(**cache_kwargs)
662
+ model_kwargs["use_cache"] = True
663
+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
664
+ stop_tokens = self._get_stops(generation_config, tokenizer).to(input_ids.device)
665
+ if continuous_compute:
666
+ embedded_inputs, _, _ = self.embed_inputs(input_ids)
667
+ model_kwargs["input_states"] = self.initialize_state(embedded_inputs)
668
+ # Generate tokens
669
+ for _ in range(generation_config.max_length - input_ids.shape[1]):
670
+ # Forward pass
671
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
672
+ outputs = self(**model_inputs)
673
+ next_token_logits = outputs.logits[0, -1, :]
674
+ if continuous_compute:
675
+ current_last_latent = outputs.latent_states[:, -1:, :]
676
+
677
+ # Sample or select next token
678
+ if generation_config.do_sample:
679
+ if generation_config.temperature:
680
+ next_token_logits = next_token_logits / generation_config.temperature
681
+
682
+ probs = F.softmax(next_token_logits, dim=-1)
683
+
684
+ # Apply top_k
685
+ if generation_config.top_k:
686
+ top_k_probs, _ = torch.topk(probs, generation_config.top_k)
687
+ probs[probs < top_k_probs[-1]] = 0
688
+ # Apply top_p
689
+ if generation_config.top_p:
690
+ sorted_probs = torch.sort(probs, descending=True)[0]
691
+ cumsum = torch.cumsum(sorted_probs, dim=-1)
692
+ probs[cumsum > generation_config.top_p] = 0
693
+ # Apply min_p
694
+ if generation_config.min_p:
695
+ probs[probs < generation_config.min_p * probs.max()] = 0
696
+
697
+ probs = probs / probs.sum()
698
+ next_token = torch.multinomial(probs, num_samples=1)
699
+ else:
700
+ next_token = torch.argmax(next_token_logits, dim=-1, keepdim=True)
701
+
702
+ input_ids = torch.cat([input_ids, next_token[None, :]], dim=-1) # type: ignore
703
+
704
+ if streamer:
705
+ streamer.put(next_token.cpu())
706
+
707
+ # Update model kwargs
708
+ model_kwargs = self._update_model_kwargs_for_generation(outputs, model_kwargs)
709
+ if continuous_compute:
710
+ model_kwargs["input_states"] = current_last_latent
711
+
712
+ # Check if we hit a stop token
713
+ if stop_tokens is not None and next_token in stop_tokens:
714
+ break
715
+
716
+ if streamer:
717
+ streamer.end()
718
+
719
+ if generation_config.return_dict_in_generate:
720
+ return GenerateDecoderOnlyOutput(
721
+ sequences=input_ids,
722
+ scores=None,
723
+ logits=None,
724
+ attentions=None,
725
+ hidden_states=None,
726
+ past_key_values=model_kwargs.get("past_key_values"),
727
+ )
728
+ return input_ids
729
+
730
+ @torch.no_grad()
731
+ def generate_with_adaptive_compute(
732
+ self,
733
+ input_ids: torch.LongTensor,
734
+ generation_config: Optional[GenerationConfig] = None, # type: ignore
735
+ tokenizer=None,
736
+ streamer=None,
737
+ continuous_compute=False, # warm-start state / continuous CoT
738
+ latent_dampening=False,
739
+ criterion="entropy-diff",
740
+ exit_threshold: Union[str, float, int] = "auto",
741
+ cache_kwargs: dict = {},
742
+ **model_kwargs,
743
+ ) -> Union[torch.Tensor, GenerateDecoderOnlyOutput]:
744
+ """Minimal single-sequence generation. Template for more complicated generate tasks"""
745
+ # Setup
746
+ if generation_config is None:
747
+ generation_config: GenerationConfig = self.generation_config # type: ignore
748
+ model_kwargs["past_key_values"] = HuginnDynamicCache(**cache_kwargs)
749
+ model_kwargs["use_cache"] = True
750
+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
751
+ stop_tokens = self._get_stops(generation_config, tokenizer).to(input_ids.device)
752
+ if continuous_compute:
753
+ embedded_inputs, _, _ = self.embed_inputs(input_ids)
754
+ current_last_latent = self.initialize_state(embedded_inputs)
755
+ compute_steps = []
756
+
757
+ # Generate tokens
758
+ for step in range(generation_config.max_length - input_ids.shape[1]):
759
+ # Adaptive compute forward
760
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
761
+ aux_inputs = {
762
+ k: model_inputs[k] for k in ["cache_position", "past_key_values", "attention_mask"] if k in model_inputs
763
+ }
764
+ embedded_inputs, block_idx, _ = self.embed_inputs(model_inputs["input_ids"], **aux_inputs)
765
+ if not continuous_compute:
766
+ current_latents = self.initialize_state(embedded_inputs, deterministic=False)
767
+ else:
768
+ current_latents = current_last_latent
769
+
770
+ # Prep criterions:
771
+ if criterion == "entropy-diff":
772
+ entropy = torch.tensor(100.0, device=input_ids.device)
773
+ exit_threshold = 1e-3 if exit_threshold == "auto" else float(exit_threshold)
774
+ elif criterion in ["latent-diff", "none"]:
775
+ exit_threshold = 0.03 if exit_threshold == "auto" else float(exit_threshold)
776
+ elif "kl" in criterion:
777
+ V = self.config.padded_vocab_size
778
+ log_probs = (1 / V * torch.ones(V, device=input_ids.device)).log()
779
+ if criterion == "minp-kl":
780
+ exit_threshold = 1e-6 if exit_threshold == "auto" else float(exit_threshold)
781
+ else:
782
+ exit_threshold = 5e-4 if exit_threshold == "auto" else float(exit_threshold)
783
+ elif criterion == "argmax-stability":
784
+ stable_for_n_steps = 0
785
+ current_argmax = torch.tensor(-1, dtype=torch.long, device=input_ids.device)
786
+ exit_threshold = 5 if exit_threshold == "auto" else int(exit_threshold)
787
+ else:
788
+ raise ValueError("Invalid adaptive compute strategy.")
789
+
790
+ all_latents = []
791
+ exit_values = []
792
+ for compute_step in range(model_inputs["num_steps"]):
793
+ prev_latents = current_latents.clone()
794
+ current_latents, block_idx, _ = self.iterate_one_step(
795
+ embedded_inputs, current_latents, block_idx=block_idx, **aux_inputs
796
+ )
797
+ all_latents.append(current_latents if latent_dampening else None)
798
+ if step > 0: # do not exit in prefill:
799
+ if criterion == "entropy-diff":
800
+ prev_entropy = entropy.clone()
801
+ outputs = self.predict_from_latents(current_latents, **aux_inputs)
802
+ probs = F.softmax(outputs.logits[:, -1, :], dim=-1) # type: ignore
803
+ entropy = -torch.sum(probs * torch.log(probs + 1e-10), dim=-1).mean()
804
+ entropy_diff = (entropy - prev_entropy).abs()
805
+ exit_values.append(entropy_diff.item())
806
+ if entropy_diff < exit_threshold:
807
+ break
808
+ elif criterion == "latent-diff":
809
+ norm_diff = (prev_latents - current_latents).norm() / current_latents.norm()
810
+ exit_values.append(norm_diff.item())
811
+ if norm_diff < exit_threshold:
812
+ break
813
+ elif criterion == "kl":
814
+ prev_log_probs = log_probs.clone()
815
+ outputs = self.predict_from_latents(current_latents, **aux_inputs)
816
+ log_probs = F.log_softmax(outputs.logits[:, -1, :], dim=-1) # type: ignore
817
+ kl = F.kl_div(log_probs, prev_log_probs, reduction="none", log_target=True).sum(dim=-1)
818
+ exit_values.append(kl.item())
819
+ if kl < exit_threshold:
820
+ break
821
+ elif criterion == "minp-kl":
822
+ prev_log_probs = log_probs.clone()
823
+ outputs = self.predict_from_latents(current_latents, **aux_inputs)
824
+ probs = F.softmax(outputs.logits[:, -1, :], dim=-1) # type: ignore
825
+ probs[probs < 0.1 * probs.max()] = 1 / V
826
+ probs = probs / probs.sum()
827
+ log_probs = probs.log()
828
+ kl = F.kl_div(log_probs, prev_log_probs, reduction="none", log_target=True).sum(dim=-1)
829
+ exit_values.append(kl.item())
830
+ if kl < exit_threshold:
831
+ break
832
+ elif criterion == "argmax-stability":
833
+ prev_argmax = current_argmax.clone()
834
+ outputs = self.predict_from_latents(current_latents, **aux_inputs)
835
+ current_argmax = outputs.logits[0, -1, :].argmax(dim=-1) # type: ignore
836
+ if current_argmax == prev_argmax:
837
+ stable_for_n_steps += 1
838
+ else:
839
+ stable_for_n_steps = 0
840
+ exit_values.append(stable_for_n_steps)
841
+ if stable_for_n_steps >= exit_threshold:
842
+ break
843
+ elif criterion == "none":
844
+ pass
845
+
846
+ else:
847
+ if not latent_dampening:
848
+ outputs = self.predict_from_latents(current_latents, **aux_inputs)
849
+ else:
850
+ dampened_latents = torch.sum(torch.cat(all_latents, dim=0), dim=0, keepdim=True)
851
+ outputs = self.predict_from_latents(dampened_latents, **aux_inputs)
852
+ compute_steps.append([compute_step + 1, exit_values])
853
+
854
+ next_token_logits = outputs.logits[0, -1, :] # type: ignore
855
+ if continuous_compute: # Save last latent
856
+ current_last_latent = current_latents[:, -1:, :]
857
+
858
+ # Sample or select next token
859
+ if generation_config.do_sample:
860
+ if generation_config.temperature:
861
+ next_token_logits = next_token_logits / generation_config.temperature
862
+
863
+ probs = F.softmax(next_token_logits, dim=-1)
864
+ # Apply top_k
865
+ if generation_config.top_k:
866
+ top_k_probs, _ = torch.topk(probs, generation_config.top_k)
867
+ probs[probs < top_k_probs[-1]] = 0
868
+ # Apply top_p
869
+ if generation_config.top_p:
870
+ sorted_probs = torch.sort(probs, descending=True)[0]
871
+ cumsum = torch.cumsum(sorted_probs, dim=-1)
872
+ probs[cumsum > generation_config.top_p] = 0
873
+ # Apply min_p
874
+ if generation_config.min_p:
875
+ probs[probs < generation_config.min_p * probs.max()] = 0
876
+
877
+ probs = probs / probs.sum()
878
+ next_token = torch.multinomial(probs, num_samples=1)
879
+ else:
880
+ next_token = torch.argmax(next_token_logits, dim=-1, keepdim=True)
881
+
882
+ input_ids = torch.cat([input_ids, next_token[None, :]], dim=-1) # type: ignore
883
+
884
+ if streamer:
885
+ streamer.put(next_token.cpu())
886
+
887
+ # Update model kwargs
888
+ model_kwargs = self._update_model_kwargs_for_generation(outputs, model_kwargs)
889
+
890
+ # Check if we hit a stop token
891
+ if stop_tokens is not None and next_token in stop_tokens:
892
+ break
893
+
894
+ if streamer:
895
+ streamer.end()
896
+
897
+ if generation_config.return_dict_in_generate:
898
+ return GenerateDecoderOnlyOutput(
899
+ sequences=input_ids,
900
+ scores=compute_steps, # type: ignore
901
+ logits=None,
902
+ attentions=None,
903
+ hidden_states=None,
904
+ past_key_values=model_kwargs.get("past_key_values"),
905
+ )
906
+ return input_ids
907
+
908
+ def _get_stops(self, generation_config, tokenizer):
909
+ stop_tokens = set()
910
+ if generation_config.eos_token_id is not None:
911
+ stop_tokens.add(generation_config.eos_token_id)
912
+ if hasattr(generation_config, "stop_strings") and tokenizer and generation_config.stop_strings:
913
+ for s in generation_config.stop_strings:
914
+ token_id = tokenizer(s, add_special_tokens=False)["input_ids"][0]
915
+ stop_tokens.add(token_id)
916
+ return torch.tensor(list(stop_tokens))
917
+
918
+ def get_stats(self, logits, x, latent_states, xk, input_embeds, num_steps_no_grad, num_steps_with_grad):
919
+ probs = torch.softmax(logits.float(), dim=-1)
920
+ prob_entropy = torch.where(probs > 0, -probs * probs.log(), 0).sum(dim=-1)
921
+ residual_diff = (x - latent_states).norm(dim=-1)
922
+ rel_residual = residual_diff / latent_states.norm(dim=-1)
923
+ stats = {
924
+ "entropy": prob_entropy,
925
+ "residual_diff": residual_diff,
926
+ "rel_residual": rel_residual,
927
+ "num_steps_no_grad": num_steps_no_grad,
928
+ "num_steps_with_grad": num_steps_with_grad,
929
+ }
930
+ return stats
931
+
932
+
933
+ #################################### Utils #######################################################################
934
+ def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0, condense_ratio: int = 1):
935
+ with torch.autocast("cuda", enabled=False):
936
+ inv_freqs = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
937
+ t = torch.arange(end, dtype=torch.float32, device=inv_freqs.device) / condense_ratio
938
+ freqs = torch.outer(t, inv_freqs).float()
939
+ return torch.stack([torch.cos(freqs)[None, :, None, :], torch.sin(freqs)[None, :, None, :]], dim=4)
940
+ # equivalent to
941
+ # freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
942
+ # cache = torch.stack([freqs_cis.real, freqs_cis.imag], dim=-1)
943
+
944
+
945
+ def apply_rotary_emb_complex_like(q: Tensor, k: Tensor, freqs_cis: Tensor) -> tuple[Tensor, Tensor]:
946
+ with torch.autocast("cuda", enabled=False):
947
+ qk_r2 = torch.cat([q, k], dim=2).unflatten(dim=-1, sizes=(-1, 2)).float() # cast to float32 for smooth skin
948
+ rotated_qk_r2 = torch.stack(
949
+ [
950
+ qk_r2[..., 0] * freqs_cis[..., 0] - qk_r2[..., 1] * freqs_cis[..., 1],
951
+ qk_r2[..., 1] * freqs_cis[..., 0] + qk_r2[..., 0] * freqs_cis[..., 1],
952
+ ],
953
+ -1,
954
+ ).flatten(3)
955
+ rotated_qk = rotated_qk_r2
956
+ return torch.split(rotated_qk.type_as(q), q.shape[2], dim=2) # type: ignore
957
+
958
+
959
+ #################################### HF registration ############################################################
960
+
961
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
962
+
963
+ # New
964
+ RavenConfig.register_for_auto_class()
965
+
966
+ RavenForCausalLM.register_for_auto_class("AutoModel")
967
+ RavenForCausalLM.register_for_auto_class("AutoModelForCausalLM")
968
+
969
+ # Old?
970
+ AutoConfig.register("huginn_raven", RavenConfig)
971
+ AutoModel.register(RavenConfig, RavenForCausalLM)
972
+ AutoModelForCausalLM.register(RavenConfig, RavenForCausalLM)