Upload RavenForCausalLM
Browse files- README.md +199 -0
- config.json +53 -0
- generation_config.json +7 -0
- model-00001-of-00004.safetensors +3 -0
- model-00002-of-00004.safetensors +3 -0
- model-00003-of-00004.safetensors +3 -0
- model-00004-of-00004.safetensors +3 -0
- model.safetensors.index.json +84 -0
- raven_config_minimal.py +96 -0
- raven_modeling_minimal.py +512 -0
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,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"bos_token_id": 65504,
|
| 15 |
+
"effective_expected_depth": 132,
|
| 16 |
+
"eos_token_id": 65505,
|
| 17 |
+
"head_dim": 96,
|
| 18 |
+
"init_orthogonal": false,
|
| 19 |
+
"init_strategy": "takase",
|
| 20 |
+
"init_values": {
|
| 21 |
+
"embed_scale": 72.6636084983398,
|
| 22 |
+
"embedding": 0.008703882797784892,
|
| 23 |
+
"out_proj": 0.0005356869554443541,
|
| 24 |
+
"std": 0.008703882797784892
|
| 25 |
+
},
|
| 26 |
+
"injection_type": "linear",
|
| 27 |
+
"intermediate_size": 17920,
|
| 28 |
+
"mean_backprop_depth": 8,
|
| 29 |
+
"mean_recurrence": 32,
|
| 30 |
+
"mlp_class_name": "GatedMLP",
|
| 31 |
+
"model_type": "huginn_raven",
|
| 32 |
+
"n_embd": 5280,
|
| 33 |
+
"n_heads": 55,
|
| 34 |
+
"n_layers": 8,
|
| 35 |
+
"n_layers_in_coda": 2,
|
| 36 |
+
"n_layers_in_prelude": 2,
|
| 37 |
+
"n_layers_in_recurrent_block": 4,
|
| 38 |
+
"nonlin_name": "SiLU",
|
| 39 |
+
"norm_class_name": "RMSNorm_llama",
|
| 40 |
+
"norm_eps": 1e-06,
|
| 41 |
+
"num_key_value_heads": 55,
|
| 42 |
+
"pad_token_id": 65509,
|
| 43 |
+
"padded_vocab_size": 65536,
|
| 44 |
+
"padding_multiple": 4096,
|
| 45 |
+
"qk_bias": true,
|
| 46 |
+
"rope_base": 50000,
|
| 47 |
+
"sampling_scheme": "poisson-lognormal-filling",
|
| 48 |
+
"state_init": "like-init",
|
| 49 |
+
"tie_embeddings": true,
|
| 50 |
+
"torch_dtype": "float32",
|
| 51 |
+
"transformers_version": "4.44.2",
|
| 52 |
+
"vocab_size": 65536
|
| 53 |
+
}
|
generation_config.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 65504,
|
| 4 |
+
"eos_token_id": 65505,
|
| 5 |
+
"pad_token_id": 65509,
|
| 6 |
+
"transformers_version": "4.44.2"
|
| 7 |
+
}
|
model-00001-of-00004.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5b461584b74249e87eabec34b59a13e188791dd8a7ccf2c7be95bb7fa8383e43
|
| 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:44bac332b204abb687b2820eb0fadcb5795fdb0cfc06b3b6f2ac5241eec5c591
|
| 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:07160dce9da01918d0b0bf2159ffe11d007e1fbe661d687ad4a7b0e65bde4e84
|
| 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:40ce4f159938857dbbfa1020962045e1b96303ff902cfa76051ce54d2d51dea4
|
| 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,512 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 9 |
+
|
| 10 |
+
from .raven_config_minimal import RavenConfig
|
| 11 |
+
from transformers.cache_utils import Cache, DynamicCache
|
| 12 |
+
|
| 13 |
+
###################### Huggingface Glue code I ##################################################################
|
| 14 |
+
from transformers import PreTrainedModel
|
| 15 |
+
from transformers.utils import ModelOutput
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class RavenPreTrainedModel(PreTrainedModel):
|
| 19 |
+
config_class = RavenConfig
|
| 20 |
+
base_model_prefix = "model"
|
| 21 |
+
supports_gradient_checkpointing = True
|
| 22 |
+
_no_split_modules = ["SandwichBlock"]
|
| 23 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 24 |
+
_supports_flash_attn_2 = True
|
| 25 |
+
_supports_sdpa = True
|
| 26 |
+
_supports_cache_class = True
|
| 27 |
+
_supports_quantized_cache = False
|
| 28 |
+
_supports_static_cache = False
|
| 29 |
+
|
| 30 |
+
def _init_weights(self, module):
|
| 31 |
+
print("Random Initialization not implemented.")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@dataclass
|
| 35 |
+
class CausalLMOutputRecurrentLatents(ModelOutput):
|
| 36 |
+
loss: Optional[torch.Tensor] = None
|
| 37 |
+
log_ppl: Optional[torch.Tensor] = None
|
| 38 |
+
logits: Optional[torch.Tensor] = None
|
| 39 |
+
past_key_values: Optional[Cache] = None
|
| 40 |
+
latent_states: Optional[torch.Tensor] = None
|
| 41 |
+
hidden_states: Optional[torch.Tensor] = None
|
| 42 |
+
attention_maps: Optional[tuple[torch.Tensor, ...]] = None
|
| 43 |
+
stats: Optional[dict] = None
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
###################### Minimal implementation from here ############################################################
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class RMSNorm(torch.nn.Module):
|
| 50 |
+
"""Saner dtype handling and slightly better for fusion"""
|
| 51 |
+
|
| 52 |
+
def __init__(self, dim: int, eps: float = 1e-6):
|
| 53 |
+
super().__init__()
|
| 54 |
+
self.eps = eps
|
| 55 |
+
self.weight = torch.nn.Parameter(torch.ones(dim))
|
| 56 |
+
|
| 57 |
+
def _norm(self, x):
|
| 58 |
+
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 59 |
+
|
| 60 |
+
def forward(self, x):
|
| 61 |
+
with torch.autocast(enabled=False, device_type=x.device.type):
|
| 62 |
+
return self._norm(x.float()).type_as(x) * self.weight
|
| 63 |
+
|
| 64 |
+
def reset_parameters(self) -> None:
|
| 65 |
+
torch.nn.init.ones_(self.weight)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class HuginnDynamicCache(DynamicCache):
|
| 69 |
+
def __init__(self) -> None:
|
| 70 |
+
super().__init__()
|
| 71 |
+
self._seen_tokens = 0
|
| 72 |
+
self.key_cache: dict[int, dict[int, torch.Tensor]] = {}
|
| 73 |
+
self.value_cache: dict[int, dict[int, torch.Tensor]] = {}
|
| 74 |
+
# structure: cache[index_of_layer_or_recurrent_step][index_in_sequence]
|
| 75 |
+
# the cache is held uncoalesced because certain recurrent steps may be missing for some sequence ids if using
|
| 76 |
+
# per-token adaptive compute. In those cases, the "lookup_strategy" determines how to proceed
|
| 77 |
+
# Also, It is critical that the head indices do not overlap with the recurrent iteration indices
|
| 78 |
+
|
| 79 |
+
def update(
|
| 80 |
+
self,
|
| 81 |
+
key_states: torch.Tensor,
|
| 82 |
+
value_states: torch.Tensor,
|
| 83 |
+
step_idx: int,
|
| 84 |
+
lookup_strategy: str = "latest",
|
| 85 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 86 |
+
# Init
|
| 87 |
+
if step_idx not in self.key_cache:
|
| 88 |
+
self.key_cache[step_idx] = {}
|
| 89 |
+
self.value_cache[step_idx] = {}
|
| 90 |
+
# Update the number of seen tokens, we assume that step_idx=0 (first prelude) is always hit
|
| 91 |
+
if step_idx == 0:
|
| 92 |
+
self._seen_tokens += key_states.shape[-2]
|
| 93 |
+
# Add entries to cache
|
| 94 |
+
for idx, entry in enumerate(key_states.unbind(dim=-2)):
|
| 95 |
+
assert self._seen_tokens - key_states.shape[-2] + idx not in self.key_cache[step_idx]
|
| 96 |
+
self.key_cache[step_idx][self._seen_tokens - key_states.shape[-2] + idx] = entry
|
| 97 |
+
for idx, entry in enumerate(value_states.unbind(dim=-2)):
|
| 98 |
+
self.value_cache[step_idx][self._seen_tokens - value_states.shape[-2] + idx] = entry
|
| 99 |
+
|
| 100 |
+
# Materialize past state based on lookup strategy:
|
| 101 |
+
if len(self.key_cache[step_idx]) == self._seen_tokens:
|
| 102 |
+
# All entries are present, materialize cache as normal
|
| 103 |
+
return (
|
| 104 |
+
torch.stack(list(self.key_cache[step_idx].values()), dim=-2),
|
| 105 |
+
torch.stack(list(self.value_cache[step_idx].values()), dim=-2),
|
| 106 |
+
)
|
| 107 |
+
else: # some entries where not previously computed
|
| 108 |
+
if lookup_strategy == "latest":
|
| 109 |
+
latest_keys = []
|
| 110 |
+
latest_values = []
|
| 111 |
+
for token_pos in range(self._seen_tokens):
|
| 112 |
+
# Find the latest step that has this token position
|
| 113 |
+
max_step = max((s for s in range(step_idx + 1) if token_pos in self.key_cache[s]), default=None)
|
| 114 |
+
if max_step is None:
|
| 115 |
+
raise ValueError(f"No cache entry found for token position {token_pos}")
|
| 116 |
+
latest_keys.append(self.key_cache[max_step][token_pos])
|
| 117 |
+
latest_values.append(self.value_cache[max_step][token_pos])
|
| 118 |
+
return torch.stack(latest_keys, dim=-2), torch.stack(latest_values, dim=-2)
|
| 119 |
+
elif lookup_strategy == "skip":
|
| 120 |
+
existing_keys = []
|
| 121 |
+
existing_values = []
|
| 122 |
+
for token_pos in range(self._seen_tokens):
|
| 123 |
+
if token_pos in self.key_cache[step_idx]:
|
| 124 |
+
existing_keys.append(self.key_cache[step_idx][token_pos])
|
| 125 |
+
existing_values.append(self.value_cache[step_idx][token_pos])
|
| 126 |
+
return torch.stack(existing_keys, dim=-2), torch.stack(existing_values, dim=-2)
|
| 127 |
+
elif lookup_strategy == "randomized": # sanity check
|
| 128 |
+
rand_keys = []
|
| 129 |
+
rand_values = []
|
| 130 |
+
for token_pos in range(self._seen_tokens):
|
| 131 |
+
# Find steps that have this token position
|
| 132 |
+
steps = [s for s in range(step_idx + 1) if token_pos in self.key_cache[s]]
|
| 133 |
+
rand_step = steps[torch.randint(len(steps), (1,))]
|
| 134 |
+
rand_keys.append(self.key_cache[rand_step][token_pos])
|
| 135 |
+
rand_values.append(self.value_cache[rand_step][token_pos])
|
| 136 |
+
return torch.stack(rand_keys, dim=-2), torch.stack(rand_values, dim=-2)
|
| 137 |
+
else:
|
| 138 |
+
raise ValueError(f"Unknown lookup strategy: {lookup_strategy}")
|
| 139 |
+
|
| 140 |
+
def reset(self) -> None:
|
| 141 |
+
"""Reset the cache state."""
|
| 142 |
+
self._seen_tokens = 0
|
| 143 |
+
self.key_cache.clear()
|
| 144 |
+
self.value_cache.clear()
|
| 145 |
+
|
| 146 |
+
def get_seq_length(self, step_idx: int = 0) -> int:
|
| 147 |
+
return self._seen_tokens
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class CausalSelfAttention(torch.nn.Module):
|
| 151 |
+
def __init__(self, config: RavenConfig) -> None:
|
| 152 |
+
super().__init__()
|
| 153 |
+
self.config = config
|
| 154 |
+
self.n_head = config.num_attention_heads
|
| 155 |
+
self.n_kv_heads = config.num_key_value_heads
|
| 156 |
+
self.head_dim = config.n_embd // self.n_head
|
| 157 |
+
|
| 158 |
+
shape = (self.n_head + 2 * self.n_kv_heads) * self.head_dim
|
| 159 |
+
self.chunks = [config.n_embd, self.n_kv_heads * self.head_dim, self.n_kv_heads * self.head_dim]
|
| 160 |
+
self.Wqkv = torch.nn.Linear(config.n_embd, shape, bias=False)
|
| 161 |
+
if config.qk_bias:
|
| 162 |
+
self.qk_bias = torch.nn.Parameter(torch.zeros(2, 1, self.n_head, self.head_dim))
|
| 163 |
+
self.proj = torch.nn.Linear(config.n_embd, config.n_embd, bias=False)
|
| 164 |
+
|
| 165 |
+
def forward(
|
| 166 |
+
self,
|
| 167 |
+
x: Tensor,
|
| 168 |
+
freqs_cis: Tensor,
|
| 169 |
+
step_idx: int,
|
| 170 |
+
mask: Optional[Tensor] = None,
|
| 171 |
+
past_key_values: Optional[Cache] = None,
|
| 172 |
+
) -> Tensor:
|
| 173 |
+
B, S, E = x.shape # batch size, sequence length, embedding dimensionality (n_embd)
|
| 174 |
+
q, k, v = self.Wqkv(x).split(self.chunks, dim=2)
|
| 175 |
+
q = q.view(B, S, self.n_head, self.head_dim)
|
| 176 |
+
k = k.view(B, S, self.n_kv_heads, self.head_dim)
|
| 177 |
+
v = v.view(B, S, self.n_kv_heads, self.head_dim)
|
| 178 |
+
# bias?
|
| 179 |
+
if self.config.qk_bias:
|
| 180 |
+
q_bias, k_bias = self.qk_bias.split(1, dim=0)
|
| 181 |
+
q, k = (q + q_bias).to(q.dtype), (k + k_bias).to(q.dtype)
|
| 182 |
+
# apply rotary
|
| 183 |
+
q, k = apply_rotary_emb_complex_like(q, k, freqs_cis=freqs_cis)
|
| 184 |
+
|
| 185 |
+
q = q.transpose(1, 2) # (B, nh, S, hs)
|
| 186 |
+
k = k.transpose(1, 2)
|
| 187 |
+
v = v.transpose(1, 2)
|
| 188 |
+
|
| 189 |
+
if past_key_values is not None:
|
| 190 |
+
k, v = past_key_values.update(k, v, step_idx)
|
| 191 |
+
|
| 192 |
+
y = torch.nn.functional.scaled_dot_product_attention(
|
| 193 |
+
q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=q.shape[2] > 1
|
| 194 |
+
)
|
| 195 |
+
y = y.transpose(1, 2).reshape(B, S, E).contiguous() # reshape is a view if possible (it mostly is)
|
| 196 |
+
return self.proj(y)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
class GatedMLP(torch.nn.Module):
|
| 200 |
+
def __init__(self, config: RavenConfig, in_features: int = 0) -> None:
|
| 201 |
+
super().__init__()
|
| 202 |
+
in_features = config.n_embd if in_features == 0 else in_features
|
| 203 |
+
self.fc = torch.nn.Linear(in_features, config.intermediate_size * 2, bias=False)
|
| 204 |
+
|
| 205 |
+
self.proj = torch.nn.Linear(config.intermediate_size, config.n_embd, bias=False)
|
| 206 |
+
self.nonlin = torch.nn.SiLU()
|
| 207 |
+
|
| 208 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 209 |
+
# modified to single FC layer to improve parallelism
|
| 210 |
+
x_fc_1, x_fc_2 = self.fc(x).chunk(2, dim=-1)
|
| 211 |
+
x = self.nonlin(x_fc_1) * x_fc_2
|
| 212 |
+
return self.proj(x)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class SandwichBlock(torch.nn.Module):
|
| 216 |
+
expanded = False
|
| 217 |
+
|
| 218 |
+
def __init__(self, config: RavenConfig, layer_id: int) -> None:
|
| 219 |
+
super().__init__()
|
| 220 |
+
self.norm_1 = RMSNorm(config.n_embd, eps=config.norm_eps)
|
| 221 |
+
self.attn = CausalSelfAttention(config)
|
| 222 |
+
self.norm_2 = RMSNorm(config.n_embd, eps=config.norm_eps)
|
| 223 |
+
self.mlp = GatedMLP(config)
|
| 224 |
+
self.norm_3 = RMSNorm(config.n_embd, eps=config.norm_eps)
|
| 225 |
+
self.norm_4 = RMSNorm(config.n_embd, eps=config.norm_eps)
|
| 226 |
+
self.layer_id = layer_id
|
| 227 |
+
|
| 228 |
+
def forward(
|
| 229 |
+
self,
|
| 230 |
+
x: Tensor,
|
| 231 |
+
freqs_cis: Tensor,
|
| 232 |
+
step_idx: int,
|
| 233 |
+
mask: Optional[Tensor] = None,
|
| 234 |
+
past_key_values: Optional[Cache] = None,
|
| 235 |
+
) -> Tensor:
|
| 236 |
+
x = self.norm_2(self.attn(self.norm_1(x), freqs_cis, step_idx, mask, past_key_values) + x)
|
| 237 |
+
x = self.norm_4(self.mlp(self.norm_3(x)) + x)
|
| 238 |
+
return x
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
class RavenForCausalLM(RavenPreTrainedModel):
|
| 242 |
+
def __init__(
|
| 243 |
+
self,
|
| 244 |
+
config: RavenConfig,
|
| 245 |
+
) -> None:
|
| 246 |
+
super().__init__(config)
|
| 247 |
+
self.config = config
|
| 248 |
+
|
| 249 |
+
# Transformer layers
|
| 250 |
+
prelude = torch.nn.ModuleList(SandwichBlock(config, layer_id=i) for i in range(config.n_layers_in_prelude))
|
| 251 |
+
adapter = torch.nn.Linear(config.n_embd * 2, config.n_embd, bias=config.bias)
|
| 252 |
+
core_block = torch.nn.ModuleList(
|
| 253 |
+
SandwichBlock(config, layer_id=i + config.n_layers_in_prelude)
|
| 254 |
+
for i in range(config.n_layers_in_recurrent_block)
|
| 255 |
+
)
|
| 256 |
+
o = config.n_layers_in_prelude + config.n_layers_in_recurrent_block * config.mean_recurrence
|
| 257 |
+
coda = torch.nn.ModuleList(SandwichBlock(config, layer_id=i + o) for i in range(config.n_layers_in_coda))
|
| 258 |
+
|
| 259 |
+
self.transformer = torch.nn.ModuleDict(
|
| 260 |
+
dict(
|
| 261 |
+
wte=torch.nn.Embedding(config.padded_vocab_size, config.n_embd),
|
| 262 |
+
prelude=prelude,
|
| 263 |
+
adapter=adapter,
|
| 264 |
+
core_block=core_block,
|
| 265 |
+
coda=coda,
|
| 266 |
+
ln_f=RMSNorm(config.n_embd, eps=config.norm_eps), # used twice :>
|
| 267 |
+
)
|
| 268 |
+
)
|
| 269 |
+
self.emb_scale = config.init_values["embed_scale"]
|
| 270 |
+
# Head
|
| 271 |
+
self.lm_head = torch.nn.Linear(config.n_embd, config.padded_vocab_size, bias=False)
|
| 272 |
+
if self.config.tie_embeddings:
|
| 273 |
+
self.lm_head.weight = self.transformer.wte.weight
|
| 274 |
+
# rope
|
| 275 |
+
self.register_buffer("freqs_cis", self._precompute_freqs_cis(), persistent=True)
|
| 276 |
+
|
| 277 |
+
def _precompute_freqs_cis(self):
|
| 278 |
+
# can actually be a buffer now, and remains in fp32! (at least in the settings I tested)
|
| 279 |
+
freqs_cis = precompute_freqs_cis(
|
| 280 |
+
self.config.n_embd // self.config.num_attention_heads, self.config.block_size, self.config.rope_base, 1
|
| 281 |
+
)
|
| 282 |
+
return freqs_cis
|
| 283 |
+
|
| 284 |
+
def forward(
|
| 285 |
+
self,
|
| 286 |
+
input_ids: torch.Tensor,
|
| 287 |
+
input_embeds: Optional[torch.Tensor] = None,
|
| 288 |
+
input_states: Optional[torch.Tensor] = None,
|
| 289 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 290 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 291 |
+
labels: Optional[torch.Tensor] = None,
|
| 292 |
+
num_steps_pair: Optional[torch.Tensor] = None,
|
| 293 |
+
past_key_values: Optional[Cache] = None,
|
| 294 |
+
output_details: dict = {
|
| 295 |
+
"return_logits": True,
|
| 296 |
+
"return_latents": True,
|
| 297 |
+
"return_attention": False,
|
| 298 |
+
"return_head": False,
|
| 299 |
+
"return_stats": True,
|
| 300 |
+
},
|
| 301 |
+
use_cache: bool = False,
|
| 302 |
+
cache_position: Optional[torch.Tensor] = None,
|
| 303 |
+
) -> dict[str, Optional[torch.Tensor]]:
|
| 304 |
+
if position_ids is None and cache_position is None:
|
| 305 |
+
freqs_cis = self.freqs_cis[:, : input_ids.shape[1]]
|
| 306 |
+
elif position_ids is not None:
|
| 307 |
+
freqs_cis = self.freqs_cis.index_select(1, position_ids)
|
| 308 |
+
elif cache_position is not None: # support HF format
|
| 309 |
+
freqs_cis = self.freqs_cis[:, cache_position : cache_position + 1]
|
| 310 |
+
|
| 311 |
+
if input_embeds is None:
|
| 312 |
+
input_embeds = self.transformer.wte(input_ids)
|
| 313 |
+
|
| 314 |
+
if self.emb_scale != 1:
|
| 315 |
+
input_embeds = input_embeds * self.emb_scale # type: ignore
|
| 316 |
+
|
| 317 |
+
if use_cache and past_key_values is None:
|
| 318 |
+
past_key_values = HuginnDynamicCache()
|
| 319 |
+
|
| 320 |
+
# Non-recurrent prelude
|
| 321 |
+
for block_idx, block in enumerate(self.transformer.prelude):
|
| 322 |
+
input_embeds = block(input_embeds, freqs_cis, block_idx, attention_mask, past_key_values)
|
| 323 |
+
|
| 324 |
+
# Main recurrence
|
| 325 |
+
x, num_steps_no_grad, num_steps_with_grad, xk = self.iterate_forward(
|
| 326 |
+
input_embeds, # type: ignore
|
| 327 |
+
input_states,
|
| 328 |
+
freqs_cis,
|
| 329 |
+
block_idx,
|
| 330 |
+
attention_mask,
|
| 331 |
+
past_key_values,
|
| 332 |
+
num_steps_pair,
|
| 333 |
+
)
|
| 334 |
+
latent_states = x.clone().detach()
|
| 335 |
+
|
| 336 |
+
# Coda layers
|
| 337 |
+
for block_idx, block in enumerate(self.transformer.coda, start=1):
|
| 338 |
+
x = block(x, freqs_cis, -block_idx, attention_mask, past_key_values)
|
| 339 |
+
x = self.transformer.ln_f(x)
|
| 340 |
+
|
| 341 |
+
# Prediction head, assuming labels really are labels and not equal to input_ids
|
| 342 |
+
if labels is not None:
|
| 343 |
+
logits = self.lm_head(x).float()
|
| 344 |
+
loss = torch.nn.functional.cross_entropy(logits.view(-1, logits.shape[-1]), labels.view(-1))
|
| 345 |
+
log_ppl = loss.clone().detach()
|
| 346 |
+
else:
|
| 347 |
+
logits = self.lm_head(x).float()
|
| 348 |
+
loss, log_ppl = torch.as_tensor(0.0), torch.as_tensor(0.0)
|
| 349 |
+
|
| 350 |
+
return CausalLMOutputRecurrentLatents(
|
| 351 |
+
loss=loss,
|
| 352 |
+
log_ppl=log_ppl,
|
| 353 |
+
logits=logits if output_details["return_logits"] else None,
|
| 354 |
+
past_key_values=past_key_values,
|
| 355 |
+
hidden_states=x if output_details["return_head"] else None,
|
| 356 |
+
latent_states=latent_states if output_details["return_latents"] else None,
|
| 357 |
+
attention_maps=ValueError() if output_details["return_attention"] else None, # type: ignore
|
| 358 |
+
stats=self.get_stats(logits, x, latent_states, xk, input_embeds, num_steps_no_grad, num_steps_with_grad)
|
| 359 |
+
if output_details["return_stats"]
|
| 360 |
+
else None,
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
@torch._dynamo.disable(recursive=False) # type: ignore
|
| 364 |
+
def iterate_forward(
|
| 365 |
+
self,
|
| 366 |
+
input_embeds,
|
| 367 |
+
input_states,
|
| 368 |
+
freqs_cis,
|
| 369 |
+
block_idx,
|
| 370 |
+
mask,
|
| 371 |
+
past_key_values: Optional[Cache] = None,
|
| 372 |
+
num_steps_pair: Optional[torch.Tensor] = None,
|
| 373 |
+
):
|
| 374 |
+
x = xk = self.initialize_state(input_embeds) if input_states is None else input_states.clone()
|
| 375 |
+
|
| 376 |
+
if num_steps_pair is None:
|
| 377 |
+
num_steps_no_grad, num_steps_with_grad = self.randomized_iteration_sampler() # type: ignore
|
| 378 |
+
elif len(num_steps_pair) > 1:
|
| 379 |
+
num_steps_no_grad, num_steps_with_grad = num_steps_pair
|
| 380 |
+
else:
|
| 381 |
+
num_steps_no_grad, num_steps_with_grad = num_steps_pair, torch.tensor(0)
|
| 382 |
+
|
| 383 |
+
with torch.no_grad():
|
| 384 |
+
# ultra annoying in ddp due to
|
| 385 |
+
# https://discuss.pytorch.org/t/does-distributeddataparallel-work-with-torch-no-grad-and-find-unused-parameters-false/122594
|
| 386 |
+
# for now running with find_unused_params=True enabled even though the graph structure is (technically) clear
|
| 387 |
+
# and all parameters are always used
|
| 388 |
+
for step in range(num_steps_no_grad):
|
| 389 |
+
xk = x
|
| 390 |
+
x, block_idx = self.core_block_forward(xk, input_embeds, freqs_cis, mask, past_key_values, block_idx)
|
| 391 |
+
|
| 392 |
+
for step in range(num_steps_with_grad):
|
| 393 |
+
xk = x
|
| 394 |
+
x, block_idx = self.core_block_forward(xk, input_embeds, freqs_cis, mask, past_key_values, block_idx)
|
| 395 |
+
return self.transformer.ln_f(x), num_steps_no_grad, num_steps_with_grad, xk.detach()
|
| 396 |
+
|
| 397 |
+
def core_block_forward(
|
| 398 |
+
self, x, input_embeds, freqs_cis, mask, past_key_values, block_idx: Union[torch.Tensor, int]
|
| 399 |
+
):
|
| 400 |
+
x = self.transformer.adapter(torch.cat([x, input_embeds], dim=-1))
|
| 401 |
+
for idx, block in enumerate(self.transformer.core_block, start=1):
|
| 402 |
+
x = block(x, freqs_cis, block_idx + idx, mask, past_key_values)
|
| 403 |
+
return x, block_idx + idx
|
| 404 |
+
|
| 405 |
+
@torch._dynamo.disable(recursive=False) # type: ignore
|
| 406 |
+
def randomized_iteration_sampler(self) -> tuple[torch.Tensor, torch.Tensor]:
|
| 407 |
+
"""Outputs are long tensors so that they can be passed through compiled functions"""
|
| 408 |
+
t = max(self.config.mean_recurrence - self.config.mean_backprop_depth, 0)
|
| 409 |
+
s = self.config.mean_backprop_depth
|
| 410 |
+
if self.training:
|
| 411 |
+
sigma = 0.5
|
| 412 |
+
mu = math.log(t + s) - (sigma**2 / 2)
|
| 413 |
+
rate = torch.zeros((1,)).log_normal_(mean=mu, std=sigma)
|
| 414 |
+
p = torch.poisson(torch.tensor([rate], dtype=torch.float)) + 1
|
| 415 |
+
n = torch.clamp(p - s, min=0)
|
| 416 |
+
k = torch.as_tensor(torch.minimum(torch.as_tensor(s), p))
|
| 417 |
+
else:
|
| 418 |
+
n, k = torch.as_tensor(self.config.mean_recurrence), torch.as_tensor(0)
|
| 419 |
+
|
| 420 |
+
return n.to(dtype=torch.long), k.to(dtype=torch.long)
|
| 421 |
+
|
| 422 |
+
def initialize_state(self, input_embeds):
|
| 423 |
+
x = torch.randn_like(input_embeds)
|
| 424 |
+
std = self.config.init_values["std"]
|
| 425 |
+
torch.nn.init.trunc_normal_(x, mean=0.0, std=std, a=-3 * std, b=3 * std)
|
| 426 |
+
if self.emb_scale != 1:
|
| 427 |
+
x = x * self.emb_scale
|
| 428 |
+
return x
|
| 429 |
+
|
| 430 |
+
def prepare_inputs_for_generation(
|
| 431 |
+
self,
|
| 432 |
+
input_ids: torch.LongTensor,
|
| 433 |
+
past_key_values: Optional[Cache] = None,
|
| 434 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 435 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 436 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 437 |
+
**kwargs,
|
| 438 |
+
):
|
| 439 |
+
model_inputs = {}
|
| 440 |
+
model_inputs["cache_position"] = cache_position
|
| 441 |
+
current_input_length = model_inputs["input_ids"].shape[1]
|
| 442 |
+
if past_key_values is not None:
|
| 443 |
+
model_inputs["past_key_values"] = past_key_values
|
| 444 |
+
input_ids = input_ids[:, cache_position] # type: ignore
|
| 445 |
+
model_inputs["input_ids"] = input_ids.clone(memory_format=torch.contiguous_format)
|
| 446 |
+
|
| 447 |
+
position_ids = torch.arange(current_input_length)[None, :]
|
| 448 |
+
model_inputs["positions_ids"] = position_ids[:, -current_input_length:].clone(
|
| 449 |
+
memory_format=torch.contiguous_format
|
| 450 |
+
) # positions_ids is a critical argument for the model to correctly apply rope!
|
| 451 |
+
|
| 452 |
+
# forward all other entries
|
| 453 |
+
for key, value in kwargs.items():
|
| 454 |
+
if key not in model_inputs:
|
| 455 |
+
model_inputs[key] = value
|
| 456 |
+
return model_inputs
|
| 457 |
+
|
| 458 |
+
def get_stats(self, logits, x, latent_states, xk, input_embeds, num_steps_no_grad, num_steps_with_grad):
|
| 459 |
+
probs = torch.softmax(logits.float(), dim=-1)
|
| 460 |
+
prob_entropy = torch.where(probs > 0, -probs * probs.log(), 0).sum(dim=-1)
|
| 461 |
+
residual_diff = (x - latent_states).norm(dim=-1)
|
| 462 |
+
rel_residual = residual_diff / latent_states.norm(dim=-1)
|
| 463 |
+
stats = {
|
| 464 |
+
"entropy": prob_entropy,
|
| 465 |
+
"residual_diff": residual_diff,
|
| 466 |
+
"rel_residual": rel_residual,
|
| 467 |
+
"num_steps_no_grad": num_steps_no_grad,
|
| 468 |
+
"num_steps_with_grad": num_steps_with_grad,
|
| 469 |
+
}
|
| 470 |
+
return stats
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
#################################### Utils #######################################################################
|
| 474 |
+
def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0, condense_ratio: int = 1):
|
| 475 |
+
with torch.autocast("cuda", enabled=False):
|
| 476 |
+
inv_freqs = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
|
| 477 |
+
t = torch.arange(end, dtype=torch.float32, device=inv_freqs.device) / condense_ratio
|
| 478 |
+
freqs = torch.outer(t, inv_freqs).float()
|
| 479 |
+
return torch.stack([torch.cos(freqs)[None, :, None, :], torch.sin(freqs)[None, :, None, :]], dim=4)
|
| 480 |
+
# equivalent to
|
| 481 |
+
# freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
|
| 482 |
+
# cache = torch.stack([freqs_cis.real, freqs_cis.imag], dim=-1)
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def apply_rotary_emb_complex_like(q: Tensor, k: Tensor, freqs_cis: Tensor) -> tuple[Tensor, Tensor]:
|
| 486 |
+
with torch.autocast("cuda", enabled=False):
|
| 487 |
+
qk_r2 = torch.cat([q, k], dim=2).unflatten(dim=-1, sizes=(-1, 2)).float() # cast to float32 for smooth skin
|
| 488 |
+
rotated_qk_r2 = torch.stack(
|
| 489 |
+
[
|
| 490 |
+
qk_r2[..., 0] * freqs_cis[..., 0] - qk_r2[..., 1] * freqs_cis[..., 1],
|
| 491 |
+
qk_r2[..., 1] * freqs_cis[..., 0] + qk_r2[..., 0] * freqs_cis[..., 1],
|
| 492 |
+
],
|
| 493 |
+
-1,
|
| 494 |
+
).flatten(3)
|
| 495 |
+
rotated_qk = rotated_qk_r2
|
| 496 |
+
return torch.split(rotated_qk.type_as(q), q.shape[2], dim=2) # type: ignore
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
#################################### HF registration ############################################################
|
| 500 |
+
|
| 501 |
+
from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
|
| 502 |
+
|
| 503 |
+
# New
|
| 504 |
+
RavenConfig.register_for_auto_class()
|
| 505 |
+
|
| 506 |
+
RavenForCausalLM.register_for_auto_class("AutoModel")
|
| 507 |
+
RavenForCausalLM.register_for_auto_class("AutoModelForCausalLM")
|
| 508 |
+
|
| 509 |
+
# Old?
|
| 510 |
+
AutoConfig.register("huginn_raven", RavenConfig)
|
| 511 |
+
AutoModel.register(RavenConfig, RavenForCausalLM)
|
| 512 |
+
AutoModelForCausalLM.register(RavenConfig, RavenForCausalLM)
|