JonasGeiping commited on
Commit
47bba14
·
verified ·
1 Parent(s): d7ff5e4

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