JonasGeiping commited on
Commit
543b80b
·
verified ·
1 Parent(s): 6739519

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": "bfloat16",
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-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:37dd42dee1ae5fe53de7d5c6b238327974ca193482c52e479814e82e54095ba0
3
+ size 4981416480
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cf8bdae940cb5b452e2a2ee83695301e007de4c61b4798da3dc798dd394daac5
3
+ size 2841392416
model.safetensors.index.json ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 7822800192
4
+ },
5
+ "weight_map": {
6
+ "freqs_cis": "model-00001-of-00002.safetensors",
7
+ "lm_head.weight": "model-00002-of-00002.safetensors",
8
+ "transformer.adapter.weight": "model-00001-of-00002.safetensors",
9
+ "transformer.coda.0.attn.Wqkv.weight": "model-00002-of-00002.safetensors",
10
+ "transformer.coda.0.attn.proj.weight": "model-00002-of-00002.safetensors",
11
+ "transformer.coda.0.attn.qk_bias": "model-00002-of-00002.safetensors",
12
+ "transformer.coda.0.mlp.fc.weight": "model-00002-of-00002.safetensors",
13
+ "transformer.coda.0.mlp.proj.weight": "model-00002-of-00002.safetensors",
14
+ "transformer.coda.0.norm_1.weight": "model-00002-of-00002.safetensors",
15
+ "transformer.coda.0.norm_2.weight": "model-00002-of-00002.safetensors",
16
+ "transformer.coda.0.norm_3.weight": "model-00002-of-00002.safetensors",
17
+ "transformer.coda.0.norm_4.weight": "model-00002-of-00002.safetensors",
18
+ "transformer.coda.1.attn.Wqkv.weight": "model-00002-of-00002.safetensors",
19
+ "transformer.coda.1.attn.proj.weight": "model-00002-of-00002.safetensors",
20
+ "transformer.coda.1.attn.qk_bias": "model-00002-of-00002.safetensors",
21
+ "transformer.coda.1.mlp.fc.weight": "model-00002-of-00002.safetensors",
22
+ "transformer.coda.1.mlp.proj.weight": "model-00002-of-00002.safetensors",
23
+ "transformer.coda.1.norm_1.weight": "model-00002-of-00002.safetensors",
24
+ "transformer.coda.1.norm_2.weight": "model-00002-of-00002.safetensors",
25
+ "transformer.coda.1.norm_3.weight": "model-00002-of-00002.safetensors",
26
+ "transformer.coda.1.norm_4.weight": "model-00002-of-00002.safetensors",
27
+ "transformer.core_block.0.attn.Wqkv.weight": "model-00001-of-00002.safetensors",
28
+ "transformer.core_block.0.attn.proj.weight": "model-00001-of-00002.safetensors",
29
+ "transformer.core_block.0.attn.qk_bias": "model-00001-of-00002.safetensors",
30
+ "transformer.core_block.0.mlp.fc.weight": "model-00001-of-00002.safetensors",
31
+ "transformer.core_block.0.mlp.proj.weight": "model-00001-of-00002.safetensors",
32
+ "transformer.core_block.0.norm_1.weight": "model-00001-of-00002.safetensors",
33
+ "transformer.core_block.0.norm_2.weight": "model-00001-of-00002.safetensors",
34
+ "transformer.core_block.0.norm_3.weight": "model-00001-of-00002.safetensors",
35
+ "transformer.core_block.0.norm_4.weight": "model-00001-of-00002.safetensors",
36
+ "transformer.core_block.1.attn.Wqkv.weight": "model-00001-of-00002.safetensors",
37
+ "transformer.core_block.1.attn.proj.weight": "model-00001-of-00002.safetensors",
38
+ "transformer.core_block.1.attn.qk_bias": "model-00001-of-00002.safetensors",
39
+ "transformer.core_block.1.mlp.fc.weight": "model-00001-of-00002.safetensors",
40
+ "transformer.core_block.1.mlp.proj.weight": "model-00001-of-00002.safetensors",
41
+ "transformer.core_block.1.norm_1.weight": "model-00001-of-00002.safetensors",
42
+ "transformer.core_block.1.norm_2.weight": "model-00001-of-00002.safetensors",
43
+ "transformer.core_block.1.norm_3.weight": "model-00001-of-00002.safetensors",
44
+ "transformer.core_block.1.norm_4.weight": "model-00001-of-00002.safetensors",
45
+ "transformer.core_block.2.attn.Wqkv.weight": "model-00001-of-00002.safetensors",
46
+ "transformer.core_block.2.attn.proj.weight": "model-00001-of-00002.safetensors",
47
+ "transformer.core_block.2.attn.qk_bias": "model-00001-of-00002.safetensors",
48
+ "transformer.core_block.2.mlp.fc.weight": "model-00001-of-00002.safetensors",
49
+ "transformer.core_block.2.mlp.proj.weight": "model-00001-of-00002.safetensors",
50
+ "transformer.core_block.2.norm_1.weight": "model-00001-of-00002.safetensors",
51
+ "transformer.core_block.2.norm_2.weight": "model-00001-of-00002.safetensors",
52
+ "transformer.core_block.2.norm_3.weight": "model-00001-of-00002.safetensors",
53
+ "transformer.core_block.2.norm_4.weight": "model-00001-of-00002.safetensors",
54
+ "transformer.core_block.3.attn.Wqkv.weight": "model-00001-of-00002.safetensors",
55
+ "transformer.core_block.3.attn.proj.weight": "model-00001-of-00002.safetensors",
56
+ "transformer.core_block.3.attn.qk_bias": "model-00001-of-00002.safetensors",
57
+ "transformer.core_block.3.mlp.fc.weight": "model-00002-of-00002.safetensors",
58
+ "transformer.core_block.3.mlp.proj.weight": "model-00002-of-00002.safetensors",
59
+ "transformer.core_block.3.norm_1.weight": "model-00001-of-00002.safetensors",
60
+ "transformer.core_block.3.norm_2.weight": "model-00001-of-00002.safetensors",
61
+ "transformer.core_block.3.norm_3.weight": "model-00002-of-00002.safetensors",
62
+ "transformer.core_block.3.norm_4.weight": "model-00002-of-00002.safetensors",
63
+ "transformer.ln_f.weight": "model-00002-of-00002.safetensors",
64
+ "transformer.prelude.0.attn.Wqkv.weight": "model-00001-of-00002.safetensors",
65
+ "transformer.prelude.0.attn.proj.weight": "model-00001-of-00002.safetensors",
66
+ "transformer.prelude.0.attn.qk_bias": "model-00001-of-00002.safetensors",
67
+ "transformer.prelude.0.mlp.fc.weight": "model-00001-of-00002.safetensors",
68
+ "transformer.prelude.0.mlp.proj.weight": "model-00001-of-00002.safetensors",
69
+ "transformer.prelude.0.norm_1.weight": "model-00001-of-00002.safetensors",
70
+ "transformer.prelude.0.norm_2.weight": "model-00001-of-00002.safetensors",
71
+ "transformer.prelude.0.norm_3.weight": "model-00001-of-00002.safetensors",
72
+ "transformer.prelude.0.norm_4.weight": "model-00001-of-00002.safetensors",
73
+ "transformer.prelude.1.attn.Wqkv.weight": "model-00001-of-00002.safetensors",
74
+ "transformer.prelude.1.attn.proj.weight": "model-00001-of-00002.safetensors",
75
+ "transformer.prelude.1.attn.qk_bias": "model-00001-of-00002.safetensors",
76
+ "transformer.prelude.1.mlp.fc.weight": "model-00001-of-00002.safetensors",
77
+ "transformer.prelude.1.mlp.proj.weight": "model-00001-of-00002.safetensors",
78
+ "transformer.prelude.1.norm_1.weight": "model-00001-of-00002.safetensors",
79
+ "transformer.prelude.1.norm_2.weight": "model-00001-of-00002.safetensors",
80
+ "transformer.prelude.1.norm_3.weight": "model-00001-of-00002.safetensors",
81
+ "transformer.prelude.1.norm_4.weight": "model-00001-of-00002.safetensors",
82
+ "transformer.wte.weight": "model-00001-of-00002.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,974 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ return_attn = False # hardcode for now
246
+ if return_attn:
247
+ y, attention_map = self.compute_eager_sdpa(q, k, v, attn_mask=mask)
248
+ else:
249
+ y = torch.nn.functional.scaled_dot_product_attention(
250
+ q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=q.shape[2] > 1
251
+ )
252
+ y = y.transpose(1, 2).reshape(B, S, E).contiguous() # reshape is a view if possible (it mostly is)
253
+ return self.proj(y), attention_map if return_attn else None
254
+
255
+ def compute_eager_sdpa(self, q, k, v, attn_mask):
256
+ scale = 1.0 / math.sqrt(self.head_dim)
257
+ scores = torch.matmul(q, k.transpose(-2, -1)) * scale
258
+
259
+ if attn_mask is not None:
260
+ scores = scores + attn_mask
261
+ if q.shape[2] > 1:
262
+ causal_mask = torch.triu(torch.ones(q.shape[2], q.shape[2]), diagonal=1).bool()
263
+ scores.masked_fill_(causal_mask.to(scores.device), float("-inf"))
264
+
265
+ attention_weights = torch.nn.functional.softmax(scores, dim=-1)
266
+ y = torch.matmul(attention_weights, v)
267
+ return y, attention_weights.max(dim=1)[0]
268
+
269
+
270
+ class GatedMLP(torch.nn.Module):
271
+ def __init__(self, config: RavenConfig, in_features: int = 0) -> None:
272
+ super().__init__()
273
+ in_features = config.n_embd if in_features == 0 else in_features
274
+ self.fc = torch.nn.Linear(in_features, config.intermediate_size * 2, bias=False)
275
+
276
+ self.proj = torch.nn.Linear(config.intermediate_size, config.n_embd, bias=False)
277
+ self.nonlin = torch.nn.SiLU()
278
+
279
+ def forward(self, x: Tensor) -> Tensor:
280
+ # modified to single FC layer to improve parallelism
281
+ x_fc_1, x_fc_2 = self.fc(x).chunk(2, dim=-1)
282
+ x = self.nonlin(x_fc_1) * x_fc_2
283
+ return self.proj(x)
284
+
285
+
286
+ class SandwichBlock(torch.nn.Module):
287
+ expanded = False
288
+
289
+ def __init__(self, config: RavenConfig, layer_id: int) -> None:
290
+ super().__init__()
291
+ self.norm_1 = RMSNorm(config.n_embd, eps=config.norm_eps)
292
+ self.attn = CausalSelfAttention(config)
293
+ self.norm_2 = RMSNorm(config.n_embd, eps=config.norm_eps)
294
+ self.mlp = GatedMLP(config)
295
+ self.norm_3 = RMSNorm(config.n_embd, eps=config.norm_eps)
296
+ self.norm_4 = RMSNorm(config.n_embd, eps=config.norm_eps)
297
+ self.layer_id = layer_id
298
+
299
+ def forward(
300
+ self,
301
+ x: Tensor,
302
+ freqs_cis: Tensor,
303
+ step_idx: int,
304
+ mask: Optional[Tensor] = None,
305
+ past_key_values: Optional[Cache] = None,
306
+ return_attn: bool = False,
307
+ ) -> tuple[Tensor, Optional[Tensor]]:
308
+ attn_out, attn_map = self.attn(self.norm_1(x), freqs_cis, step_idx, mask, past_key_values, return_attn)
309
+ x = self.norm_2(attn_out + x)
310
+ x = self.norm_4(self.mlp(self.norm_3(x)) + x)
311
+ return x, attn_map
312
+
313
+
314
+ class RavenForCausalLM(RavenPreTrainedModel, GenerationMixin):
315
+ def __init__(
316
+ self,
317
+ config: RavenConfig,
318
+ ) -> None:
319
+ super().__init__(config)
320
+ self.config = config
321
+
322
+ # Transformer layers
323
+ prelude = torch.nn.ModuleList(SandwichBlock(config, layer_id=i) for i in range(config.n_layers_in_prelude))
324
+ adapter = torch.nn.Linear(config.n_embd * 2, config.n_embd, bias=config.bias)
325
+ core_block = torch.nn.ModuleList(
326
+ SandwichBlock(config, layer_id=i + config.n_layers_in_prelude)
327
+ for i in range(config.n_layers_in_recurrent_block)
328
+ )
329
+ o = config.n_layers_in_prelude + config.n_layers_in_recurrent_block * config.mean_recurrence
330
+ coda = torch.nn.ModuleList(SandwichBlock(config, layer_id=i + o) for i in range(config.n_layers_in_coda))
331
+
332
+ self.transformer = torch.nn.ModuleDict(
333
+ dict(
334
+ wte=torch.nn.Embedding(config.padded_vocab_size, config.n_embd),
335
+ prelude=prelude,
336
+ adapter=adapter,
337
+ core_block=core_block,
338
+ coda=coda,
339
+ ln_f=RMSNorm(config.n_embd, eps=config.norm_eps), # used twice :>
340
+ )
341
+ )
342
+ self.emb_scale = config.init_values["embed_scale"]
343
+ # Head
344
+ self.lm_head = torch.nn.Linear(config.n_embd, config.padded_vocab_size, bias=False)
345
+ if self.config.tie_embeddings:
346
+ self.lm_head.weight = self.transformer.wte.weight
347
+ # rope
348
+ self.register_buffer("freqs_cis", self._precompute_freqs_cis(), persistent=True)
349
+
350
+ def _precompute_freqs_cis(self):
351
+ # can actually be a buffer now, and remains in fp32! (at least in the settings I tested)
352
+ freqs_cis = precompute_freqs_cis(
353
+ self.config.n_embd // self.config.num_attention_heads, self.config.block_size, self.config.rope_base, 1
354
+ )
355
+ return freqs_cis
356
+
357
+ def forward(
358
+ self,
359
+ input_ids: torch.Tensor,
360
+ input_embeds: Optional[torch.Tensor] = None,
361
+ input_states: Optional[torch.Tensor] = None,
362
+ attention_mask: Optional[torch.Tensor] = None,
363
+ position_ids: Optional[torch.Tensor] = None,
364
+ labels: Optional[torch.Tensor] = None,
365
+ num_steps: Optional[torch.Tensor] = None,
366
+ past_key_values: Optional[Cache] = None,
367
+ output_details: dict = {
368
+ "return_logits": True,
369
+ "return_latents": True,
370
+ "return_attention": False,
371
+ "return_head": False,
372
+ "return_stats": True,
373
+ },
374
+ use_cache: bool = False,
375
+ cache_position: Optional[torch.Tensor] = None,
376
+ **kwargs,
377
+ ) -> CausalLMOutputRecurrentLatents:
378
+ # Support multiple position formats:
379
+ if position_ids is None and cache_position is None:
380
+ freqs_cis = self.freqs_cis[:, : input_ids.shape[1]]
381
+ elif position_ids is not None:
382
+ freqs_cis = self.freqs_cis.index_select(1, position_ids.squeeze())
383
+ elif cache_position is not None:
384
+ freqs_cis = self.freqs_cis[:, cache_position]
385
+
386
+ if input_embeds is None:
387
+ input_embeds = self.transformer.wte(input_ids)
388
+
389
+ if self.emb_scale != 1:
390
+ input_embeds = input_embeds * self.emb_scale # type: ignore
391
+
392
+ if use_cache and past_key_values is None:
393
+ past_key_values = HuginnDynamicCache()
394
+ attn_maps = {}
395
+ return_attn = output_details["return_attention"]
396
+
397
+ # Non-recurrent prelude
398
+ for block_idx, block in enumerate(self.transformer.prelude):
399
+ input_embeds, attn_map = block(
400
+ input_embeds, freqs_cis, block_idx, attention_mask, past_key_values, return_attn
401
+ )
402
+ attn_maps[block_idx] = attn_map
403
+
404
+ # Main recurrence
405
+ x, num_steps_no_grad, num_steps_with_grad, xk, block_idx, attn_maps = self.iterate_forward(
406
+ input_embeds, # type: ignore
407
+ input_states,
408
+ freqs_cis,
409
+ block_idx,
410
+ attention_mask,
411
+ past_key_values,
412
+ num_steps,
413
+ attn_maps,
414
+ )
415
+ latent_states = x.clone().detach()
416
+
417
+ # Coda layers
418
+ for block_idx, block in enumerate(self.transformer.coda, start=1):
419
+ x, attn_map = block(x, freqs_cis, -block_idx, attention_mask, past_key_values, return_attn)
420
+ attn_maps[-block_idx] = attn_map
421
+ x = self.transformer.ln_f(x)
422
+
423
+ # Prediction head, assuming labels really are labels and not equal to input_ids
424
+ if labels is not None:
425
+ logits = self.lm_head(x).float()
426
+ loss = torch.nn.functional.cross_entropy(logits.view(-1, logits.shape[-1]), labels.view(-1))
427
+ log_ppl = loss.clone().detach()
428
+ else:
429
+ logits = self.lm_head(x).float()
430
+ loss, log_ppl = torch.as_tensor(0.0), torch.as_tensor(0.0)
431
+
432
+ return CausalLMOutputRecurrentLatents(
433
+ loss=loss,
434
+ log_ppl=log_ppl,
435
+ logits=logits if output_details["return_logits"] else None,
436
+ past_key_values=past_key_values,
437
+ hidden_states=x if output_details["return_head"] else None,
438
+ latent_states=latent_states if output_details["return_latents"] else None,
439
+ attention_maps=attn_maps if output_details["return_attention"] else None, # type: ignore
440
+ stats=self.get_stats(logits, x, latent_states, xk, input_embeds, num_steps_no_grad, num_steps_with_grad)
441
+ if output_details["return_stats"]
442
+ else None,
443
+ )
444
+
445
+ @torch._dynamo.disable(recursive=False) # type: ignore
446
+ def iterate_forward(
447
+ self,
448
+ input_embeds,
449
+ input_states,
450
+ freqs_cis,
451
+ block_idx,
452
+ mask,
453
+ past_key_values: Optional[Cache] = None,
454
+ num_steps: Optional[torch.Tensor] = None,
455
+ attn_maps: dict = {},
456
+ ):
457
+ x = xk = self.initialize_state(input_embeds) if input_states is None else input_states.clone()
458
+ if num_steps is None:
459
+ num_steps_no_grad, num_steps_with_grad = self.randomized_iteration_sampler() # type: ignore
460
+ elif hasattr(num_steps, "__len__") and len(num_steps) > 1:
461
+ num_steps_no_grad, num_steps_with_grad = num_steps
462
+ else:
463
+ num_steps_no_grad, num_steps_with_grad = num_steps, torch.tensor(0)
464
+
465
+ with torch.no_grad():
466
+ # ultra annoying in ddp due to
467
+ # https://discuss.pytorch.org/t/does-distributeddataparallel-work-with-torch-no-grad-and-find-unused-parameters-false/122594
468
+ # for now running with find_unused_params=True enabled even though the graph structure is (technically) clear
469
+ # and all parameters are always used
470
+ for step in range(num_steps_no_grad):
471
+ xk = x
472
+ x, block_idx, attn_maps = self.core_block_forward(
473
+ xk, input_embeds, freqs_cis, mask, past_key_values, block_idx, attn_maps
474
+ )
475
+
476
+ for step in range(num_steps_with_grad):
477
+ xk = x
478
+ x, block_idx, attn_maps = self.core_block_forward(
479
+ xk, input_embeds, freqs_cis, mask, past_key_values, block_idx, attn_maps
480
+ )
481
+ return self.transformer.ln_f(x), num_steps_no_grad, num_steps_with_grad, xk.detach(), block_idx, attn_maps
482
+
483
+ def core_block_forward(
484
+ self,
485
+ x,
486
+ input_embeds,
487
+ freqs_cis,
488
+ mask,
489
+ past_key_values,
490
+ block_idx: Union[torch.Tensor, int],
491
+ attn_maps: dict = {},
492
+ ):
493
+ x = self.transformer.adapter(torch.cat([x, input_embeds], dim=-1))
494
+ for idx, block in enumerate(self.transformer.core_block, start=1):
495
+ x, attn_map = block(x, freqs_cis, block_idx + idx, mask, past_key_values, return_attn=len(attn_maps) > 0)
496
+ attn_maps[block_idx + idx] = attn_map
497
+ return x, block_idx + idx, attn_maps
498
+
499
+ @torch.no_grad()
500
+ def iterate_one_step(
501
+ self,
502
+ input_embeds,
503
+ input_states,
504
+ position_ids: Optional[torch.Tensor] = None,
505
+ cache_position: Optional[torch.Tensor] = None,
506
+ block_idx: Union[torch.Tensor, int] = 0,
507
+ attention_mask: Optional[Tensor] = None,
508
+ past_key_values: Optional[Cache] = None,
509
+ attn_maps: dict = {},
510
+ ):
511
+ if position_ids is None and cache_position is None:
512
+ freqs_cis = self.freqs_cis[:, : input_embeds.shape[1]]
513
+ elif position_ids is not None:
514
+ freqs_cis = self.freqs_cis.index_select(1, position_ids.squeeze())
515
+ elif cache_position is not None:
516
+ freqs_cis = self.freqs_cis[:, cache_position]
517
+ x, block_idx, attn_maps = self.core_block_forward(
518
+ input_states, input_embeds, freqs_cis, attention_mask, past_key_values, block_idx, attn_maps
519
+ )
520
+ return x, block_idx, attn_maps
521
+
522
+ def predict_from_latents(
523
+ self,
524
+ latents,
525
+ attention_mask: Optional[torch.Tensor] = None,
526
+ position_ids: Optional[torch.Tensor] = None,
527
+ cache_position: Optional[torch.Tensor] = None,
528
+ past_key_values: Optional[Cache] = None,
529
+ return_attn: bool = False,
530
+ attn_maps: dict = {},
531
+ ):
532
+ if position_ids is None and cache_position is None:
533
+ freqs_cis = self.freqs_cis[:, : latents.shape[1]]
534
+ elif position_ids is not None:
535
+ freqs_cis = self.freqs_cis.index_select(1, position_ids.squeeze())
536
+ elif cache_position is not None:
537
+ freqs_cis = self.freqs_cis[:, cache_position]
538
+ x = self.transformer.ln_f(latents)
539
+ # Coda layers
540
+ for block_idx, block in enumerate(self.transformer.coda, start=1):
541
+ x, attn_map = block(x, freqs_cis, -block_idx, attention_mask, past_key_values)
542
+ attn_maps[block_idx] = attn_map
543
+ x = self.transformer.ln_f(x)
544
+
545
+ logits = self.lm_head(x).float()
546
+
547
+ return CausalLMOutputRecurrentLatents(
548
+ loss=torch.as_tensor(0.0),
549
+ log_ppl=torch.as_tensor(0.0),
550
+ logits=logits,
551
+ past_key_values=past_key_values,
552
+ attention_maps=attn_maps if len(attn_maps) > 0 else None,
553
+ )
554
+
555
+ def embed_inputs(
556
+ self,
557
+ input_ids: torch.Tensor,
558
+ attention_mask: Optional[torch.Tensor] = None,
559
+ position_ids: Optional[torch.Tensor] = None,
560
+ past_key_values: Optional[Cache] = None,
561
+ use_cache: bool = False,
562
+ cache_position: Optional[torch.Tensor] = None,
563
+ return_attn: bool = False,
564
+ **kwargs,
565
+ ) -> tuple[torch.Tensor, int, dict[int, Tensor]]:
566
+ # Support multiple position formats:
567
+ if position_ids is None and cache_position is None:
568
+ freqs_cis = self.freqs_cis[:, : input_ids.shape[1]]
569
+ elif position_ids is not None:
570
+ freqs_cis = self.freqs_cis.index_select(1, position_ids.squeeze())
571
+ elif cache_position is not None:
572
+ freqs_cis = self.freqs_cis[:, cache_position]
573
+
574
+ input_embeds = self.transformer.wte(input_ids)
575
+
576
+ if self.emb_scale != 1:
577
+ input_embeds = input_embeds * self.emb_scale # type: ignore
578
+
579
+ if use_cache and past_key_values is None:
580
+ past_key_values = HuginnDynamicCache()
581
+
582
+ # Non-recurrent prelude
583
+ attn_maps = {}
584
+ for block_idx, block in enumerate(self.transformer.prelude):
585
+ input_embeds, attn_maps = block(
586
+ input_embeds, freqs_cis, block_idx, attention_mask, past_key_values, return_attn
587
+ )
588
+ return input_embeds, block_idx, attn_maps
589
+
590
+ @torch._dynamo.disable(recursive=False) # type: ignore
591
+ def randomized_iteration_sampler(self) -> tuple[torch.Tensor, torch.Tensor]:
592
+ """Outputs are long tensors so that they can be passed through compiled functions"""
593
+ t = max(self.config.mean_recurrence - self.config.mean_backprop_depth, 0)
594
+ s = self.config.mean_backprop_depth
595
+ if self.training:
596
+ sigma = 0.5
597
+ mu = math.log(t + s) - (sigma**2 / 2)
598
+ rate = torch.zeros((1,)).log_normal_(mean=mu, std=sigma)
599
+ p = torch.poisson(torch.tensor([rate], dtype=torch.float)) + 1
600
+ n = torch.clamp(p - s, min=0)
601
+ k = torch.as_tensor(torch.minimum(torch.as_tensor(s), p))
602
+ else:
603
+ n, k = torch.as_tensor(self.config.mean_recurrence), torch.as_tensor(0)
604
+
605
+ return n.to(dtype=torch.long), k.to(dtype=torch.long)
606
+
607
+ def initialize_state(self, input_embeds, deterministic: bool = False):
608
+ x = torch.randn_like(input_embeds)
609
+ std = self.config.init_values["std"]
610
+ torch.nn.init.trunc_normal_(x, mean=0.0, std=std, a=-3 * std, b=3 * std)
611
+ if self.emb_scale != 1:
612
+ x = x * self.emb_scale
613
+ return x if not deterministic else x.zero_()
614
+
615
+ def prepare_inputs_for_generation(
616
+ self,
617
+ input_ids: torch.LongTensor,
618
+ past_key_values: Optional[Cache] = None,
619
+ attention_mask: Optional[torch.LongTensor] = None,
620
+ inputs_embeds: Optional[torch.FloatTensor] = None,
621
+ cache_position: Optional[torch.LongTensor] = None,
622
+ **kwargs,
623
+ ):
624
+ model_inputs = {}
625
+ model_inputs["cache_position"] = cache_position
626
+ current_input_length = input_ids.shape[1]
627
+ if past_key_values is not None:
628
+ if type(past_key_values) == DynamicCache:
629
+ # Need to use custom cache, detect and replace HF dynamic cache if generate injects it
630
+ assert past_key_values.get_seq_length() == 0
631
+ past_key_values = HuginnDynamicCache()
632
+ model_inputs["past_key_values"] = past_key_values if kwargs["use_cache"] else None
633
+ input_ids = input_ids[:, cache_position] # type: ignore
634
+ model_inputs["input_ids"] = input_ids.clone(memory_format=torch.contiguous_format)
635
+
636
+ if cache_position is None:
637
+ position_ids = torch.arange(current_input_length)[None, :].to(input_ids.device)
638
+ model_inputs["position_ids"] = position_ids[:, -current_input_length:].clone(
639
+ memory_format=torch.contiguous_format
640
+ ) # some form of position_ids is a critical argument for the model to correctly apply rope!
641
+
642
+ # forward all other entries
643
+ for key, value in kwargs.items():
644
+ if key not in model_inputs:
645
+ model_inputs[key] = value
646
+ return model_inputs
647
+
648
+ @torch.no_grad()
649
+ def generate_minimal(
650
+ self,
651
+ input_ids: torch.LongTensor,
652
+ generation_config: Optional[GenerationConfig] = None, # type: ignore
653
+ tokenizer=None,
654
+ streamer=None,
655
+ continuous_compute=False, # warm-start state / continuous CoT
656
+ cache_kwargs: dict = {},
657
+ **model_kwargs,
658
+ ) -> Union[torch.Tensor, dict[str, Any]]:
659
+ """Minimal single-sequence generation. Template for more complicated generate tasks"""
660
+ # Setup
661
+ if generation_config is None:
662
+ generation_config: GenerationConfig = self.generation_config # type: ignore
663
+ model_kwargs["past_key_values"] = HuginnDynamicCache(**cache_kwargs)
664
+ model_kwargs["use_cache"] = True
665
+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
666
+ stop_tokens = self._get_stops(generation_config, tokenizer).to(input_ids.device)
667
+ if continuous_compute:
668
+ embedded_inputs, _, _ = self.embed_inputs(input_ids)
669
+ model_kwargs["input_states"] = self.initialize_state(embedded_inputs)
670
+ # Generate tokens
671
+ for _ in range(generation_config.max_length - input_ids.shape[1]):
672
+ # Forward pass
673
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
674
+ outputs = self(**model_inputs)
675
+ next_token_logits = outputs.logits[0, -1, :]
676
+ if continuous_compute:
677
+ current_last_latent = outputs.latent_states[:, -1:, :]
678
+
679
+ # Sample or select next token
680
+ if generation_config.do_sample:
681
+ if generation_config.temperature:
682
+ next_token_logits = next_token_logits / generation_config.temperature
683
+
684
+ probs = F.softmax(next_token_logits, dim=-1)
685
+
686
+ # Apply top_k
687
+ if generation_config.top_k:
688
+ top_k_probs, _ = torch.topk(probs, generation_config.top_k)
689
+ probs[probs < top_k_probs[-1]] = 0
690
+ # Apply top_p
691
+ if generation_config.top_p:
692
+ sorted_probs = torch.sort(probs, descending=True)[0]
693
+ cumsum = torch.cumsum(sorted_probs, dim=-1)
694
+ probs[cumsum > generation_config.top_p] = 0
695
+ # Apply min_p
696
+ if generation_config.min_p:
697
+ probs[probs < generation_config.min_p * probs.max()] = 0
698
+
699
+ probs = probs / probs.sum()
700
+ next_token = torch.multinomial(probs, num_samples=1)
701
+ else:
702
+ next_token = torch.argmax(next_token_logits, dim=-1, keepdim=True)
703
+
704
+ input_ids = torch.cat([input_ids, next_token[None, :]], dim=-1) # type: ignore
705
+
706
+ if streamer:
707
+ streamer.put(next_token.cpu())
708
+
709
+ # Update model kwargs
710
+ model_kwargs = self._update_model_kwargs_for_generation(outputs, model_kwargs)
711
+ if continuous_compute:
712
+ model_kwargs["input_states"] = current_last_latent
713
+
714
+ # Check if we hit a stop token
715
+ if stop_tokens is not None and next_token in stop_tokens:
716
+ break
717
+
718
+ if streamer:
719
+ streamer.end()
720
+
721
+ if generation_config.return_dict_in_generate:
722
+ return GenerateDecoderOnlyOutput(
723
+ sequences=input_ids,
724
+ scores=None,
725
+ logits=None,
726
+ attentions=None,
727
+ hidden_states=None,
728
+ past_key_values=model_kwargs.get("past_key_values"),
729
+ )
730
+ return input_ids
731
+
732
+ @torch.no_grad()
733
+ def generate_with_adaptive_compute(
734
+ self,
735
+ input_ids: torch.LongTensor,
736
+ generation_config: Optional[GenerationConfig] = None, # type: ignore
737
+ tokenizer=None,
738
+ streamer=None,
739
+ continuous_compute=False, # warm-start state / continuous CoT
740
+ latent_dampening=False,
741
+ criterion="entropy-diff",
742
+ exit_threshold: Union[str, float, int] = "auto",
743
+ cache_kwargs: dict = {},
744
+ **model_kwargs,
745
+ ) -> Union[torch.Tensor, GenerateDecoderOnlyOutput]:
746
+ """Minimal single-sequence generation. Template for more complicated generate tasks"""
747
+ # Setup
748
+ if generation_config is None:
749
+ generation_config: GenerationConfig = self.generation_config # type: ignore
750
+ model_kwargs["past_key_values"] = HuginnDynamicCache(**cache_kwargs)
751
+ model_kwargs["use_cache"] = True
752
+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
753
+ stop_tokens = self._get_stops(generation_config, tokenizer).to(input_ids.device)
754
+ if continuous_compute:
755
+ embedded_inputs, _, _ = self.embed_inputs(input_ids)
756
+ current_last_latent = self.initialize_state(embedded_inputs)
757
+ compute_steps = []
758
+
759
+ # Generate tokens
760
+ for step in range(generation_config.max_length - input_ids.shape[1]):
761
+ # Adaptive compute forward
762
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
763
+ aux_inputs = {
764
+ k: model_inputs[k] for k in ["cache_position", "past_key_values", "attention_mask"] if k in model_inputs
765
+ }
766
+ embedded_inputs, block_idx, _ = self.embed_inputs(model_inputs["input_ids"], **aux_inputs)
767
+ if not continuous_compute:
768
+ current_latents = self.initialize_state(embedded_inputs, deterministic=False)
769
+ else:
770
+ current_latents = current_last_latent
771
+
772
+ # Prep criterions:
773
+ if criterion == "entropy-diff":
774
+ entropy = torch.tensor(100.0, device=input_ids.device)
775
+ exit_threshold = 1e-3 if exit_threshold == "auto" else float(exit_threshold)
776
+ elif criterion in ["latent-diff", "none"]:
777
+ exit_threshold = 0.03 if exit_threshold == "auto" else float(exit_threshold)
778
+ elif "kl" in criterion:
779
+ V = self.config.padded_vocab_size
780
+ log_probs = (1 / V * torch.ones(V, device=input_ids.device)).log()
781
+ if criterion == "minp-kl":
782
+ exit_threshold = 1e-6 if exit_threshold == "auto" else float(exit_threshold)
783
+ else:
784
+ exit_threshold = 5e-4 if exit_threshold == "auto" else float(exit_threshold)
785
+ elif criterion == "argmax-stability":
786
+ stable_for_n_steps = 0
787
+ current_argmax = torch.tensor(-1, dtype=torch.long, device=input_ids.device)
788
+ exit_threshold = 5 if exit_threshold == "auto" else int(exit_threshold)
789
+ else:
790
+ raise ValueError("Invalid adaptive compute strategy.")
791
+
792
+ all_latents = []
793
+ exit_values = []
794
+ for compute_step in range(model_inputs["num_steps"]):
795
+ prev_latents = current_latents.clone()
796
+ current_latents, block_idx, _ = self.iterate_one_step(
797
+ embedded_inputs, current_latents, block_idx=block_idx, **aux_inputs
798
+ )
799
+ all_latents.append(current_latents if latent_dampening else None)
800
+ if step > 0: # do not exit in prefill:
801
+ if criterion == "entropy-diff":
802
+ prev_entropy = entropy.clone()
803
+ outputs = self.predict_from_latents(current_latents, **aux_inputs)
804
+ probs = F.softmax(outputs.logits[:, -1, :], dim=-1) # type: ignore
805
+ entropy = -torch.sum(probs * torch.log(probs + 1e-10), dim=-1).mean()
806
+ entropy_diff = (entropy - prev_entropy).abs()
807
+ exit_values.append(entropy_diff.item())
808
+ if entropy_diff < exit_threshold:
809
+ break
810
+ elif criterion == "latent-diff":
811
+ norm_diff = (prev_latents - current_latents).norm() / current_latents.norm()
812
+ exit_values.append(norm_diff.item())
813
+ if norm_diff < exit_threshold:
814
+ break
815
+ elif criterion == "kl":
816
+ prev_log_probs = log_probs.clone()
817
+ outputs = self.predict_from_latents(current_latents, **aux_inputs)
818
+ log_probs = F.log_softmax(outputs.logits[:, -1, :], dim=-1) # type: ignore
819
+ kl = F.kl_div(log_probs, prev_log_probs, reduction="none", log_target=True).sum(dim=-1)
820
+ exit_values.append(kl.item())
821
+ if kl < exit_threshold:
822
+ break
823
+ elif criterion == "minp-kl":
824
+ prev_log_probs = log_probs.clone()
825
+ outputs = self.predict_from_latents(current_latents, **aux_inputs)
826
+ probs = F.softmax(outputs.logits[:, -1, :], dim=-1) # type: ignore
827
+ probs[probs < 0.1 * probs.max()] = 1 / V
828
+ probs = probs / probs.sum()
829
+ log_probs = probs.log()
830
+ kl = F.kl_div(log_probs, prev_log_probs, reduction="none", log_target=True).sum(dim=-1)
831
+ exit_values.append(kl.item())
832
+ if kl < exit_threshold:
833
+ break
834
+ elif criterion == "argmax-stability":
835
+ prev_argmax = current_argmax.clone()
836
+ outputs = self.predict_from_latents(current_latents, **aux_inputs)
837
+ current_argmax = outputs.logits[0, -1, :].argmax(dim=-1) # type: ignore
838
+ if current_argmax == prev_argmax:
839
+ stable_for_n_steps += 1
840
+ else:
841
+ stable_for_n_steps = 0
842
+ exit_values.append(stable_for_n_steps)
843
+ if stable_for_n_steps >= exit_threshold:
844
+ break
845
+ elif criterion == "none":
846
+ pass
847
+
848
+ else:
849
+ if not latent_dampening:
850
+ outputs = self.predict_from_latents(current_latents, **aux_inputs)
851
+ else:
852
+ dampened_latents = torch.sum(torch.cat(all_latents, dim=0), dim=0, keepdim=True)
853
+ outputs = self.predict_from_latents(dampened_latents, **aux_inputs)
854
+ compute_steps.append([compute_step + 1, exit_values])
855
+
856
+ next_token_logits = outputs.logits[0, -1, :] # type: ignore
857
+ if continuous_compute: # Save last latent
858
+ current_last_latent = current_latents[:, -1:, :]
859
+
860
+ # Sample or select next token
861
+ if generation_config.do_sample:
862
+ if generation_config.temperature:
863
+ next_token_logits = next_token_logits / generation_config.temperature
864
+
865
+ probs = F.softmax(next_token_logits, dim=-1)
866
+ # Apply top_k
867
+ if generation_config.top_k:
868
+ top_k_probs, _ = torch.topk(probs, generation_config.top_k)
869
+ probs[probs < top_k_probs[-1]] = 0
870
+ # Apply top_p
871
+ if generation_config.top_p:
872
+ sorted_probs = torch.sort(probs, descending=True)[0]
873
+ cumsum = torch.cumsum(sorted_probs, dim=-1)
874
+ probs[cumsum > generation_config.top_p] = 0
875
+ # Apply min_p
876
+ if generation_config.min_p:
877
+ probs[probs < generation_config.min_p * probs.max()] = 0
878
+
879
+ probs = probs / probs.sum()
880
+ next_token = torch.multinomial(probs, num_samples=1)
881
+ else:
882
+ next_token = torch.argmax(next_token_logits, dim=-1, keepdim=True)
883
+
884
+ input_ids = torch.cat([input_ids, next_token[None, :]], dim=-1) # type: ignore
885
+
886
+ if streamer:
887
+ streamer.put(next_token.cpu())
888
+
889
+ # Update model kwargs
890
+ model_kwargs = self._update_model_kwargs_for_generation(outputs, model_kwargs)
891
+
892
+ # Check if we hit a stop token
893
+ if stop_tokens is not None and next_token in stop_tokens:
894
+ break
895
+
896
+ if streamer:
897
+ streamer.end()
898
+
899
+ if generation_config.return_dict_in_generate:
900
+ return GenerateDecoderOnlyOutput(
901
+ sequences=input_ids,
902
+ scores=compute_steps, # type: ignore
903
+ logits=None,
904
+ attentions=None,
905
+ hidden_states=None,
906
+ past_key_values=model_kwargs.get("past_key_values"),
907
+ )
908
+ return input_ids
909
+
910
+ def _get_stops(self, generation_config, tokenizer):
911
+ stop_tokens = set()
912
+ if generation_config.eos_token_id is not None:
913
+ stop_tokens.add(generation_config.eos_token_id)
914
+ if hasattr(generation_config, "stop_strings") and tokenizer and generation_config.stop_strings:
915
+ for s in generation_config.stop_strings:
916
+ token_id = tokenizer(s, add_special_tokens=False)["input_ids"][0]
917
+ stop_tokens.add(token_id)
918
+ return torch.tensor(list(stop_tokens))
919
+
920
+ def get_stats(self, logits, x, latent_states, xk, input_embeds, num_steps_no_grad, num_steps_with_grad):
921
+ probs = torch.softmax(logits.float(), dim=-1)
922
+ prob_entropy = torch.where(probs > 0, -probs * probs.log(), 0).sum(dim=-1)
923
+ residual_diff = (x - latent_states).norm(dim=-1)
924
+ rel_residual = residual_diff / latent_states.norm(dim=-1)
925
+ stats = {
926
+ "entropy": prob_entropy,
927
+ "residual_diff": residual_diff,
928
+ "rel_residual": rel_residual,
929
+ "num_steps_no_grad": num_steps_no_grad,
930
+ "num_steps_with_grad": num_steps_with_grad,
931
+ }
932
+ return stats
933
+
934
+
935
+ #################################### Utils #######################################################################
936
+ def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0, condense_ratio: int = 1):
937
+ with torch.autocast("cuda", enabled=False):
938
+ inv_freqs = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
939
+ t = torch.arange(end, dtype=torch.float32, device=inv_freqs.device) / condense_ratio
940
+ freqs = torch.outer(t, inv_freqs).float()
941
+ return torch.stack([torch.cos(freqs)[None, :, None, :], torch.sin(freqs)[None, :, None, :]], dim=4)
942
+ # equivalent to
943
+ # freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
944
+ # cache = torch.stack([freqs_cis.real, freqs_cis.imag], dim=-1)
945
+
946
+
947
+ def apply_rotary_emb_complex_like(q: Tensor, k: Tensor, freqs_cis: Tensor) -> tuple[Tensor, Tensor]:
948
+ with torch.autocast("cuda", enabled=False):
949
+ qk_r2 = torch.cat([q, k], dim=2).unflatten(dim=-1, sizes=(-1, 2)).float() # cast to float32 for smooth skin
950
+ rotated_qk_r2 = torch.stack(
951
+ [
952
+ qk_r2[..., 0] * freqs_cis[..., 0] - qk_r2[..., 1] * freqs_cis[..., 1],
953
+ qk_r2[..., 1] * freqs_cis[..., 0] + qk_r2[..., 0] * freqs_cis[..., 1],
954
+ ],
955
+ -1,
956
+ ).flatten(3)
957
+ rotated_qk = rotated_qk_r2
958
+ return torch.split(rotated_qk.type_as(q), q.shape[2], dim=2) # type: ignore
959
+
960
+
961
+ #################################### HF registration ############################################################
962
+
963
+ from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
964
+
965
+ # New
966
+ RavenConfig.register_for_auto_class()
967
+
968
+ RavenForCausalLM.register_for_auto_class("AutoModel")
969
+ RavenForCausalLM.register_for_auto_class("AutoModelForCausalLM")
970
+
971
+ # Old?
972
+ AutoConfig.register("huginn_raven", RavenConfig)
973
+ AutoModel.register(RavenConfig, RavenForCausalLM)
974
+ AutoModelForCausalLM.register(RavenConfig, RavenForCausalLM)