Commit ·
9c4ec6d
0
Parent(s):
Revert to 7ed7003 and squash history
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +35 -0
- README.md +72 -0
- chat_template.jinja +4 -0
- checkpoint-1000/chat_template.jinja +4 -0
- checkpoint-1000/config.json +43 -0
- checkpoint-1000/configuration_surjo_exp.py +21 -0
- checkpoint-1000/generation_config.json +10 -0
- checkpoint-1000/model.safetensors +3 -0
- checkpoint-1000/modeling_surjo_exp.py +417 -0
- checkpoint-1000/optimizer.bin +3 -0
- checkpoint-1000/optimizer_1.bin +3 -0
- checkpoint-1000/random_states_0.pkl +3 -0
- checkpoint-1000/tokenizer.json +0 -0
- checkpoint-1000/tokenizer_config.json +85 -0
- checkpoint-10000/chat_template.jinja +4 -0
- checkpoint-10000/config.json +43 -0
- checkpoint-10000/configuration_surjo_exp.py +21 -0
- checkpoint-10000/generation_config.json +10 -0
- checkpoint-10000/model.safetensors +3 -0
- checkpoint-10000/modeling_surjo_exp.py +417 -0
- checkpoint-10000/optimizer.bin +3 -0
- checkpoint-10000/optimizer_1.bin +3 -0
- checkpoint-10000/random_states_0.pkl +3 -0
- checkpoint-10000/tokenizer.json +0 -0
- checkpoint-10000/tokenizer_config.json +85 -0
- checkpoint-11000/chat_template.jinja +4 -0
- checkpoint-11000/config.json +43 -0
- checkpoint-11000/configuration_surjo_exp.py +21 -0
- checkpoint-11000/generation_config.json +10 -0
- checkpoint-11000/model.safetensors +3 -0
- checkpoint-11000/modeling_surjo_exp.py +417 -0
- checkpoint-11000/optimizer.bin +3 -0
- checkpoint-11000/optimizer_1.bin +3 -0
- checkpoint-11000/random_states_0.pkl +3 -0
- checkpoint-11000/tokenizer.json +0 -0
- checkpoint-11000/tokenizer_config.json +85 -0
- checkpoint-12000/chat_template.jinja +4 -0
- checkpoint-12000/config.json +43 -0
- checkpoint-12000/configuration_surjo_exp.py +21 -0
- checkpoint-12000/generation_config.json +10 -0
- checkpoint-12000/model.safetensors +3 -0
- checkpoint-12000/modeling_surjo_exp.py +417 -0
- checkpoint-12000/optimizer.bin +3 -0
- checkpoint-12000/optimizer_1.bin +3 -0
- checkpoint-12000/random_states_0.pkl +3 -0
- checkpoint-12000/tokenizer.json +0 -0
- checkpoint-12000/tokenizer_config.json +85 -0
- checkpoint-13000/chat_template.jinja +4 -0
- checkpoint-13000/config.json +43 -0
- checkpoint-13000/configuration_surjo_exp.py +21 -0
.gitattributes
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
---
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
tags:
|
| 6 |
+
- text-generation
|
| 7 |
+
- causal-lm
|
| 8 |
+
- custom-architecture
|
| 9 |
+
- slm
|
| 10 |
+
- small-language-model
|
| 11 |
+
license: mit
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
# Flare (130M Parameters)
|
| 15 |
+
|
| 16 |
+
Flare is a highly efficient small language model developed by SurjoLabs, demonstrating that this custom XSA recurrent architecture is viable and can yield exceptional reasoning capabilities in tiny architectures.
|
| 17 |
+
|
| 18 |
+
## Methodology
|
| 19 |
+
|
| 20 |
+
Flare is built to prove that unique recurrent architectures can match or beat standard transformers even at small scales.
|
| 21 |
+
|
| 22 |
+
* **Custom Architecture:** Built on a Llama-variant framework but features **XSA Attention** (value-subtraction projection) and **Recurrent Layers**. By reusing weights across recurrent passes, the model achieves extended effective depth while carrying a reduced set of unique weights.
|
| 23 |
+
* **Optimized Tokenizer:** Uses a custom 32,768-vocabulary (2^15) English tokenizer. This power-of-two vocabulary optimizes tensor parallelism and compute alignment while providing strong compression rates across text, code, and math.
|
| 24 |
+
* **Extreme Overtraining:** Trained on **26.21 Billion tokens** (25,000 steps at 1,048,576 tokens per step), resulting in a ~1:200 parameter-to-token ratio. This forces the architecture to memorize syntax and knowledge far beyond Chinchilla-optimal limits.
|
| 25 |
+
* **Data Mixture:**
|
| 26 |
+
* 60% Finephrase (Synthetic FineWeb-Edu)
|
| 27 |
+
* 20% DCLM (Web text)
|
| 28 |
+
* 10% FineMath (Mathematics)
|
| 29 |
+
* 10% CornStack (Code)
|
| 30 |
+
* **Optimizer:** Utilizes a hybrid Muon (for 2D weight matrices) and AdamW (for embeddings/norms) optimizer setup for stable, rapid convergence.
|
| 31 |
+
|
| 32 |
+
## Benchmark Results (Open SLM Leaderboard)
|
| 33 |
+
|
| 34 |
+
Evaluated at checkpoint-24999.
|
| 35 |
+
|
| 36 |
+
| Benchmark | Score (acc_norm) |
|
| 37 |
+
| :--- | :--- |
|
| 38 |
+
| HellaSwag | 39.43% |
|
| 39 |
+
| ARC-Easy | 51.14% |
|
| 40 |
+
| ARC-Challenge | 26.88% |
|
| 41 |
+
| PIQA | 65.94% |
|
| 42 |
+
| ArithMark-3 | 39.20% |
|
| 43 |
+
| **Intelligence Index** | **22.50** |
|
| 44 |
+
|
| 45 |
+
We used the Language Model Evaluation Harness for HellaSwag, ARC-Easy, ARC-Challenge, and PIQA (0-shot).
|
| 46 |
+
We used the provided script for ArithMark-3.
|
| 47 |
+
|
| 48 |
+
## Usage
|
| 49 |
+
|
| 50 |
+
```python
|
| 51 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 52 |
+
import torch
|
| 53 |
+
|
| 54 |
+
model_id = "SurjoLabs/Flare"
|
| 55 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
| 56 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 57 |
+
model_id,
|
| 58 |
+
trust_remote_code=True,
|
| 59 |
+
torch_dtype=torch.bfloat16
|
| 60 |
+
).cuda()
|
| 61 |
+
|
| 62 |
+
prompt = "The capital of France is"
|
| 63 |
+
inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
|
| 64 |
+
outputs = model.generate(**inputs, max_new_tokens=20)
|
| 65 |
+
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
## Acknowledgement
|
| 69 |
+
We would like to thank [AxiomicLabs](https://huggingface.co/AxiomicLabs) for proving that XSA architecture is excellent for token efficiency.
|
| 70 |
+
|
| 71 |
+
## Limitations
|
| 72 |
+
This is an early test of the larger Surjo Project. The code is not very stable and we do not recommend using the modeling file without doing edits for training your own model.
|
chat_template.jinja
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{ bos_token }}{% for message in messages %}{{ '<|im_start|>' + message['role'] + '
|
| 2 |
+
' + message['content'] + '<|im_end|>
|
| 3 |
+
' }}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant
|
| 4 |
+
' }}{% endif %}
|
checkpoint-1000/chat_template.jinja
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{ bos_token }}{% for message in messages %}{{ '<|im_start|>' + message['role'] + '
|
| 2 |
+
' + message['content'] + '<|im_end|>
|
| 3 |
+
' }}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant
|
| 4 |
+
' }}{% endif %}
|
checkpoint-1000/config.json
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"SurjoExpForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"attention_bias": false,
|
| 6 |
+
"attention_dropout": 0.0,
|
| 7 |
+
"auto_map": {
|
| 8 |
+
"AutoConfig": "configuration_surjo_exp.SurjoExpConfig",
|
| 9 |
+
"AutoModelForCausalLM": "modeling_surjo_exp.SurjoExpForCausalLM"
|
| 10 |
+
},
|
| 11 |
+
"bos_token_id": 0,
|
| 12 |
+
"coda_layers": 16,
|
| 13 |
+
"dtype": "float32",
|
| 14 |
+
"eos_token_id": 2,
|
| 15 |
+
"gradient_checkpointing": false,
|
| 16 |
+
"head_dim": 72,
|
| 17 |
+
"hidden_act": "silu",
|
| 18 |
+
"hidden_size": 576,
|
| 19 |
+
"initializer_range": 0.02,
|
| 20 |
+
"intermediate_size": 1536,
|
| 21 |
+
"max_position_embeddings": 2048,
|
| 22 |
+
"mlp_bias": false,
|
| 23 |
+
"model_type": "surjo_exp",
|
| 24 |
+
"num_attention_heads": 8,
|
| 25 |
+
"num_hidden_layers": 32,
|
| 26 |
+
"num_key_value_heads": 2,
|
| 27 |
+
"pad_token_id": 1,
|
| 28 |
+
"prelude_layers": 4,
|
| 29 |
+
"pretraining_tp": 1,
|
| 30 |
+
"recurrent_layers": 12,
|
| 31 |
+
"rms_norm_eps": 1e-05,
|
| 32 |
+
"rope_parameters": {
|
| 33 |
+
"rope_theta": 10000.0,
|
| 34 |
+
"rope_type": "default"
|
| 35 |
+
},
|
| 36 |
+
"rope_theta": 10000.0,
|
| 37 |
+
"tie_word_embeddings": true,
|
| 38 |
+
"transformers_version": "5.15.0",
|
| 39 |
+
"use_cache": false,
|
| 40 |
+
"use_flash_attn": false,
|
| 41 |
+
"vocab_size": 32768,
|
| 42 |
+
"xsa_projection": true
|
| 43 |
+
}
|
checkpoint-1000/configuration_surjo_exp.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from transformers import LlamaConfig
|
| 3 |
+
|
| 4 |
+
class SurjoExpConfig(LlamaConfig):
|
| 5 |
+
model_type = "surjo_exp"
|
| 6 |
+
def __init__(self, *args, xsa_projection=True, rope_theta=10000.0, attention_bias=False,
|
| 7 |
+
prelude_layers=4, recurrent_layers=12, coda_layers=16,
|
| 8 |
+
gradient_checkpointing=True, use_flash_attn=True, **kwargs):
|
| 9 |
+
kwargs["num_hidden_layers"] = prelude_layers + recurrent_layers + coda_layers
|
| 10 |
+
kwargs.setdefault("use_cache", False)
|
| 11 |
+
super().__init__(*args, rope_theta=rope_theta, attention_bias=attention_bias, **kwargs)
|
| 12 |
+
self.xsa_projection = xsa_projection
|
| 13 |
+
self.rope_theta = rope_theta
|
| 14 |
+
self.attention_bias = attention_bias
|
| 15 |
+
self.prelude_layers = prelude_layers
|
| 16 |
+
self.recurrent_layers = recurrent_layers
|
| 17 |
+
self.coda_layers = coda_layers
|
| 18 |
+
self.gradient_checkpointing = gradient_checkpointing
|
| 19 |
+
self.use_flash_attn = use_flash_attn
|
| 20 |
+
if not hasattr(self, 'rope_parameters') or self.rope_parameters is None:
|
| 21 |
+
self.rope_parameters = {"rope_type": "default", "factor": 1.0, "rope_theta": rope_theta}
|
checkpoint-1000/generation_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 0,
|
| 4 |
+
"eos_token_id": 2,
|
| 5 |
+
"output_attentions": false,
|
| 6 |
+
"output_hidden_states": false,
|
| 7 |
+
"pad_token_id": 1,
|
| 8 |
+
"transformers_version": "5.15.0",
|
| 9 |
+
"use_cache": false
|
| 10 |
+
}
|
checkpoint-1000/model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:94945ebfb26ee1fc4b49f11ccab59fd5eefbefcebaf04163a243528d10477256
|
| 3 |
+
size 521611856
|
checkpoint-1000/modeling_surjo_exp.py
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import torch.utils.checkpoint
|
| 6 |
+
from transformers import LlamaConfig, LlamaModel, LlamaForCausalLM
|
| 7 |
+
from transformers.models.llama.modeling_llama import LlamaRMSNorm
|
| 8 |
+
from transformers.models.llama.modeling_llama import LlamaMLP
|
| 9 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 10 |
+
from transformers.models.llama.modeling_llama import LlamaRotaryEmbedding, apply_rotary_pos_emb
|
| 11 |
+
from transformers.cache_utils import DynamicCache
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
from .configuration_surjo_exp import SurjoExpConfig
|
| 15 |
+
except ImportError:
|
| 16 |
+
from configuration_surjo_exp import SurjoExpConfig
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
from flash_attn import flash_attn_varlen_func
|
| 20 |
+
FLASH_ATTN_AVAILABLE = True
|
| 21 |
+
except ImportError:
|
| 22 |
+
FLASH_ATTN_AVAILABLE = False
|
| 23 |
+
|
| 24 |
+
@torch._dynamo.disable()
|
| 25 |
+
def _flash_varlen(q, k, v, cu_seqlens, max_seqlen, dropout_p):
|
| 26 |
+
ms = int(max_seqlen.item()) if torch.is_tensor(max_seqlen) else int(max_seqlen)
|
| 27 |
+
return flash_attn_varlen_func(
|
| 28 |
+
q, k, v, cu_seqlens, cu_seqlens, ms, ms,
|
| 29 |
+
dropout_p=dropout_p, causal=True,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
class ClampedLlamaMLP(LlamaMLP):
|
| 33 |
+
def forward(self, x):
|
| 34 |
+
gate = F.silu(self.gate_proj(x).clamp(-15.0, 15.0))
|
| 35 |
+
up = self.up_proj(x)
|
| 36 |
+
return self.down_proj(gate * up)
|
| 37 |
+
|
| 38 |
+
class XSAAttention(nn.Module):
|
| 39 |
+
def __init__(self, config, layer_idx=None):
|
| 40 |
+
super().__init__()
|
| 41 |
+
self.config = config
|
| 42 |
+
self.layer_idx = layer_idx
|
| 43 |
+
self.recurrent_cache_idx = None
|
| 44 |
+
self._use_recurrent_slot = False
|
| 45 |
+
self.hidden_size = config.hidden_size
|
| 46 |
+
self.num_heads = config.num_attention_heads
|
| 47 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 48 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 49 |
+
self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
|
| 50 |
+
self.attention_bias = getattr(config, "attention_bias", False)
|
| 51 |
+
|
| 52 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=self.attention_bias)
|
| 53 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=self.attention_bias)
|
| 54 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=self.attention_bias)
|
| 55 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=self.attention_bias)
|
| 56 |
+
|
| 57 |
+
self.q_norm = LlamaRMSNorm(self.head_dim, eps=1e-6)
|
| 58 |
+
self.k_norm = LlamaRMSNorm(self.head_dim, eps=1e-6)
|
| 59 |
+
|
| 60 |
+
def forward(self, hidden_states, attention_mask=None, position_ids=None, past_key_value=None,
|
| 61 |
+
output_attentions=False, use_cache=False, cache_position=None, position_embeddings=None,
|
| 62 |
+
expected_batch_size=None, cu_seqlens=None, max_seqlen=None, **kwargs):
|
| 63 |
+
past_kv = past_key_value if past_key_value is not None else kwargs.get("past_key_values", None)
|
| 64 |
+
|
| 65 |
+
if hidden_states.ndim == 2:
|
| 66 |
+
if expected_batch_size is None:
|
| 67 |
+
raise RuntimeError(
|
| 68 |
+
f"XSAAttention received 2D hidden_states {hidden_states.shape} "
|
| 69 |
+
f"without an expected_batch_size to safely restore the batch dim."
|
| 70 |
+
)
|
| 71 |
+
hidden_states = hidden_states.reshape(expected_batch_size, -1, self.hidden_size)
|
| 72 |
+
|
| 73 |
+
bsz, q_len, _ = hidden_states.size()
|
| 74 |
+
|
| 75 |
+
if expected_batch_size is not None and bsz != expected_batch_size:
|
| 76 |
+
raise RuntimeError(
|
| 77 |
+
f"XSAAttention: hidden_states batch size {bsz} does not match "
|
| 78 |
+
f"expected_batch_size {expected_batch_size}."
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim)
|
| 82 |
+
key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim)
|
| 83 |
+
value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim)
|
| 84 |
+
|
| 85 |
+
query_states = self.q_norm(query_states)
|
| 86 |
+
key_states = self.k_norm(key_states)
|
| 87 |
+
|
| 88 |
+
cos, sin = position_embeddings
|
| 89 |
+
|
| 90 |
+
use_flash = (
|
| 91 |
+
cu_seqlens is not None
|
| 92 |
+
and past_kv is None
|
| 93 |
+
and getattr(self.config, "use_flash_attn", False)
|
| 94 |
+
and FLASH_ATTN_AVAILABLE
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
if use_flash:
|
| 98 |
+
total = bsz * q_len
|
| 99 |
+
q = query_states.reshape(total, self.num_heads, self.head_dim)
|
| 100 |
+
k = key_states.reshape(total, self.num_key_value_heads, self.head_dim)
|
| 101 |
+
v = value_states.reshape(total, self.num_key_value_heads, self.head_dim)
|
| 102 |
+
|
| 103 |
+
q = q.to(torch.bfloat16)
|
| 104 |
+
k = k.to(torch.bfloat16)
|
| 105 |
+
v = v.to(torch.bfloat16)
|
| 106 |
+
|
| 107 |
+
cos_f = cos.reshape(-1, cos.shape[-1]).to(torch.bfloat16)
|
| 108 |
+
sin_f = sin.reshape(-1, sin.shape[-1]).to(torch.bfloat16)
|
| 109 |
+
q, k = apply_rotary_pos_emb(q, k, cos_f, sin_f, unsqueeze_dim=1)
|
| 110 |
+
|
| 111 |
+
attn_output = _flash_varlen(
|
| 112 |
+
q, k, v, cu_seqlens, max_seqlen,
|
| 113 |
+
self.config.attention_dropout if self.training else 0.0,
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
if getattr(self.config, 'xsa_projection', True):
|
| 117 |
+
y = attn_output.view(total, self.num_key_value_heads, self.num_key_value_groups, self.head_dim)
|
| 118 |
+
v_grouped = v.unsqueeze(2)
|
| 119 |
+
dot_yv = (y * v_grouped).sum(dim=-1, keepdim=True).float()
|
| 120 |
+
dot_vv = v_grouped.pow(2).sum(dim=-1, keepdim=True).clamp_min(1e-4).float()
|
| 121 |
+
scale = (dot_yv / dot_vv).to(y.dtype)
|
| 122 |
+
attn_output = (y - scale * v_grouped).reshape(total, self.num_heads, self.head_dim)
|
| 123 |
+
|
| 124 |
+
attn_output = self.o_proj(attn_output.reshape(bsz, q_len, self.hidden_size))
|
| 125 |
+
return (attn_output, None)
|
| 126 |
+
|
| 127 |
+
query_states = query_states.transpose(1, 2)
|
| 128 |
+
key_states = key_states.transpose(1, 2)
|
| 129 |
+
value_states = value_states.transpose(1, 2)
|
| 130 |
+
|
| 131 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 132 |
+
|
| 133 |
+
current_v = value_states
|
| 134 |
+
|
| 135 |
+
target_idx = self.layer_idx
|
| 136 |
+
if self._use_recurrent_slot and self.recurrent_cache_idx is not None:
|
| 137 |
+
target_idx = self.recurrent_cache_idx
|
| 138 |
+
|
| 139 |
+
if past_kv is not None:
|
| 140 |
+
while len(past_kv) <= target_idx:
|
| 141 |
+
past_kv.update(
|
| 142 |
+
torch.empty(bsz, self.num_key_value_heads, 0, self.head_dim, dtype=key_states.dtype, device=key_states.device),
|
| 143 |
+
torch.empty(bsz, self.num_key_value_heads, 0, self.head_dim, dtype=value_states.dtype, device=value_states.device),
|
| 144 |
+
len(past_kv)
|
| 145 |
+
)
|
| 146 |
+
key_states, value_states = past_kv.update(key_states, value_states, target_idx)
|
| 147 |
+
|
| 148 |
+
key_states = key_states.repeat_interleave(self.num_key_value_groups, dim=1)
|
| 149 |
+
value_states = value_states.repeat_interleave(self.num_key_value_groups, dim=1)
|
| 150 |
+
|
| 151 |
+
kv_len = key_states.shape[-2]
|
| 152 |
+
|
| 153 |
+
if attention_mask is not None:
|
| 154 |
+
if attention_mask.ndim == 2:
|
| 155 |
+
if attention_mask.shape[-1] < kv_len:
|
| 156 |
+
attention_mask = F.pad(attention_mask, (0, kv_len - attention_mask.shape[-1]), value=1)
|
| 157 |
+
elif attention_mask.shape[-1] > kv_len:
|
| 158 |
+
attention_mask = attention_mask[:, -kv_len:]
|
| 159 |
+
|
| 160 |
+
pad_mask = (1.0 - attention_mask[:, None, None, :].to(query_states.dtype)) * torch.finfo(query_states.dtype).min
|
| 161 |
+
|
| 162 |
+
if q_len > 1:
|
| 163 |
+
if cache_position is None:
|
| 164 |
+
cache_position = torch.arange(kv_len - q_len, kv_len, device=query_states.device)
|
| 165 |
+
kv_positions = torch.arange(kv_len, device=query_states.device)
|
| 166 |
+
|
| 167 |
+
neg_inf = torch.finfo(query_states.dtype).min
|
| 168 |
+
causal_mask = torch.zeros((q_len, kv_len), dtype=query_states.dtype, device=query_states.device)
|
| 169 |
+
causal_mask = causal_mask.masked_fill(kv_positions[None, :] > cache_position[:, None], neg_inf)
|
| 170 |
+
attn_mask = causal_mask[None, None, :, :] + pad_mask
|
| 171 |
+
|
| 172 |
+
diag_idx = torch.arange(q_len, device=attn_mask.device)
|
| 173 |
+
start_idx = attn_mask.shape[-1] - q_len
|
| 174 |
+
attn_mask[:, :, diag_idx, start_idx + diag_idx] = 0.0
|
| 175 |
+
else:
|
| 176 |
+
attn_mask = pad_mask
|
| 177 |
+
else:
|
| 178 |
+
if attention_mask.shape[0] != bsz:
|
| 179 |
+
raise RuntimeError(
|
| 180 |
+
f"attention_mask batch size {attention_mask.shape[0]} does not "
|
| 181 |
+
f"match hidden_states batch size {bsz}."
|
| 182 |
+
)
|
| 183 |
+
attn_mask = attention_mask.to(dtype=query_states.dtype)
|
| 184 |
+
is_causal = False
|
| 185 |
+
else:
|
| 186 |
+
is_causal = True
|
| 187 |
+
attn_mask = None
|
| 188 |
+
|
| 189 |
+
attn_output = F.scaled_dot_product_attention(
|
| 190 |
+
query_states, key_states, value_states, attn_mask=attn_mask,
|
| 191 |
+
dropout_p=0.0 if not self.training else self.config.attention_dropout, is_causal=is_causal
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
if getattr(self.config, 'xsa_projection', True):
|
| 195 |
+
y = attn_output.reshape(bsz, self.num_key_value_heads, self.num_key_value_groups, q_len, self.head_dim)
|
| 196 |
+
v_grouped = current_v.unsqueeze(2)
|
| 197 |
+
dot_yv = (y * v_grouped).sum(dim=-1, keepdim=True).float()
|
| 198 |
+
dot_vv = v_grouped.pow(2).sum(dim=-1, keepdim=True).clamp_min(1e-4).float()
|
| 199 |
+
scale = (dot_yv / dot_vv).to(y.dtype)
|
| 200 |
+
attn_output = (y - scale * v_grouped).reshape(bsz, self.num_heads, q_len, self.head_dim)
|
| 201 |
+
|
| 202 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 203 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
| 204 |
+
attn_output = self.o_proj(attn_output)
|
| 205 |
+
|
| 206 |
+
return (attn_output, None)
|
| 207 |
+
|
| 208 |
+
@torch._dynamo.disable()
|
| 209 |
+
def _checkpointed_layer_forward(layer, hidden_states, attention_mask, position_ids,
|
| 210 |
+
cache_position, cos, sin, expected_batch_size, cu_seqlens, max_seqlen):
|
| 211 |
+
out = layer(
|
| 212 |
+
hidden_states, attention_mask=attention_mask, position_ids=position_ids,
|
| 213 |
+
past_key_value=None, use_cache=False,
|
| 214 |
+
cache_position=cache_position, position_embeddings=(cos, sin),
|
| 215 |
+
expected_batch_size=expected_batch_size,
|
| 216 |
+
cu_seqlens=cu_seqlens, max_seqlen=max_seqlen,
|
| 217 |
+
)
|
| 218 |
+
hs_out = out[0] if isinstance(out, tuple) else out
|
| 219 |
+
if hs_out.ndim != 3 or hs_out.shape[0] != expected_batch_size:
|
| 220 |
+
raise RuntimeError(
|
| 221 |
+
f"Layer output shape {tuple(hs_out.shape)} does not match expected "
|
| 222 |
+
f"batch size {expected_batch_size}."
|
| 223 |
+
)
|
| 224 |
+
return hs_out
|
| 225 |
+
|
| 226 |
+
class SurjoExpModel(LlamaModel):
|
| 227 |
+
def __init__(self, config):
|
| 228 |
+
super().__init__(config)
|
| 229 |
+
|
| 230 |
+
assert config.prelude_layers + config.recurrent_layers + config.coda_layers == config.num_hidden_layers, \
|
| 231 |
+
"prelude_layers + recurrent_layers + coda_layers must equal num_hidden_layers"
|
| 232 |
+
|
| 233 |
+
if getattr(config, "use_flash_attn", False) and not FLASH_ATTN_AVAILABLE:
|
| 234 |
+
raise ImportError(
|
| 235 |
+
"config.use_flash_attn=True but flash_attn is not importable. "
|
| 236 |
+
"Install the FA2 wheel or set use_flash_attn=False."
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
p1 = config.prelude_layers
|
| 240 |
+
r1 = p1 + config.recurrent_layers
|
| 241 |
+
|
| 242 |
+
for i, layer in enumerate(self.layers):
|
| 243 |
+
layer.self_attn = XSAAttention(config, layer_idx=i)
|
| 244 |
+
layer.mlp = ClampedLlamaMLP(config)
|
| 245 |
+
|
| 246 |
+
for i, layer in enumerate(self.layers[p1:r1]):
|
| 247 |
+
layer.self_attn.recurrent_cache_idx = config.num_hidden_layers + p1 + i
|
| 248 |
+
|
| 249 |
+
self.gradient_checkpointing = getattr(config, "gradient_checkpointing", True)
|
| 250 |
+
|
| 251 |
+
def gradient_checkpointing_enable(self):
|
| 252 |
+
self.gradient_checkpointing = True
|
| 253 |
+
|
| 254 |
+
def gradient_checkpointing_disable(self):
|
| 255 |
+
self.gradient_checkpointing = False
|
| 256 |
+
|
| 257 |
+
def forward(self, input_ids=None, attention_mask=None, position_ids=None, inputs_embeds=None,
|
| 258 |
+
past_key_values=None, use_cache=None, output_attentions=False, output_hidden_states=False,
|
| 259 |
+
cache_position=None, return_dict=True, cu_seqlens=None, max_seqlen=None, **kwargs):
|
| 260 |
+
if use_cache is None:
|
| 261 |
+
use_cache = False
|
| 262 |
+
|
| 263 |
+
if inputs_embeds is None:
|
| 264 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 265 |
+
|
| 266 |
+
bsz, seq_len = inputs_embeds.shape[0], inputs_embeds.shape[1]
|
| 267 |
+
|
| 268 |
+
if cache_position is None:
|
| 269 |
+
past_seen = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 270 |
+
cache_position = torch.arange(past_seen, past_seen + seq_len, dtype=torch.long, device=inputs_embeds.device)
|
| 271 |
+
if position_ids is None:
|
| 272 |
+
position_ids = cache_position.unsqueeze(0).expand(bsz, -1)
|
| 273 |
+
|
| 274 |
+
hidden_states = inputs_embeds
|
| 275 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 276 |
+
cos, sin = position_embeddings
|
| 277 |
+
|
| 278 |
+
if use_cache and past_key_values is None:
|
| 279 |
+
past_key_values = DynamicCache()
|
| 280 |
+
|
| 281 |
+
p1 = self.config.prelude_layers
|
| 282 |
+
r1 = p1 + self.config.recurrent_layers
|
| 283 |
+
c1 = r1 + self.config.coda_layers
|
| 284 |
+
|
| 285 |
+
prelude = self.layers[:p1]
|
| 286 |
+
recurrent = self.layers[p1:r1]
|
| 287 |
+
coda = self.layers[r1:c1]
|
| 288 |
+
|
| 289 |
+
use_ckpt = self.training and self.gradient_checkpointing and not use_cache
|
| 290 |
+
|
| 291 |
+
def run_layer(layer, hs):
|
| 292 |
+
if cu_seqlens is not None:
|
| 293 |
+
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
| 294 |
+
|
| 295 |
+
out = layer(
|
| 296 |
+
hs, attention_mask=attention_mask, position_ids=position_ids,
|
| 297 |
+
past_key_value=past_key_values if use_cache else None, use_cache=use_cache,
|
| 298 |
+
cache_position=cache_position, position_embeddings=position_embeddings,
|
| 299 |
+
expected_batch_size=bsz, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen,
|
| 300 |
+
)
|
| 301 |
+
hs_out = out[0] if isinstance(out, tuple) else out
|
| 302 |
+
if hs_out.ndim != 3 or hs_out.shape[0] != bsz:
|
| 303 |
+
raise RuntimeError(
|
| 304 |
+
f"Layer output shape {tuple(hs_out.shape)} does not match expected "
|
| 305 |
+
f"batch size {bsz}."
|
| 306 |
+
)
|
| 307 |
+
return hs_out
|
| 308 |
+
|
| 309 |
+
def run_layer_maybe_ckpt(layer, hs):
|
| 310 |
+
if use_ckpt:
|
| 311 |
+
return torch.utils.checkpoint.checkpoint(
|
| 312 |
+
_checkpointed_layer_forward,
|
| 313 |
+
layer, hs, attention_mask, position_ids, cache_position, cos, sin, bsz,
|
| 314 |
+
cu_seqlens, max_seqlen,
|
| 315 |
+
use_reentrant=False,
|
| 316 |
+
)
|
| 317 |
+
return run_layer(layer, hs)
|
| 318 |
+
|
| 319 |
+
for layer in prelude:
|
| 320 |
+
hidden_states = run_layer_maybe_ckpt(layer, hidden_states)
|
| 321 |
+
|
| 322 |
+
if self.training:
|
| 323 |
+
hidden_states = hidden_states + torch.randn_like(hidden_states) * 0.02
|
| 324 |
+
|
| 325 |
+
for layer in recurrent:
|
| 326 |
+
hidden_states = run_layer_maybe_ckpt(layer, hidden_states)
|
| 327 |
+
|
| 328 |
+
if self.training:
|
| 329 |
+
hidden_states = hidden_states + torch.randn_like(hidden_states) * 0.02
|
| 330 |
+
|
| 331 |
+
for layer in recurrent:
|
| 332 |
+
layer.self_attn._use_recurrent_slot = True
|
| 333 |
+
try:
|
| 334 |
+
hidden_states = run_layer_maybe_ckpt(layer, hidden_states)
|
| 335 |
+
finally:
|
| 336 |
+
layer.self_attn._use_recurrent_slot = False
|
| 337 |
+
|
| 338 |
+
for layer in coda:
|
| 339 |
+
hidden_states = run_layer_maybe_ckpt(layer, hidden_states)
|
| 340 |
+
|
| 341 |
+
hidden_states = self.norm(hidden_states)
|
| 342 |
+
return BaseModelOutputWithPast(last_hidden_state=hidden_states, past_key_values=past_key_values)
|
| 343 |
+
|
| 344 |
+
class SurjoExpForCausalLM(LlamaForCausalLM):
|
| 345 |
+
config_class = SurjoExpConfig
|
| 346 |
+
def __init__(self, config):
|
| 347 |
+
super(LlamaForCausalLM, self).__init__(config)
|
| 348 |
+
self.model = SurjoExpModel(config)
|
| 349 |
+
self.vocab_size = config.vocab_size
|
| 350 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 351 |
+
self.post_init()
|
| 352 |
+
|
| 353 |
+
def gradient_checkpointing_enable(self, **kwargs):
|
| 354 |
+
self.model.gradient_checkpointing_enable()
|
| 355 |
+
|
| 356 |
+
def gradient_checkpointing_disable(self):
|
| 357 |
+
self.model.gradient_checkpointing_disable()
|
| 358 |
+
|
| 359 |
+
def forward(self, input_ids=None, attention_mask=None, labels=None, inputs_embeds=None,
|
| 360 |
+
use_cache=None, num_logits_to_keep=0, position_ids=None, past_key_values=None,
|
| 361 |
+
cache_position=None, cu_seqlens=None, max_seqlen=None, **kwargs):
|
| 362 |
+
if use_cache is None:
|
| 363 |
+
use_cache = False if (self.training or labels is not None) else True
|
| 364 |
+
|
| 365 |
+
if num_logits_to_keep == 0 and "logits_to_keep" in kwargs:
|
| 366 |
+
num_logits_to_keep = kwargs["logits_to_keep"]
|
| 367 |
+
|
| 368 |
+
outputs = self.model(
|
| 369 |
+
input_ids=input_ids,
|
| 370 |
+
attention_mask=attention_mask,
|
| 371 |
+
position_ids=position_ids,
|
| 372 |
+
inputs_embeds=inputs_embeds,
|
| 373 |
+
past_key_values=past_key_values,
|
| 374 |
+
use_cache=use_cache,
|
| 375 |
+
cache_position=cache_position,
|
| 376 |
+
cu_seqlens=cu_seqlens,
|
| 377 |
+
max_seqlen=max_seqlen,
|
| 378 |
+
)
|
| 379 |
+
hidden_states = outputs[0]
|
| 380 |
+
|
| 381 |
+
expected_bsz = input_ids.shape[0] if input_ids is not None else inputs_embeds.shape[0]
|
| 382 |
+
if hidden_states.ndim != 3 or hidden_states.shape[0] != expected_bsz:
|
| 383 |
+
raise RuntimeError(
|
| 384 |
+
f"SurjoExpModel returned hidden_states with shape {tuple(hidden_states.shape)}, "
|
| 385 |
+
f"expected batch size {expected_bsz}."
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
loss = None
|
| 389 |
+
logits = None
|
| 390 |
+
|
| 391 |
+
if labels is not None:
|
| 392 |
+
shift_hidden = hidden_states[..., :-1, :].contiguous()
|
| 393 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 394 |
+
|
| 395 |
+
num_chunks = 8
|
| 396 |
+
h_chunks = shift_hidden.chunk(num_chunks, dim=0)
|
| 397 |
+
l_chunks = shift_labels.chunk(num_chunks, dim=0)
|
| 398 |
+
|
| 399 |
+
total_loss = hidden_states.new_zeros((), dtype=torch.float32)
|
| 400 |
+
total_tokens = 0
|
| 401 |
+
for h_c, l_c in zip(h_chunks, l_chunks):
|
| 402 |
+
logits_c = self.lm_head(h_c)
|
| 403 |
+
chunk_loss = F.cross_entropy(
|
| 404 |
+
logits_c.view(-1, logits_c.size(-1)).float(),
|
| 405 |
+
l_c.view(-1),
|
| 406 |
+
reduction="sum",
|
| 407 |
+
)
|
| 408 |
+
total_loss = total_loss + chunk_loss
|
| 409 |
+
total_tokens += l_c.numel()
|
| 410 |
+
loss = (total_loss / total_tokens).to(hidden_states.dtype)
|
| 411 |
+
else:
|
| 412 |
+
slice_hidden = hidden_states if num_logits_to_keep == 0 else hidden_states[:, -num_logits_to_keep:, :]
|
| 413 |
+
logits = self.lm_head(slice_hidden)
|
| 414 |
+
|
| 415 |
+
return CausalLMOutputWithPast(
|
| 416 |
+
loss=loss, logits=logits, past_key_values=outputs.past_key_values
|
| 417 |
+
)
|
checkpoint-1000/optimizer.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c6b394d6f309adbbffea29d1d10fec6b00da75cc46e88cefd995d809902ea91a
|
| 3 |
+
size 445974859
|
checkpoint-1000/optimizer_1.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a1be1befd1a27d3f2d69a1d0d3e995a7c89cf42e555e91d6beca6527bce0762c
|
| 3 |
+
size 151436195
|
checkpoint-1000/random_states_0.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:add40f08bbc1206775769ce44d91cd19424f9c3e000687bf8341907acc4622b3
|
| 3 |
+
size 14821
|
checkpoint-1000/tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
checkpoint-1000/tokenizer_config.json
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"bos_token": "<|bos|>",
|
| 4 |
+
"clean_up_tokenization_spaces": false,
|
| 5 |
+
"eos_token": "<|eos|>",
|
| 6 |
+
"extra_special_tokens": [
|
| 7 |
+
"<|unk|>",
|
| 8 |
+
"<|pad|>",
|
| 9 |
+
"<|bos|>",
|
| 10 |
+
"<|eos|>",
|
| 11 |
+
"<|mask|>",
|
| 12 |
+
"<|im_start|>",
|
| 13 |
+
"<|im_end|>",
|
| 14 |
+
"<|system|>",
|
| 15 |
+
"<|user|>",
|
| 16 |
+
"<|assistant|>",
|
| 17 |
+
"<think>",
|
| 18 |
+
"</think>",
|
| 19 |
+
"<|begin_of_thought|>",
|
| 20 |
+
"<|end_of_thought|>",
|
| 21 |
+
"<answer>",
|
| 22 |
+
"</answer>",
|
| 23 |
+
"<|step|>",
|
| 24 |
+
"<|/step|>",
|
| 25 |
+
"<context>",
|
| 26 |
+
"</context>",
|
| 27 |
+
"<|doc_start|>",
|
| 28 |
+
"<|doc_end|>",
|
| 29 |
+
"<|search|>",
|
| 30 |
+
"<|search_results|>",
|
| 31 |
+
"<|tool_list_start|>",
|
| 32 |
+
"<|tool_list_end|>",
|
| 33 |
+
"<tools>",
|
| 34 |
+
"</tools>",
|
| 35 |
+
"<|tool_call_start|>",
|
| 36 |
+
"<|tool_call_end|>",
|
| 37 |
+
"<|tool_call|>",
|
| 38 |
+
"<|/tool_call|>",
|
| 39 |
+
"<|tool_response_start|>",
|
| 40 |
+
"<|tool_response_end|>",
|
| 41 |
+
"<|tool_response|>",
|
| 42 |
+
"<|/tool_response|>",
|
| 43 |
+
"<|image|>",
|
| 44 |
+
"<|image_pad|>",
|
| 45 |
+
"<|image_placeholder|>",
|
| 46 |
+
"<|audio|>",
|
| 47 |
+
"<|audio_pad|>",
|
| 48 |
+
"<|audio_placeholder|>",
|
| 49 |
+
"<|video|>",
|
| 50 |
+
"<|video_pad|>",
|
| 51 |
+
"<|fim_prefix|>",
|
| 52 |
+
"<|fim_suffix|>",
|
| 53 |
+
"<|fim_middle|>",
|
| 54 |
+
"<|repo_name|>",
|
| 55 |
+
"<|file_separator|>",
|
| 56 |
+
"<|reward|>",
|
| 57 |
+
"<|reserved_0|>",
|
| 58 |
+
"<|reserved_1|>",
|
| 59 |
+
"<|reserved_2|>",
|
| 60 |
+
"<|reserved_3|>",
|
| 61 |
+
"<|reserved_4|>",
|
| 62 |
+
"<|reserved_5|>",
|
| 63 |
+
"<|reserved_6|>",
|
| 64 |
+
"<|reserved_7|>",
|
| 65 |
+
"<|reserved_8|>",
|
| 66 |
+
"<|reserved_9|>",
|
| 67 |
+
"<|reserved_10|>",
|
| 68 |
+
"<|reserved_11|>",
|
| 69 |
+
"<|reserved_12|>",
|
| 70 |
+
"<|reserved_13|>",
|
| 71 |
+
"<|reserved_14|>",
|
| 72 |
+
"<|reserved_15|>",
|
| 73 |
+
"<|reserved_16|>",
|
| 74 |
+
"<|reserved_17|>",
|
| 75 |
+
"<|reserved_18|>",
|
| 76 |
+
"<|reserved_19|>"
|
| 77 |
+
],
|
| 78 |
+
"is_local": false,
|
| 79 |
+
"local_files_only": false,
|
| 80 |
+
"mask_token": "<|mask|>",
|
| 81 |
+
"model_max_length": 10000000,
|
| 82 |
+
"pad_token": "<|pad|>",
|
| 83 |
+
"tokenizer_class": "TokenizersBackend",
|
| 84 |
+
"unk_token": "<|unk|>"
|
| 85 |
+
}
|
checkpoint-10000/chat_template.jinja
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{ bos_token }}{% for message in messages %}{{ '<|im_start|>' + message['role'] + '
|
| 2 |
+
' + message['content'] + '<|im_end|>
|
| 3 |
+
' }}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant
|
| 4 |
+
' }}{% endif %}
|
checkpoint-10000/config.json
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"SurjoExpForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"attention_bias": false,
|
| 6 |
+
"attention_dropout": 0.0,
|
| 7 |
+
"auto_map": {
|
| 8 |
+
"AutoConfig": "configuration_surjo_exp.SurjoExpConfig",
|
| 9 |
+
"AutoModelForCausalLM": "modeling_surjo_exp.SurjoExpForCausalLM"
|
| 10 |
+
},
|
| 11 |
+
"bos_token_id": 0,
|
| 12 |
+
"coda_layers": 16,
|
| 13 |
+
"dtype": "float32",
|
| 14 |
+
"eos_token_id": 2,
|
| 15 |
+
"gradient_checkpointing": false,
|
| 16 |
+
"head_dim": 72,
|
| 17 |
+
"hidden_act": "silu",
|
| 18 |
+
"hidden_size": 576,
|
| 19 |
+
"initializer_range": 0.02,
|
| 20 |
+
"intermediate_size": 1536,
|
| 21 |
+
"max_position_embeddings": 2048,
|
| 22 |
+
"mlp_bias": false,
|
| 23 |
+
"model_type": "surjo_exp",
|
| 24 |
+
"num_attention_heads": 8,
|
| 25 |
+
"num_hidden_layers": 32,
|
| 26 |
+
"num_key_value_heads": 2,
|
| 27 |
+
"pad_token_id": 1,
|
| 28 |
+
"prelude_layers": 4,
|
| 29 |
+
"pretraining_tp": 1,
|
| 30 |
+
"recurrent_layers": 12,
|
| 31 |
+
"rms_norm_eps": 1e-05,
|
| 32 |
+
"rope_parameters": {
|
| 33 |
+
"rope_theta": 10000.0,
|
| 34 |
+
"rope_type": "default"
|
| 35 |
+
},
|
| 36 |
+
"rope_theta": 10000.0,
|
| 37 |
+
"tie_word_embeddings": true,
|
| 38 |
+
"transformers_version": "5.15.0",
|
| 39 |
+
"use_cache": false,
|
| 40 |
+
"use_flash_attn": false,
|
| 41 |
+
"vocab_size": 32768,
|
| 42 |
+
"xsa_projection": true
|
| 43 |
+
}
|
checkpoint-10000/configuration_surjo_exp.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from transformers import LlamaConfig
|
| 3 |
+
|
| 4 |
+
class SurjoExpConfig(LlamaConfig):
|
| 5 |
+
model_type = "surjo_exp"
|
| 6 |
+
def __init__(self, *args, xsa_projection=True, rope_theta=10000.0, attention_bias=False,
|
| 7 |
+
prelude_layers=4, recurrent_layers=12, coda_layers=16,
|
| 8 |
+
gradient_checkpointing=True, use_flash_attn=True, **kwargs):
|
| 9 |
+
kwargs["num_hidden_layers"] = prelude_layers + recurrent_layers + coda_layers
|
| 10 |
+
kwargs.setdefault("use_cache", False)
|
| 11 |
+
super().__init__(*args, rope_theta=rope_theta, attention_bias=attention_bias, **kwargs)
|
| 12 |
+
self.xsa_projection = xsa_projection
|
| 13 |
+
self.rope_theta = rope_theta
|
| 14 |
+
self.attention_bias = attention_bias
|
| 15 |
+
self.prelude_layers = prelude_layers
|
| 16 |
+
self.recurrent_layers = recurrent_layers
|
| 17 |
+
self.coda_layers = coda_layers
|
| 18 |
+
self.gradient_checkpointing = gradient_checkpointing
|
| 19 |
+
self.use_flash_attn = use_flash_attn
|
| 20 |
+
if not hasattr(self, 'rope_parameters') or self.rope_parameters is None:
|
| 21 |
+
self.rope_parameters = {"rope_type": "default", "factor": 1.0, "rope_theta": rope_theta}
|
checkpoint-10000/generation_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 0,
|
| 4 |
+
"eos_token_id": 2,
|
| 5 |
+
"output_attentions": false,
|
| 6 |
+
"output_hidden_states": false,
|
| 7 |
+
"pad_token_id": 1,
|
| 8 |
+
"transformers_version": "5.15.0",
|
| 9 |
+
"use_cache": false
|
| 10 |
+
}
|
checkpoint-10000/model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:88f0d0ceb027ddccd77b39ad137541505598dd42978097ae4f01fc17a4aef03e
|
| 3 |
+
size 521611856
|
checkpoint-10000/modeling_surjo_exp.py
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import torch.utils.checkpoint
|
| 6 |
+
from transformers import LlamaConfig, LlamaModel, LlamaForCausalLM
|
| 7 |
+
from transformers.models.llama.modeling_llama import LlamaRMSNorm
|
| 8 |
+
from transformers.models.llama.modeling_llama import LlamaMLP
|
| 9 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 10 |
+
from transformers.models.llama.modeling_llama import LlamaRotaryEmbedding, apply_rotary_pos_emb
|
| 11 |
+
from transformers.cache_utils import DynamicCache
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
from .configuration_surjo_exp import SurjoExpConfig
|
| 15 |
+
except ImportError:
|
| 16 |
+
from configuration_surjo_exp import SurjoExpConfig
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
from flash_attn import flash_attn_varlen_func
|
| 20 |
+
FLASH_ATTN_AVAILABLE = True
|
| 21 |
+
except ImportError:
|
| 22 |
+
FLASH_ATTN_AVAILABLE = False
|
| 23 |
+
|
| 24 |
+
@torch._dynamo.disable()
|
| 25 |
+
def _flash_varlen(q, k, v, cu_seqlens, max_seqlen, dropout_p):
|
| 26 |
+
ms = int(max_seqlen.item()) if torch.is_tensor(max_seqlen) else int(max_seqlen)
|
| 27 |
+
return flash_attn_varlen_func(
|
| 28 |
+
q, k, v, cu_seqlens, cu_seqlens, ms, ms,
|
| 29 |
+
dropout_p=dropout_p, causal=True,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
class ClampedLlamaMLP(LlamaMLP):
|
| 33 |
+
def forward(self, x):
|
| 34 |
+
gate = F.silu(self.gate_proj(x).clamp(-15.0, 15.0))
|
| 35 |
+
up = self.up_proj(x)
|
| 36 |
+
return self.down_proj(gate * up)
|
| 37 |
+
|
| 38 |
+
class XSAAttention(nn.Module):
|
| 39 |
+
def __init__(self, config, layer_idx=None):
|
| 40 |
+
super().__init__()
|
| 41 |
+
self.config = config
|
| 42 |
+
self.layer_idx = layer_idx
|
| 43 |
+
self.recurrent_cache_idx = None
|
| 44 |
+
self._use_recurrent_slot = False
|
| 45 |
+
self.hidden_size = config.hidden_size
|
| 46 |
+
self.num_heads = config.num_attention_heads
|
| 47 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 48 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 49 |
+
self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
|
| 50 |
+
self.attention_bias = getattr(config, "attention_bias", False)
|
| 51 |
+
|
| 52 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=self.attention_bias)
|
| 53 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=self.attention_bias)
|
| 54 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=self.attention_bias)
|
| 55 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=self.attention_bias)
|
| 56 |
+
|
| 57 |
+
self.q_norm = LlamaRMSNorm(self.head_dim, eps=1e-6)
|
| 58 |
+
self.k_norm = LlamaRMSNorm(self.head_dim, eps=1e-6)
|
| 59 |
+
|
| 60 |
+
def forward(self, hidden_states, attention_mask=None, position_ids=None, past_key_value=None,
|
| 61 |
+
output_attentions=False, use_cache=False, cache_position=None, position_embeddings=None,
|
| 62 |
+
expected_batch_size=None, cu_seqlens=None, max_seqlen=None, **kwargs):
|
| 63 |
+
past_kv = past_key_value if past_key_value is not None else kwargs.get("past_key_values", None)
|
| 64 |
+
|
| 65 |
+
if hidden_states.ndim == 2:
|
| 66 |
+
if expected_batch_size is None:
|
| 67 |
+
raise RuntimeError(
|
| 68 |
+
f"XSAAttention received 2D hidden_states {hidden_states.shape} "
|
| 69 |
+
f"without an expected_batch_size to safely restore the batch dim."
|
| 70 |
+
)
|
| 71 |
+
hidden_states = hidden_states.reshape(expected_batch_size, -1, self.hidden_size)
|
| 72 |
+
|
| 73 |
+
bsz, q_len, _ = hidden_states.size()
|
| 74 |
+
|
| 75 |
+
if expected_batch_size is not None and bsz != expected_batch_size:
|
| 76 |
+
raise RuntimeError(
|
| 77 |
+
f"XSAAttention: hidden_states batch size {bsz} does not match "
|
| 78 |
+
f"expected_batch_size {expected_batch_size}."
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim)
|
| 82 |
+
key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim)
|
| 83 |
+
value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim)
|
| 84 |
+
|
| 85 |
+
query_states = self.q_norm(query_states)
|
| 86 |
+
key_states = self.k_norm(key_states)
|
| 87 |
+
|
| 88 |
+
cos, sin = position_embeddings
|
| 89 |
+
|
| 90 |
+
use_flash = (
|
| 91 |
+
cu_seqlens is not None
|
| 92 |
+
and past_kv is None
|
| 93 |
+
and getattr(self.config, "use_flash_attn", False)
|
| 94 |
+
and FLASH_ATTN_AVAILABLE
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
if use_flash:
|
| 98 |
+
total = bsz * q_len
|
| 99 |
+
q = query_states.reshape(total, self.num_heads, self.head_dim)
|
| 100 |
+
k = key_states.reshape(total, self.num_key_value_heads, self.head_dim)
|
| 101 |
+
v = value_states.reshape(total, self.num_key_value_heads, self.head_dim)
|
| 102 |
+
|
| 103 |
+
q = q.to(torch.bfloat16)
|
| 104 |
+
k = k.to(torch.bfloat16)
|
| 105 |
+
v = v.to(torch.bfloat16)
|
| 106 |
+
|
| 107 |
+
cos_f = cos.reshape(-1, cos.shape[-1]).to(torch.bfloat16)
|
| 108 |
+
sin_f = sin.reshape(-1, sin.shape[-1]).to(torch.bfloat16)
|
| 109 |
+
q, k = apply_rotary_pos_emb(q, k, cos_f, sin_f, unsqueeze_dim=1)
|
| 110 |
+
|
| 111 |
+
attn_output = _flash_varlen(
|
| 112 |
+
q, k, v, cu_seqlens, max_seqlen,
|
| 113 |
+
self.config.attention_dropout if self.training else 0.0,
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
if getattr(self.config, 'xsa_projection', True):
|
| 117 |
+
y = attn_output.view(total, self.num_key_value_heads, self.num_key_value_groups, self.head_dim)
|
| 118 |
+
v_grouped = v.unsqueeze(2)
|
| 119 |
+
dot_yv = (y * v_grouped).sum(dim=-1, keepdim=True).float()
|
| 120 |
+
dot_vv = v_grouped.pow(2).sum(dim=-1, keepdim=True).clamp_min(1e-4).float()
|
| 121 |
+
scale = (dot_yv / dot_vv).to(y.dtype)
|
| 122 |
+
attn_output = (y - scale * v_grouped).reshape(total, self.num_heads, self.head_dim)
|
| 123 |
+
|
| 124 |
+
attn_output = self.o_proj(attn_output.reshape(bsz, q_len, self.hidden_size))
|
| 125 |
+
return (attn_output, None)
|
| 126 |
+
|
| 127 |
+
query_states = query_states.transpose(1, 2)
|
| 128 |
+
key_states = key_states.transpose(1, 2)
|
| 129 |
+
value_states = value_states.transpose(1, 2)
|
| 130 |
+
|
| 131 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 132 |
+
|
| 133 |
+
current_v = value_states
|
| 134 |
+
|
| 135 |
+
target_idx = self.layer_idx
|
| 136 |
+
if self._use_recurrent_slot and self.recurrent_cache_idx is not None:
|
| 137 |
+
target_idx = self.recurrent_cache_idx
|
| 138 |
+
|
| 139 |
+
if past_kv is not None:
|
| 140 |
+
while len(past_kv) <= target_idx:
|
| 141 |
+
past_kv.update(
|
| 142 |
+
torch.empty(bsz, self.num_key_value_heads, 0, self.head_dim, dtype=key_states.dtype, device=key_states.device),
|
| 143 |
+
torch.empty(bsz, self.num_key_value_heads, 0, self.head_dim, dtype=value_states.dtype, device=value_states.device),
|
| 144 |
+
len(past_kv)
|
| 145 |
+
)
|
| 146 |
+
key_states, value_states = past_kv.update(key_states, value_states, target_idx)
|
| 147 |
+
|
| 148 |
+
key_states = key_states.repeat_interleave(self.num_key_value_groups, dim=1)
|
| 149 |
+
value_states = value_states.repeat_interleave(self.num_key_value_groups, dim=1)
|
| 150 |
+
|
| 151 |
+
kv_len = key_states.shape[-2]
|
| 152 |
+
|
| 153 |
+
if attention_mask is not None:
|
| 154 |
+
if attention_mask.ndim == 2:
|
| 155 |
+
if attention_mask.shape[-1] < kv_len:
|
| 156 |
+
attention_mask = F.pad(attention_mask, (0, kv_len - attention_mask.shape[-1]), value=1)
|
| 157 |
+
elif attention_mask.shape[-1] > kv_len:
|
| 158 |
+
attention_mask = attention_mask[:, -kv_len:]
|
| 159 |
+
|
| 160 |
+
pad_mask = (1.0 - attention_mask[:, None, None, :].to(query_states.dtype)) * torch.finfo(query_states.dtype).min
|
| 161 |
+
|
| 162 |
+
if q_len > 1:
|
| 163 |
+
if cache_position is None:
|
| 164 |
+
cache_position = torch.arange(kv_len - q_len, kv_len, device=query_states.device)
|
| 165 |
+
kv_positions = torch.arange(kv_len, device=query_states.device)
|
| 166 |
+
|
| 167 |
+
neg_inf = torch.finfo(query_states.dtype).min
|
| 168 |
+
causal_mask = torch.zeros((q_len, kv_len), dtype=query_states.dtype, device=query_states.device)
|
| 169 |
+
causal_mask = causal_mask.masked_fill(kv_positions[None, :] > cache_position[:, None], neg_inf)
|
| 170 |
+
attn_mask = causal_mask[None, None, :, :] + pad_mask
|
| 171 |
+
|
| 172 |
+
diag_idx = torch.arange(q_len, device=attn_mask.device)
|
| 173 |
+
start_idx = attn_mask.shape[-1] - q_len
|
| 174 |
+
attn_mask[:, :, diag_idx, start_idx + diag_idx] = 0.0
|
| 175 |
+
else:
|
| 176 |
+
attn_mask = pad_mask
|
| 177 |
+
else:
|
| 178 |
+
if attention_mask.shape[0] != bsz:
|
| 179 |
+
raise RuntimeError(
|
| 180 |
+
f"attention_mask batch size {attention_mask.shape[0]} does not "
|
| 181 |
+
f"match hidden_states batch size {bsz}."
|
| 182 |
+
)
|
| 183 |
+
attn_mask = attention_mask.to(dtype=query_states.dtype)
|
| 184 |
+
is_causal = False
|
| 185 |
+
else:
|
| 186 |
+
is_causal = True
|
| 187 |
+
attn_mask = None
|
| 188 |
+
|
| 189 |
+
attn_output = F.scaled_dot_product_attention(
|
| 190 |
+
query_states, key_states, value_states, attn_mask=attn_mask,
|
| 191 |
+
dropout_p=0.0 if not self.training else self.config.attention_dropout, is_causal=is_causal
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
if getattr(self.config, 'xsa_projection', True):
|
| 195 |
+
y = attn_output.reshape(bsz, self.num_key_value_heads, self.num_key_value_groups, q_len, self.head_dim)
|
| 196 |
+
v_grouped = current_v.unsqueeze(2)
|
| 197 |
+
dot_yv = (y * v_grouped).sum(dim=-1, keepdim=True).float()
|
| 198 |
+
dot_vv = v_grouped.pow(2).sum(dim=-1, keepdim=True).clamp_min(1e-4).float()
|
| 199 |
+
scale = (dot_yv / dot_vv).to(y.dtype)
|
| 200 |
+
attn_output = (y - scale * v_grouped).reshape(bsz, self.num_heads, q_len, self.head_dim)
|
| 201 |
+
|
| 202 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 203 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
| 204 |
+
attn_output = self.o_proj(attn_output)
|
| 205 |
+
|
| 206 |
+
return (attn_output, None)
|
| 207 |
+
|
| 208 |
+
@torch._dynamo.disable()
|
| 209 |
+
def _checkpointed_layer_forward(layer, hidden_states, attention_mask, position_ids,
|
| 210 |
+
cache_position, cos, sin, expected_batch_size, cu_seqlens, max_seqlen):
|
| 211 |
+
out = layer(
|
| 212 |
+
hidden_states, attention_mask=attention_mask, position_ids=position_ids,
|
| 213 |
+
past_key_value=None, use_cache=False,
|
| 214 |
+
cache_position=cache_position, position_embeddings=(cos, sin),
|
| 215 |
+
expected_batch_size=expected_batch_size,
|
| 216 |
+
cu_seqlens=cu_seqlens, max_seqlen=max_seqlen,
|
| 217 |
+
)
|
| 218 |
+
hs_out = out[0] if isinstance(out, tuple) else out
|
| 219 |
+
if hs_out.ndim != 3 or hs_out.shape[0] != expected_batch_size:
|
| 220 |
+
raise RuntimeError(
|
| 221 |
+
f"Layer output shape {tuple(hs_out.shape)} does not match expected "
|
| 222 |
+
f"batch size {expected_batch_size}."
|
| 223 |
+
)
|
| 224 |
+
return hs_out
|
| 225 |
+
|
| 226 |
+
class SurjoExpModel(LlamaModel):
|
| 227 |
+
def __init__(self, config):
|
| 228 |
+
super().__init__(config)
|
| 229 |
+
|
| 230 |
+
assert config.prelude_layers + config.recurrent_layers + config.coda_layers == config.num_hidden_layers, \
|
| 231 |
+
"prelude_layers + recurrent_layers + coda_layers must equal num_hidden_layers"
|
| 232 |
+
|
| 233 |
+
if getattr(config, "use_flash_attn", False) and not FLASH_ATTN_AVAILABLE:
|
| 234 |
+
raise ImportError(
|
| 235 |
+
"config.use_flash_attn=True but flash_attn is not importable. "
|
| 236 |
+
"Install the FA2 wheel or set use_flash_attn=False."
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
p1 = config.prelude_layers
|
| 240 |
+
r1 = p1 + config.recurrent_layers
|
| 241 |
+
|
| 242 |
+
for i, layer in enumerate(self.layers):
|
| 243 |
+
layer.self_attn = XSAAttention(config, layer_idx=i)
|
| 244 |
+
layer.mlp = ClampedLlamaMLP(config)
|
| 245 |
+
|
| 246 |
+
for i, layer in enumerate(self.layers[p1:r1]):
|
| 247 |
+
layer.self_attn.recurrent_cache_idx = config.num_hidden_layers + p1 + i
|
| 248 |
+
|
| 249 |
+
self.gradient_checkpointing = getattr(config, "gradient_checkpointing", True)
|
| 250 |
+
|
| 251 |
+
def gradient_checkpointing_enable(self):
|
| 252 |
+
self.gradient_checkpointing = True
|
| 253 |
+
|
| 254 |
+
def gradient_checkpointing_disable(self):
|
| 255 |
+
self.gradient_checkpointing = False
|
| 256 |
+
|
| 257 |
+
def forward(self, input_ids=None, attention_mask=None, position_ids=None, inputs_embeds=None,
|
| 258 |
+
past_key_values=None, use_cache=None, output_attentions=False, output_hidden_states=False,
|
| 259 |
+
cache_position=None, return_dict=True, cu_seqlens=None, max_seqlen=None, **kwargs):
|
| 260 |
+
if use_cache is None:
|
| 261 |
+
use_cache = False
|
| 262 |
+
|
| 263 |
+
if inputs_embeds is None:
|
| 264 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 265 |
+
|
| 266 |
+
bsz, seq_len = inputs_embeds.shape[0], inputs_embeds.shape[1]
|
| 267 |
+
|
| 268 |
+
if cache_position is None:
|
| 269 |
+
past_seen = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 270 |
+
cache_position = torch.arange(past_seen, past_seen + seq_len, dtype=torch.long, device=inputs_embeds.device)
|
| 271 |
+
if position_ids is None:
|
| 272 |
+
position_ids = cache_position.unsqueeze(0).expand(bsz, -1)
|
| 273 |
+
|
| 274 |
+
hidden_states = inputs_embeds
|
| 275 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 276 |
+
cos, sin = position_embeddings
|
| 277 |
+
|
| 278 |
+
if use_cache and past_key_values is None:
|
| 279 |
+
past_key_values = DynamicCache()
|
| 280 |
+
|
| 281 |
+
p1 = self.config.prelude_layers
|
| 282 |
+
r1 = p1 + self.config.recurrent_layers
|
| 283 |
+
c1 = r1 + self.config.coda_layers
|
| 284 |
+
|
| 285 |
+
prelude = self.layers[:p1]
|
| 286 |
+
recurrent = self.layers[p1:r1]
|
| 287 |
+
coda = self.layers[r1:c1]
|
| 288 |
+
|
| 289 |
+
use_ckpt = self.training and self.gradient_checkpointing and not use_cache
|
| 290 |
+
|
| 291 |
+
def run_layer(layer, hs):
|
| 292 |
+
if cu_seqlens is not None:
|
| 293 |
+
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
| 294 |
+
|
| 295 |
+
out = layer(
|
| 296 |
+
hs, attention_mask=attention_mask, position_ids=position_ids,
|
| 297 |
+
past_key_value=past_key_values if use_cache else None, use_cache=use_cache,
|
| 298 |
+
cache_position=cache_position, position_embeddings=position_embeddings,
|
| 299 |
+
expected_batch_size=bsz, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen,
|
| 300 |
+
)
|
| 301 |
+
hs_out = out[0] if isinstance(out, tuple) else out
|
| 302 |
+
if hs_out.ndim != 3 or hs_out.shape[0] != bsz:
|
| 303 |
+
raise RuntimeError(
|
| 304 |
+
f"Layer output shape {tuple(hs_out.shape)} does not match expected "
|
| 305 |
+
f"batch size {bsz}."
|
| 306 |
+
)
|
| 307 |
+
return hs_out
|
| 308 |
+
|
| 309 |
+
def run_layer_maybe_ckpt(layer, hs):
|
| 310 |
+
if use_ckpt:
|
| 311 |
+
return torch.utils.checkpoint.checkpoint(
|
| 312 |
+
_checkpointed_layer_forward,
|
| 313 |
+
layer, hs, attention_mask, position_ids, cache_position, cos, sin, bsz,
|
| 314 |
+
cu_seqlens, max_seqlen,
|
| 315 |
+
use_reentrant=False,
|
| 316 |
+
)
|
| 317 |
+
return run_layer(layer, hs)
|
| 318 |
+
|
| 319 |
+
for layer in prelude:
|
| 320 |
+
hidden_states = run_layer_maybe_ckpt(layer, hidden_states)
|
| 321 |
+
|
| 322 |
+
if self.training:
|
| 323 |
+
hidden_states = hidden_states + torch.randn_like(hidden_states) * 0.02
|
| 324 |
+
|
| 325 |
+
for layer in recurrent:
|
| 326 |
+
hidden_states = run_layer_maybe_ckpt(layer, hidden_states)
|
| 327 |
+
|
| 328 |
+
if self.training:
|
| 329 |
+
hidden_states = hidden_states + torch.randn_like(hidden_states) * 0.02
|
| 330 |
+
|
| 331 |
+
for layer in recurrent:
|
| 332 |
+
layer.self_attn._use_recurrent_slot = True
|
| 333 |
+
try:
|
| 334 |
+
hidden_states = run_layer_maybe_ckpt(layer, hidden_states)
|
| 335 |
+
finally:
|
| 336 |
+
layer.self_attn._use_recurrent_slot = False
|
| 337 |
+
|
| 338 |
+
for layer in coda:
|
| 339 |
+
hidden_states = run_layer_maybe_ckpt(layer, hidden_states)
|
| 340 |
+
|
| 341 |
+
hidden_states = self.norm(hidden_states)
|
| 342 |
+
return BaseModelOutputWithPast(last_hidden_state=hidden_states, past_key_values=past_key_values)
|
| 343 |
+
|
| 344 |
+
class SurjoExpForCausalLM(LlamaForCausalLM):
|
| 345 |
+
config_class = SurjoExpConfig
|
| 346 |
+
def __init__(self, config):
|
| 347 |
+
super(LlamaForCausalLM, self).__init__(config)
|
| 348 |
+
self.model = SurjoExpModel(config)
|
| 349 |
+
self.vocab_size = config.vocab_size
|
| 350 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 351 |
+
self.post_init()
|
| 352 |
+
|
| 353 |
+
def gradient_checkpointing_enable(self, **kwargs):
|
| 354 |
+
self.model.gradient_checkpointing_enable()
|
| 355 |
+
|
| 356 |
+
def gradient_checkpointing_disable(self):
|
| 357 |
+
self.model.gradient_checkpointing_disable()
|
| 358 |
+
|
| 359 |
+
def forward(self, input_ids=None, attention_mask=None, labels=None, inputs_embeds=None,
|
| 360 |
+
use_cache=None, num_logits_to_keep=0, position_ids=None, past_key_values=None,
|
| 361 |
+
cache_position=None, cu_seqlens=None, max_seqlen=None, **kwargs):
|
| 362 |
+
if use_cache is None:
|
| 363 |
+
use_cache = False if (self.training or labels is not None) else True
|
| 364 |
+
|
| 365 |
+
if num_logits_to_keep == 0 and "logits_to_keep" in kwargs:
|
| 366 |
+
num_logits_to_keep = kwargs["logits_to_keep"]
|
| 367 |
+
|
| 368 |
+
outputs = self.model(
|
| 369 |
+
input_ids=input_ids,
|
| 370 |
+
attention_mask=attention_mask,
|
| 371 |
+
position_ids=position_ids,
|
| 372 |
+
inputs_embeds=inputs_embeds,
|
| 373 |
+
past_key_values=past_key_values,
|
| 374 |
+
use_cache=use_cache,
|
| 375 |
+
cache_position=cache_position,
|
| 376 |
+
cu_seqlens=cu_seqlens,
|
| 377 |
+
max_seqlen=max_seqlen,
|
| 378 |
+
)
|
| 379 |
+
hidden_states = outputs[0]
|
| 380 |
+
|
| 381 |
+
expected_bsz = input_ids.shape[0] if input_ids is not None else inputs_embeds.shape[0]
|
| 382 |
+
if hidden_states.ndim != 3 or hidden_states.shape[0] != expected_bsz:
|
| 383 |
+
raise RuntimeError(
|
| 384 |
+
f"SurjoExpModel returned hidden_states with shape {tuple(hidden_states.shape)}, "
|
| 385 |
+
f"expected batch size {expected_bsz}."
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
loss = None
|
| 389 |
+
logits = None
|
| 390 |
+
|
| 391 |
+
if labels is not None:
|
| 392 |
+
shift_hidden = hidden_states[..., :-1, :].contiguous()
|
| 393 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 394 |
+
|
| 395 |
+
num_chunks = 8
|
| 396 |
+
h_chunks = shift_hidden.chunk(num_chunks, dim=0)
|
| 397 |
+
l_chunks = shift_labels.chunk(num_chunks, dim=0)
|
| 398 |
+
|
| 399 |
+
total_loss = hidden_states.new_zeros((), dtype=torch.float32)
|
| 400 |
+
total_tokens = 0
|
| 401 |
+
for h_c, l_c in zip(h_chunks, l_chunks):
|
| 402 |
+
logits_c = self.lm_head(h_c)
|
| 403 |
+
chunk_loss = F.cross_entropy(
|
| 404 |
+
logits_c.view(-1, logits_c.size(-1)).float(),
|
| 405 |
+
l_c.view(-1),
|
| 406 |
+
reduction="sum",
|
| 407 |
+
)
|
| 408 |
+
total_loss = total_loss + chunk_loss
|
| 409 |
+
total_tokens += l_c.numel()
|
| 410 |
+
loss = (total_loss / total_tokens).to(hidden_states.dtype)
|
| 411 |
+
else:
|
| 412 |
+
slice_hidden = hidden_states if num_logits_to_keep == 0 else hidden_states[:, -num_logits_to_keep:, :]
|
| 413 |
+
logits = self.lm_head(slice_hidden)
|
| 414 |
+
|
| 415 |
+
return CausalLMOutputWithPast(
|
| 416 |
+
loss=loss, logits=logits, past_key_values=outputs.past_key_values
|
| 417 |
+
)
|
checkpoint-10000/optimizer.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:52923746bd6b294491e770e85e51b877015d27823425f067e6024e491158d4fe
|
| 3 |
+
size 445974859
|
checkpoint-10000/optimizer_1.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c70213e3f4f8c8ec7c17fb5bffbb514a0ed1eddb2c2fec590bac5a6e70b07714
|
| 3 |
+
size 151436195
|
checkpoint-10000/random_states_0.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:51f2bbe831235632f1c726e8e9f5f8a4e86b8103b51a2984152b39aaf92f271f
|
| 3 |
+
size 14821
|
checkpoint-10000/tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
checkpoint-10000/tokenizer_config.json
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"bos_token": "<|bos|>",
|
| 4 |
+
"clean_up_tokenization_spaces": false,
|
| 5 |
+
"eos_token": "<|eos|>",
|
| 6 |
+
"extra_special_tokens": [
|
| 7 |
+
"<|unk|>",
|
| 8 |
+
"<|pad|>",
|
| 9 |
+
"<|bos|>",
|
| 10 |
+
"<|eos|>",
|
| 11 |
+
"<|mask|>",
|
| 12 |
+
"<|im_start|>",
|
| 13 |
+
"<|im_end|>",
|
| 14 |
+
"<|system|>",
|
| 15 |
+
"<|user|>",
|
| 16 |
+
"<|assistant|>",
|
| 17 |
+
"<think>",
|
| 18 |
+
"</think>",
|
| 19 |
+
"<|begin_of_thought|>",
|
| 20 |
+
"<|end_of_thought|>",
|
| 21 |
+
"<answer>",
|
| 22 |
+
"</answer>",
|
| 23 |
+
"<|step|>",
|
| 24 |
+
"<|/step|>",
|
| 25 |
+
"<context>",
|
| 26 |
+
"</context>",
|
| 27 |
+
"<|doc_start|>",
|
| 28 |
+
"<|doc_end|>",
|
| 29 |
+
"<|search|>",
|
| 30 |
+
"<|search_results|>",
|
| 31 |
+
"<|tool_list_start|>",
|
| 32 |
+
"<|tool_list_end|>",
|
| 33 |
+
"<tools>",
|
| 34 |
+
"</tools>",
|
| 35 |
+
"<|tool_call_start|>",
|
| 36 |
+
"<|tool_call_end|>",
|
| 37 |
+
"<|tool_call|>",
|
| 38 |
+
"<|/tool_call|>",
|
| 39 |
+
"<|tool_response_start|>",
|
| 40 |
+
"<|tool_response_end|>",
|
| 41 |
+
"<|tool_response|>",
|
| 42 |
+
"<|/tool_response|>",
|
| 43 |
+
"<|image|>",
|
| 44 |
+
"<|image_pad|>",
|
| 45 |
+
"<|image_placeholder|>",
|
| 46 |
+
"<|audio|>",
|
| 47 |
+
"<|audio_pad|>",
|
| 48 |
+
"<|audio_placeholder|>",
|
| 49 |
+
"<|video|>",
|
| 50 |
+
"<|video_pad|>",
|
| 51 |
+
"<|fim_prefix|>",
|
| 52 |
+
"<|fim_suffix|>",
|
| 53 |
+
"<|fim_middle|>",
|
| 54 |
+
"<|repo_name|>",
|
| 55 |
+
"<|file_separator|>",
|
| 56 |
+
"<|reward|>",
|
| 57 |
+
"<|reserved_0|>",
|
| 58 |
+
"<|reserved_1|>",
|
| 59 |
+
"<|reserved_2|>",
|
| 60 |
+
"<|reserved_3|>",
|
| 61 |
+
"<|reserved_4|>",
|
| 62 |
+
"<|reserved_5|>",
|
| 63 |
+
"<|reserved_6|>",
|
| 64 |
+
"<|reserved_7|>",
|
| 65 |
+
"<|reserved_8|>",
|
| 66 |
+
"<|reserved_9|>",
|
| 67 |
+
"<|reserved_10|>",
|
| 68 |
+
"<|reserved_11|>",
|
| 69 |
+
"<|reserved_12|>",
|
| 70 |
+
"<|reserved_13|>",
|
| 71 |
+
"<|reserved_14|>",
|
| 72 |
+
"<|reserved_15|>",
|
| 73 |
+
"<|reserved_16|>",
|
| 74 |
+
"<|reserved_17|>",
|
| 75 |
+
"<|reserved_18|>",
|
| 76 |
+
"<|reserved_19|>"
|
| 77 |
+
],
|
| 78 |
+
"is_local": false,
|
| 79 |
+
"local_files_only": false,
|
| 80 |
+
"mask_token": "<|mask|>",
|
| 81 |
+
"model_max_length": 10000000,
|
| 82 |
+
"pad_token": "<|pad|>",
|
| 83 |
+
"tokenizer_class": "TokenizersBackend",
|
| 84 |
+
"unk_token": "<|unk|>"
|
| 85 |
+
}
|
checkpoint-11000/chat_template.jinja
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{ bos_token }}{% for message in messages %}{{ '<|im_start|>' + message['role'] + '
|
| 2 |
+
' + message['content'] + '<|im_end|>
|
| 3 |
+
' }}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant
|
| 4 |
+
' }}{% endif %}
|
checkpoint-11000/config.json
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"SurjoExpForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"attention_bias": false,
|
| 6 |
+
"attention_dropout": 0.0,
|
| 7 |
+
"auto_map": {
|
| 8 |
+
"AutoConfig": "configuration_surjo_exp.SurjoExpConfig",
|
| 9 |
+
"AutoModelForCausalLM": "modeling_surjo_exp.SurjoExpForCausalLM"
|
| 10 |
+
},
|
| 11 |
+
"bos_token_id": 0,
|
| 12 |
+
"coda_layers": 16,
|
| 13 |
+
"dtype": "float32",
|
| 14 |
+
"eos_token_id": 2,
|
| 15 |
+
"gradient_checkpointing": false,
|
| 16 |
+
"head_dim": 72,
|
| 17 |
+
"hidden_act": "silu",
|
| 18 |
+
"hidden_size": 576,
|
| 19 |
+
"initializer_range": 0.02,
|
| 20 |
+
"intermediate_size": 1536,
|
| 21 |
+
"max_position_embeddings": 2048,
|
| 22 |
+
"mlp_bias": false,
|
| 23 |
+
"model_type": "surjo_exp",
|
| 24 |
+
"num_attention_heads": 8,
|
| 25 |
+
"num_hidden_layers": 32,
|
| 26 |
+
"num_key_value_heads": 2,
|
| 27 |
+
"pad_token_id": 1,
|
| 28 |
+
"prelude_layers": 4,
|
| 29 |
+
"pretraining_tp": 1,
|
| 30 |
+
"recurrent_layers": 12,
|
| 31 |
+
"rms_norm_eps": 1e-05,
|
| 32 |
+
"rope_parameters": {
|
| 33 |
+
"rope_theta": 10000.0,
|
| 34 |
+
"rope_type": "default"
|
| 35 |
+
},
|
| 36 |
+
"rope_theta": 10000.0,
|
| 37 |
+
"tie_word_embeddings": true,
|
| 38 |
+
"transformers_version": "5.15.0",
|
| 39 |
+
"use_cache": false,
|
| 40 |
+
"use_flash_attn": false,
|
| 41 |
+
"vocab_size": 32768,
|
| 42 |
+
"xsa_projection": true
|
| 43 |
+
}
|
checkpoint-11000/configuration_surjo_exp.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from transformers import LlamaConfig
|
| 3 |
+
|
| 4 |
+
class SurjoExpConfig(LlamaConfig):
|
| 5 |
+
model_type = "surjo_exp"
|
| 6 |
+
def __init__(self, *args, xsa_projection=True, rope_theta=10000.0, attention_bias=False,
|
| 7 |
+
prelude_layers=4, recurrent_layers=12, coda_layers=16,
|
| 8 |
+
gradient_checkpointing=True, use_flash_attn=True, **kwargs):
|
| 9 |
+
kwargs["num_hidden_layers"] = prelude_layers + recurrent_layers + coda_layers
|
| 10 |
+
kwargs.setdefault("use_cache", False)
|
| 11 |
+
super().__init__(*args, rope_theta=rope_theta, attention_bias=attention_bias, **kwargs)
|
| 12 |
+
self.xsa_projection = xsa_projection
|
| 13 |
+
self.rope_theta = rope_theta
|
| 14 |
+
self.attention_bias = attention_bias
|
| 15 |
+
self.prelude_layers = prelude_layers
|
| 16 |
+
self.recurrent_layers = recurrent_layers
|
| 17 |
+
self.coda_layers = coda_layers
|
| 18 |
+
self.gradient_checkpointing = gradient_checkpointing
|
| 19 |
+
self.use_flash_attn = use_flash_attn
|
| 20 |
+
if not hasattr(self, 'rope_parameters') or self.rope_parameters is None:
|
| 21 |
+
self.rope_parameters = {"rope_type": "default", "factor": 1.0, "rope_theta": rope_theta}
|
checkpoint-11000/generation_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 0,
|
| 4 |
+
"eos_token_id": 2,
|
| 5 |
+
"output_attentions": false,
|
| 6 |
+
"output_hidden_states": false,
|
| 7 |
+
"pad_token_id": 1,
|
| 8 |
+
"transformers_version": "5.15.0",
|
| 9 |
+
"use_cache": false
|
| 10 |
+
}
|
checkpoint-11000/model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:364e0f2993344f4f9827a7473270efa28ff31761630174e2b1711c1105565580
|
| 3 |
+
size 521611856
|
checkpoint-11000/modeling_surjo_exp.py
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import torch.utils.checkpoint
|
| 6 |
+
from transformers import LlamaConfig, LlamaModel, LlamaForCausalLM
|
| 7 |
+
from transformers.models.llama.modeling_llama import LlamaRMSNorm
|
| 8 |
+
from transformers.models.llama.modeling_llama import LlamaMLP
|
| 9 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 10 |
+
from transformers.models.llama.modeling_llama import LlamaRotaryEmbedding, apply_rotary_pos_emb
|
| 11 |
+
from transformers.cache_utils import DynamicCache
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
from .configuration_surjo_exp import SurjoExpConfig
|
| 15 |
+
except ImportError:
|
| 16 |
+
from configuration_surjo_exp import SurjoExpConfig
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
from flash_attn import flash_attn_varlen_func
|
| 20 |
+
FLASH_ATTN_AVAILABLE = True
|
| 21 |
+
except ImportError:
|
| 22 |
+
FLASH_ATTN_AVAILABLE = False
|
| 23 |
+
|
| 24 |
+
@torch._dynamo.disable()
|
| 25 |
+
def _flash_varlen(q, k, v, cu_seqlens, max_seqlen, dropout_p):
|
| 26 |
+
ms = int(max_seqlen.item()) if torch.is_tensor(max_seqlen) else int(max_seqlen)
|
| 27 |
+
return flash_attn_varlen_func(
|
| 28 |
+
q, k, v, cu_seqlens, cu_seqlens, ms, ms,
|
| 29 |
+
dropout_p=dropout_p, causal=True,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
class ClampedLlamaMLP(LlamaMLP):
|
| 33 |
+
def forward(self, x):
|
| 34 |
+
gate = F.silu(self.gate_proj(x).clamp(-15.0, 15.0))
|
| 35 |
+
up = self.up_proj(x)
|
| 36 |
+
return self.down_proj(gate * up)
|
| 37 |
+
|
| 38 |
+
class XSAAttention(nn.Module):
|
| 39 |
+
def __init__(self, config, layer_idx=None):
|
| 40 |
+
super().__init__()
|
| 41 |
+
self.config = config
|
| 42 |
+
self.layer_idx = layer_idx
|
| 43 |
+
self.recurrent_cache_idx = None
|
| 44 |
+
self._use_recurrent_slot = False
|
| 45 |
+
self.hidden_size = config.hidden_size
|
| 46 |
+
self.num_heads = config.num_attention_heads
|
| 47 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 48 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 49 |
+
self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
|
| 50 |
+
self.attention_bias = getattr(config, "attention_bias", False)
|
| 51 |
+
|
| 52 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=self.attention_bias)
|
| 53 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=self.attention_bias)
|
| 54 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=self.attention_bias)
|
| 55 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=self.attention_bias)
|
| 56 |
+
|
| 57 |
+
self.q_norm = LlamaRMSNorm(self.head_dim, eps=1e-6)
|
| 58 |
+
self.k_norm = LlamaRMSNorm(self.head_dim, eps=1e-6)
|
| 59 |
+
|
| 60 |
+
def forward(self, hidden_states, attention_mask=None, position_ids=None, past_key_value=None,
|
| 61 |
+
output_attentions=False, use_cache=False, cache_position=None, position_embeddings=None,
|
| 62 |
+
expected_batch_size=None, cu_seqlens=None, max_seqlen=None, **kwargs):
|
| 63 |
+
past_kv = past_key_value if past_key_value is not None else kwargs.get("past_key_values", None)
|
| 64 |
+
|
| 65 |
+
if hidden_states.ndim == 2:
|
| 66 |
+
if expected_batch_size is None:
|
| 67 |
+
raise RuntimeError(
|
| 68 |
+
f"XSAAttention received 2D hidden_states {hidden_states.shape} "
|
| 69 |
+
f"without an expected_batch_size to safely restore the batch dim."
|
| 70 |
+
)
|
| 71 |
+
hidden_states = hidden_states.reshape(expected_batch_size, -1, self.hidden_size)
|
| 72 |
+
|
| 73 |
+
bsz, q_len, _ = hidden_states.size()
|
| 74 |
+
|
| 75 |
+
if expected_batch_size is not None and bsz != expected_batch_size:
|
| 76 |
+
raise RuntimeError(
|
| 77 |
+
f"XSAAttention: hidden_states batch size {bsz} does not match "
|
| 78 |
+
f"expected_batch_size {expected_batch_size}."
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim)
|
| 82 |
+
key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim)
|
| 83 |
+
value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim)
|
| 84 |
+
|
| 85 |
+
query_states = self.q_norm(query_states)
|
| 86 |
+
key_states = self.k_norm(key_states)
|
| 87 |
+
|
| 88 |
+
cos, sin = position_embeddings
|
| 89 |
+
|
| 90 |
+
use_flash = (
|
| 91 |
+
cu_seqlens is not None
|
| 92 |
+
and past_kv is None
|
| 93 |
+
and getattr(self.config, "use_flash_attn", False)
|
| 94 |
+
and FLASH_ATTN_AVAILABLE
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
if use_flash:
|
| 98 |
+
total = bsz * q_len
|
| 99 |
+
q = query_states.reshape(total, self.num_heads, self.head_dim)
|
| 100 |
+
k = key_states.reshape(total, self.num_key_value_heads, self.head_dim)
|
| 101 |
+
v = value_states.reshape(total, self.num_key_value_heads, self.head_dim)
|
| 102 |
+
|
| 103 |
+
q = q.to(torch.bfloat16)
|
| 104 |
+
k = k.to(torch.bfloat16)
|
| 105 |
+
v = v.to(torch.bfloat16)
|
| 106 |
+
|
| 107 |
+
cos_f = cos.reshape(-1, cos.shape[-1]).to(torch.bfloat16)
|
| 108 |
+
sin_f = sin.reshape(-1, sin.shape[-1]).to(torch.bfloat16)
|
| 109 |
+
q, k = apply_rotary_pos_emb(q, k, cos_f, sin_f, unsqueeze_dim=1)
|
| 110 |
+
|
| 111 |
+
attn_output = _flash_varlen(
|
| 112 |
+
q, k, v, cu_seqlens, max_seqlen,
|
| 113 |
+
self.config.attention_dropout if self.training else 0.0,
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
if getattr(self.config, 'xsa_projection', True):
|
| 117 |
+
y = attn_output.view(total, self.num_key_value_heads, self.num_key_value_groups, self.head_dim)
|
| 118 |
+
v_grouped = v.unsqueeze(2)
|
| 119 |
+
dot_yv = (y * v_grouped).sum(dim=-1, keepdim=True).float()
|
| 120 |
+
dot_vv = v_grouped.pow(2).sum(dim=-1, keepdim=True).clamp_min(1e-4).float()
|
| 121 |
+
scale = (dot_yv / dot_vv).to(y.dtype)
|
| 122 |
+
attn_output = (y - scale * v_grouped).reshape(total, self.num_heads, self.head_dim)
|
| 123 |
+
|
| 124 |
+
attn_output = self.o_proj(attn_output.reshape(bsz, q_len, self.hidden_size))
|
| 125 |
+
return (attn_output, None)
|
| 126 |
+
|
| 127 |
+
query_states = query_states.transpose(1, 2)
|
| 128 |
+
key_states = key_states.transpose(1, 2)
|
| 129 |
+
value_states = value_states.transpose(1, 2)
|
| 130 |
+
|
| 131 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 132 |
+
|
| 133 |
+
current_v = value_states
|
| 134 |
+
|
| 135 |
+
target_idx = self.layer_idx
|
| 136 |
+
if self._use_recurrent_slot and self.recurrent_cache_idx is not None:
|
| 137 |
+
target_idx = self.recurrent_cache_idx
|
| 138 |
+
|
| 139 |
+
if past_kv is not None:
|
| 140 |
+
while len(past_kv) <= target_idx:
|
| 141 |
+
past_kv.update(
|
| 142 |
+
torch.empty(bsz, self.num_key_value_heads, 0, self.head_dim, dtype=key_states.dtype, device=key_states.device),
|
| 143 |
+
torch.empty(bsz, self.num_key_value_heads, 0, self.head_dim, dtype=value_states.dtype, device=value_states.device),
|
| 144 |
+
len(past_kv)
|
| 145 |
+
)
|
| 146 |
+
key_states, value_states = past_kv.update(key_states, value_states, target_idx)
|
| 147 |
+
|
| 148 |
+
key_states = key_states.repeat_interleave(self.num_key_value_groups, dim=1)
|
| 149 |
+
value_states = value_states.repeat_interleave(self.num_key_value_groups, dim=1)
|
| 150 |
+
|
| 151 |
+
kv_len = key_states.shape[-2]
|
| 152 |
+
|
| 153 |
+
if attention_mask is not None:
|
| 154 |
+
if attention_mask.ndim == 2:
|
| 155 |
+
if attention_mask.shape[-1] < kv_len:
|
| 156 |
+
attention_mask = F.pad(attention_mask, (0, kv_len - attention_mask.shape[-1]), value=1)
|
| 157 |
+
elif attention_mask.shape[-1] > kv_len:
|
| 158 |
+
attention_mask = attention_mask[:, -kv_len:]
|
| 159 |
+
|
| 160 |
+
pad_mask = (1.0 - attention_mask[:, None, None, :].to(query_states.dtype)) * torch.finfo(query_states.dtype).min
|
| 161 |
+
|
| 162 |
+
if q_len > 1:
|
| 163 |
+
if cache_position is None:
|
| 164 |
+
cache_position = torch.arange(kv_len - q_len, kv_len, device=query_states.device)
|
| 165 |
+
kv_positions = torch.arange(kv_len, device=query_states.device)
|
| 166 |
+
|
| 167 |
+
neg_inf = torch.finfo(query_states.dtype).min
|
| 168 |
+
causal_mask = torch.zeros((q_len, kv_len), dtype=query_states.dtype, device=query_states.device)
|
| 169 |
+
causal_mask = causal_mask.masked_fill(kv_positions[None, :] > cache_position[:, None], neg_inf)
|
| 170 |
+
attn_mask = causal_mask[None, None, :, :] + pad_mask
|
| 171 |
+
|
| 172 |
+
diag_idx = torch.arange(q_len, device=attn_mask.device)
|
| 173 |
+
start_idx = attn_mask.shape[-1] - q_len
|
| 174 |
+
attn_mask[:, :, diag_idx, start_idx + diag_idx] = 0.0
|
| 175 |
+
else:
|
| 176 |
+
attn_mask = pad_mask
|
| 177 |
+
else:
|
| 178 |
+
if attention_mask.shape[0] != bsz:
|
| 179 |
+
raise RuntimeError(
|
| 180 |
+
f"attention_mask batch size {attention_mask.shape[0]} does not "
|
| 181 |
+
f"match hidden_states batch size {bsz}."
|
| 182 |
+
)
|
| 183 |
+
attn_mask = attention_mask.to(dtype=query_states.dtype)
|
| 184 |
+
is_causal = False
|
| 185 |
+
else:
|
| 186 |
+
is_causal = True
|
| 187 |
+
attn_mask = None
|
| 188 |
+
|
| 189 |
+
attn_output = F.scaled_dot_product_attention(
|
| 190 |
+
query_states, key_states, value_states, attn_mask=attn_mask,
|
| 191 |
+
dropout_p=0.0 if not self.training else self.config.attention_dropout, is_causal=is_causal
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
if getattr(self.config, 'xsa_projection', True):
|
| 195 |
+
y = attn_output.reshape(bsz, self.num_key_value_heads, self.num_key_value_groups, q_len, self.head_dim)
|
| 196 |
+
v_grouped = current_v.unsqueeze(2)
|
| 197 |
+
dot_yv = (y * v_grouped).sum(dim=-1, keepdim=True).float()
|
| 198 |
+
dot_vv = v_grouped.pow(2).sum(dim=-1, keepdim=True).clamp_min(1e-4).float()
|
| 199 |
+
scale = (dot_yv / dot_vv).to(y.dtype)
|
| 200 |
+
attn_output = (y - scale * v_grouped).reshape(bsz, self.num_heads, q_len, self.head_dim)
|
| 201 |
+
|
| 202 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 203 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
| 204 |
+
attn_output = self.o_proj(attn_output)
|
| 205 |
+
|
| 206 |
+
return (attn_output, None)
|
| 207 |
+
|
| 208 |
+
@torch._dynamo.disable()
|
| 209 |
+
def _checkpointed_layer_forward(layer, hidden_states, attention_mask, position_ids,
|
| 210 |
+
cache_position, cos, sin, expected_batch_size, cu_seqlens, max_seqlen):
|
| 211 |
+
out = layer(
|
| 212 |
+
hidden_states, attention_mask=attention_mask, position_ids=position_ids,
|
| 213 |
+
past_key_value=None, use_cache=False,
|
| 214 |
+
cache_position=cache_position, position_embeddings=(cos, sin),
|
| 215 |
+
expected_batch_size=expected_batch_size,
|
| 216 |
+
cu_seqlens=cu_seqlens, max_seqlen=max_seqlen,
|
| 217 |
+
)
|
| 218 |
+
hs_out = out[0] if isinstance(out, tuple) else out
|
| 219 |
+
if hs_out.ndim != 3 or hs_out.shape[0] != expected_batch_size:
|
| 220 |
+
raise RuntimeError(
|
| 221 |
+
f"Layer output shape {tuple(hs_out.shape)} does not match expected "
|
| 222 |
+
f"batch size {expected_batch_size}."
|
| 223 |
+
)
|
| 224 |
+
return hs_out
|
| 225 |
+
|
| 226 |
+
class SurjoExpModel(LlamaModel):
|
| 227 |
+
def __init__(self, config):
|
| 228 |
+
super().__init__(config)
|
| 229 |
+
|
| 230 |
+
assert config.prelude_layers + config.recurrent_layers + config.coda_layers == config.num_hidden_layers, \
|
| 231 |
+
"prelude_layers + recurrent_layers + coda_layers must equal num_hidden_layers"
|
| 232 |
+
|
| 233 |
+
if getattr(config, "use_flash_attn", False) and not FLASH_ATTN_AVAILABLE:
|
| 234 |
+
raise ImportError(
|
| 235 |
+
"config.use_flash_attn=True but flash_attn is not importable. "
|
| 236 |
+
"Install the FA2 wheel or set use_flash_attn=False."
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
p1 = config.prelude_layers
|
| 240 |
+
r1 = p1 + config.recurrent_layers
|
| 241 |
+
|
| 242 |
+
for i, layer in enumerate(self.layers):
|
| 243 |
+
layer.self_attn = XSAAttention(config, layer_idx=i)
|
| 244 |
+
layer.mlp = ClampedLlamaMLP(config)
|
| 245 |
+
|
| 246 |
+
for i, layer in enumerate(self.layers[p1:r1]):
|
| 247 |
+
layer.self_attn.recurrent_cache_idx = config.num_hidden_layers + p1 + i
|
| 248 |
+
|
| 249 |
+
self.gradient_checkpointing = getattr(config, "gradient_checkpointing", True)
|
| 250 |
+
|
| 251 |
+
def gradient_checkpointing_enable(self):
|
| 252 |
+
self.gradient_checkpointing = True
|
| 253 |
+
|
| 254 |
+
def gradient_checkpointing_disable(self):
|
| 255 |
+
self.gradient_checkpointing = False
|
| 256 |
+
|
| 257 |
+
def forward(self, input_ids=None, attention_mask=None, position_ids=None, inputs_embeds=None,
|
| 258 |
+
past_key_values=None, use_cache=None, output_attentions=False, output_hidden_states=False,
|
| 259 |
+
cache_position=None, return_dict=True, cu_seqlens=None, max_seqlen=None, **kwargs):
|
| 260 |
+
if use_cache is None:
|
| 261 |
+
use_cache = False
|
| 262 |
+
|
| 263 |
+
if inputs_embeds is None:
|
| 264 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 265 |
+
|
| 266 |
+
bsz, seq_len = inputs_embeds.shape[0], inputs_embeds.shape[1]
|
| 267 |
+
|
| 268 |
+
if cache_position is None:
|
| 269 |
+
past_seen = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 270 |
+
cache_position = torch.arange(past_seen, past_seen + seq_len, dtype=torch.long, device=inputs_embeds.device)
|
| 271 |
+
if position_ids is None:
|
| 272 |
+
position_ids = cache_position.unsqueeze(0).expand(bsz, -1)
|
| 273 |
+
|
| 274 |
+
hidden_states = inputs_embeds
|
| 275 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 276 |
+
cos, sin = position_embeddings
|
| 277 |
+
|
| 278 |
+
if use_cache and past_key_values is None:
|
| 279 |
+
past_key_values = DynamicCache()
|
| 280 |
+
|
| 281 |
+
p1 = self.config.prelude_layers
|
| 282 |
+
r1 = p1 + self.config.recurrent_layers
|
| 283 |
+
c1 = r1 + self.config.coda_layers
|
| 284 |
+
|
| 285 |
+
prelude = self.layers[:p1]
|
| 286 |
+
recurrent = self.layers[p1:r1]
|
| 287 |
+
coda = self.layers[r1:c1]
|
| 288 |
+
|
| 289 |
+
use_ckpt = self.training and self.gradient_checkpointing and not use_cache
|
| 290 |
+
|
| 291 |
+
def run_layer(layer, hs):
|
| 292 |
+
if cu_seqlens is not None:
|
| 293 |
+
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
| 294 |
+
|
| 295 |
+
out = layer(
|
| 296 |
+
hs, attention_mask=attention_mask, position_ids=position_ids,
|
| 297 |
+
past_key_value=past_key_values if use_cache else None, use_cache=use_cache,
|
| 298 |
+
cache_position=cache_position, position_embeddings=position_embeddings,
|
| 299 |
+
expected_batch_size=bsz, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen,
|
| 300 |
+
)
|
| 301 |
+
hs_out = out[0] if isinstance(out, tuple) else out
|
| 302 |
+
if hs_out.ndim != 3 or hs_out.shape[0] != bsz:
|
| 303 |
+
raise RuntimeError(
|
| 304 |
+
f"Layer output shape {tuple(hs_out.shape)} does not match expected "
|
| 305 |
+
f"batch size {bsz}."
|
| 306 |
+
)
|
| 307 |
+
return hs_out
|
| 308 |
+
|
| 309 |
+
def run_layer_maybe_ckpt(layer, hs):
|
| 310 |
+
if use_ckpt:
|
| 311 |
+
return torch.utils.checkpoint.checkpoint(
|
| 312 |
+
_checkpointed_layer_forward,
|
| 313 |
+
layer, hs, attention_mask, position_ids, cache_position, cos, sin, bsz,
|
| 314 |
+
cu_seqlens, max_seqlen,
|
| 315 |
+
use_reentrant=False,
|
| 316 |
+
)
|
| 317 |
+
return run_layer(layer, hs)
|
| 318 |
+
|
| 319 |
+
for layer in prelude:
|
| 320 |
+
hidden_states = run_layer_maybe_ckpt(layer, hidden_states)
|
| 321 |
+
|
| 322 |
+
if self.training:
|
| 323 |
+
hidden_states = hidden_states + torch.randn_like(hidden_states) * 0.02
|
| 324 |
+
|
| 325 |
+
for layer in recurrent:
|
| 326 |
+
hidden_states = run_layer_maybe_ckpt(layer, hidden_states)
|
| 327 |
+
|
| 328 |
+
if self.training:
|
| 329 |
+
hidden_states = hidden_states + torch.randn_like(hidden_states) * 0.02
|
| 330 |
+
|
| 331 |
+
for layer in recurrent:
|
| 332 |
+
layer.self_attn._use_recurrent_slot = True
|
| 333 |
+
try:
|
| 334 |
+
hidden_states = run_layer_maybe_ckpt(layer, hidden_states)
|
| 335 |
+
finally:
|
| 336 |
+
layer.self_attn._use_recurrent_slot = False
|
| 337 |
+
|
| 338 |
+
for layer in coda:
|
| 339 |
+
hidden_states = run_layer_maybe_ckpt(layer, hidden_states)
|
| 340 |
+
|
| 341 |
+
hidden_states = self.norm(hidden_states)
|
| 342 |
+
return BaseModelOutputWithPast(last_hidden_state=hidden_states, past_key_values=past_key_values)
|
| 343 |
+
|
| 344 |
+
class SurjoExpForCausalLM(LlamaForCausalLM):
|
| 345 |
+
config_class = SurjoExpConfig
|
| 346 |
+
def __init__(self, config):
|
| 347 |
+
super(LlamaForCausalLM, self).__init__(config)
|
| 348 |
+
self.model = SurjoExpModel(config)
|
| 349 |
+
self.vocab_size = config.vocab_size
|
| 350 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 351 |
+
self.post_init()
|
| 352 |
+
|
| 353 |
+
def gradient_checkpointing_enable(self, **kwargs):
|
| 354 |
+
self.model.gradient_checkpointing_enable()
|
| 355 |
+
|
| 356 |
+
def gradient_checkpointing_disable(self):
|
| 357 |
+
self.model.gradient_checkpointing_disable()
|
| 358 |
+
|
| 359 |
+
def forward(self, input_ids=None, attention_mask=None, labels=None, inputs_embeds=None,
|
| 360 |
+
use_cache=None, num_logits_to_keep=0, position_ids=None, past_key_values=None,
|
| 361 |
+
cache_position=None, cu_seqlens=None, max_seqlen=None, **kwargs):
|
| 362 |
+
if use_cache is None:
|
| 363 |
+
use_cache = False if (self.training or labels is not None) else True
|
| 364 |
+
|
| 365 |
+
if num_logits_to_keep == 0 and "logits_to_keep" in kwargs:
|
| 366 |
+
num_logits_to_keep = kwargs["logits_to_keep"]
|
| 367 |
+
|
| 368 |
+
outputs = self.model(
|
| 369 |
+
input_ids=input_ids,
|
| 370 |
+
attention_mask=attention_mask,
|
| 371 |
+
position_ids=position_ids,
|
| 372 |
+
inputs_embeds=inputs_embeds,
|
| 373 |
+
past_key_values=past_key_values,
|
| 374 |
+
use_cache=use_cache,
|
| 375 |
+
cache_position=cache_position,
|
| 376 |
+
cu_seqlens=cu_seqlens,
|
| 377 |
+
max_seqlen=max_seqlen,
|
| 378 |
+
)
|
| 379 |
+
hidden_states = outputs[0]
|
| 380 |
+
|
| 381 |
+
expected_bsz = input_ids.shape[0] if input_ids is not None else inputs_embeds.shape[0]
|
| 382 |
+
if hidden_states.ndim != 3 or hidden_states.shape[0] != expected_bsz:
|
| 383 |
+
raise RuntimeError(
|
| 384 |
+
f"SurjoExpModel returned hidden_states with shape {tuple(hidden_states.shape)}, "
|
| 385 |
+
f"expected batch size {expected_bsz}."
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
loss = None
|
| 389 |
+
logits = None
|
| 390 |
+
|
| 391 |
+
if labels is not None:
|
| 392 |
+
shift_hidden = hidden_states[..., :-1, :].contiguous()
|
| 393 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 394 |
+
|
| 395 |
+
num_chunks = 8
|
| 396 |
+
h_chunks = shift_hidden.chunk(num_chunks, dim=0)
|
| 397 |
+
l_chunks = shift_labels.chunk(num_chunks, dim=0)
|
| 398 |
+
|
| 399 |
+
total_loss = hidden_states.new_zeros((), dtype=torch.float32)
|
| 400 |
+
total_tokens = 0
|
| 401 |
+
for h_c, l_c in zip(h_chunks, l_chunks):
|
| 402 |
+
logits_c = self.lm_head(h_c)
|
| 403 |
+
chunk_loss = F.cross_entropy(
|
| 404 |
+
logits_c.view(-1, logits_c.size(-1)).float(),
|
| 405 |
+
l_c.view(-1),
|
| 406 |
+
reduction="sum",
|
| 407 |
+
)
|
| 408 |
+
total_loss = total_loss + chunk_loss
|
| 409 |
+
total_tokens += l_c.numel()
|
| 410 |
+
loss = (total_loss / total_tokens).to(hidden_states.dtype)
|
| 411 |
+
else:
|
| 412 |
+
slice_hidden = hidden_states if num_logits_to_keep == 0 else hidden_states[:, -num_logits_to_keep:, :]
|
| 413 |
+
logits = self.lm_head(slice_hidden)
|
| 414 |
+
|
| 415 |
+
return CausalLMOutputWithPast(
|
| 416 |
+
loss=loss, logits=logits, past_key_values=outputs.past_key_values
|
| 417 |
+
)
|
checkpoint-11000/optimizer.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:89b2b996a07860411d1fef923ec7e9483b91b32691d3e4544564065c9afd7ae1
|
| 3 |
+
size 445974859
|
checkpoint-11000/optimizer_1.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ffcc4fe3a6a7fd0615f39a9d27ee89932aa2df12f06d202734d3b47da8aa7d08
|
| 3 |
+
size 151436195
|
checkpoint-11000/random_states_0.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fd3103a4aa1fde4e32d9f2a7ebd53444025eb127a18e70df37815deebd18185c
|
| 3 |
+
size 14821
|
checkpoint-11000/tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
checkpoint-11000/tokenizer_config.json
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"bos_token": "<|bos|>",
|
| 4 |
+
"clean_up_tokenization_spaces": false,
|
| 5 |
+
"eos_token": "<|eos|>",
|
| 6 |
+
"extra_special_tokens": [
|
| 7 |
+
"<|unk|>",
|
| 8 |
+
"<|pad|>",
|
| 9 |
+
"<|bos|>",
|
| 10 |
+
"<|eos|>",
|
| 11 |
+
"<|mask|>",
|
| 12 |
+
"<|im_start|>",
|
| 13 |
+
"<|im_end|>",
|
| 14 |
+
"<|system|>",
|
| 15 |
+
"<|user|>",
|
| 16 |
+
"<|assistant|>",
|
| 17 |
+
"<think>",
|
| 18 |
+
"</think>",
|
| 19 |
+
"<|begin_of_thought|>",
|
| 20 |
+
"<|end_of_thought|>",
|
| 21 |
+
"<answer>",
|
| 22 |
+
"</answer>",
|
| 23 |
+
"<|step|>",
|
| 24 |
+
"<|/step|>",
|
| 25 |
+
"<context>",
|
| 26 |
+
"</context>",
|
| 27 |
+
"<|doc_start|>",
|
| 28 |
+
"<|doc_end|>",
|
| 29 |
+
"<|search|>",
|
| 30 |
+
"<|search_results|>",
|
| 31 |
+
"<|tool_list_start|>",
|
| 32 |
+
"<|tool_list_end|>",
|
| 33 |
+
"<tools>",
|
| 34 |
+
"</tools>",
|
| 35 |
+
"<|tool_call_start|>",
|
| 36 |
+
"<|tool_call_end|>",
|
| 37 |
+
"<|tool_call|>",
|
| 38 |
+
"<|/tool_call|>",
|
| 39 |
+
"<|tool_response_start|>",
|
| 40 |
+
"<|tool_response_end|>",
|
| 41 |
+
"<|tool_response|>",
|
| 42 |
+
"<|/tool_response|>",
|
| 43 |
+
"<|image|>",
|
| 44 |
+
"<|image_pad|>",
|
| 45 |
+
"<|image_placeholder|>",
|
| 46 |
+
"<|audio|>",
|
| 47 |
+
"<|audio_pad|>",
|
| 48 |
+
"<|audio_placeholder|>",
|
| 49 |
+
"<|video|>",
|
| 50 |
+
"<|video_pad|>",
|
| 51 |
+
"<|fim_prefix|>",
|
| 52 |
+
"<|fim_suffix|>",
|
| 53 |
+
"<|fim_middle|>",
|
| 54 |
+
"<|repo_name|>",
|
| 55 |
+
"<|file_separator|>",
|
| 56 |
+
"<|reward|>",
|
| 57 |
+
"<|reserved_0|>",
|
| 58 |
+
"<|reserved_1|>",
|
| 59 |
+
"<|reserved_2|>",
|
| 60 |
+
"<|reserved_3|>",
|
| 61 |
+
"<|reserved_4|>",
|
| 62 |
+
"<|reserved_5|>",
|
| 63 |
+
"<|reserved_6|>",
|
| 64 |
+
"<|reserved_7|>",
|
| 65 |
+
"<|reserved_8|>",
|
| 66 |
+
"<|reserved_9|>",
|
| 67 |
+
"<|reserved_10|>",
|
| 68 |
+
"<|reserved_11|>",
|
| 69 |
+
"<|reserved_12|>",
|
| 70 |
+
"<|reserved_13|>",
|
| 71 |
+
"<|reserved_14|>",
|
| 72 |
+
"<|reserved_15|>",
|
| 73 |
+
"<|reserved_16|>",
|
| 74 |
+
"<|reserved_17|>",
|
| 75 |
+
"<|reserved_18|>",
|
| 76 |
+
"<|reserved_19|>"
|
| 77 |
+
],
|
| 78 |
+
"is_local": false,
|
| 79 |
+
"local_files_only": false,
|
| 80 |
+
"mask_token": "<|mask|>",
|
| 81 |
+
"model_max_length": 10000000,
|
| 82 |
+
"pad_token": "<|pad|>",
|
| 83 |
+
"tokenizer_class": "TokenizersBackend",
|
| 84 |
+
"unk_token": "<|unk|>"
|
| 85 |
+
}
|
checkpoint-12000/chat_template.jinja
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{ bos_token }}{% for message in messages %}{{ '<|im_start|>' + message['role'] + '
|
| 2 |
+
' + message['content'] + '<|im_end|>
|
| 3 |
+
' }}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant
|
| 4 |
+
' }}{% endif %}
|
checkpoint-12000/config.json
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"SurjoExpForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"attention_bias": false,
|
| 6 |
+
"attention_dropout": 0.0,
|
| 7 |
+
"auto_map": {
|
| 8 |
+
"AutoConfig": "configuration_surjo_exp.SurjoExpConfig",
|
| 9 |
+
"AutoModelForCausalLM": "modeling_surjo_exp.SurjoExpForCausalLM"
|
| 10 |
+
},
|
| 11 |
+
"bos_token_id": 0,
|
| 12 |
+
"coda_layers": 16,
|
| 13 |
+
"dtype": "float32",
|
| 14 |
+
"eos_token_id": 2,
|
| 15 |
+
"gradient_checkpointing": false,
|
| 16 |
+
"head_dim": 72,
|
| 17 |
+
"hidden_act": "silu",
|
| 18 |
+
"hidden_size": 576,
|
| 19 |
+
"initializer_range": 0.02,
|
| 20 |
+
"intermediate_size": 1536,
|
| 21 |
+
"max_position_embeddings": 2048,
|
| 22 |
+
"mlp_bias": false,
|
| 23 |
+
"model_type": "surjo_exp",
|
| 24 |
+
"num_attention_heads": 8,
|
| 25 |
+
"num_hidden_layers": 32,
|
| 26 |
+
"num_key_value_heads": 2,
|
| 27 |
+
"pad_token_id": 1,
|
| 28 |
+
"prelude_layers": 4,
|
| 29 |
+
"pretraining_tp": 1,
|
| 30 |
+
"recurrent_layers": 12,
|
| 31 |
+
"rms_norm_eps": 1e-05,
|
| 32 |
+
"rope_parameters": {
|
| 33 |
+
"rope_theta": 10000.0,
|
| 34 |
+
"rope_type": "default"
|
| 35 |
+
},
|
| 36 |
+
"rope_theta": 10000.0,
|
| 37 |
+
"tie_word_embeddings": true,
|
| 38 |
+
"transformers_version": "5.15.0",
|
| 39 |
+
"use_cache": false,
|
| 40 |
+
"use_flash_attn": false,
|
| 41 |
+
"vocab_size": 32768,
|
| 42 |
+
"xsa_projection": true
|
| 43 |
+
}
|
checkpoint-12000/configuration_surjo_exp.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from transformers import LlamaConfig
|
| 3 |
+
|
| 4 |
+
class SurjoExpConfig(LlamaConfig):
|
| 5 |
+
model_type = "surjo_exp"
|
| 6 |
+
def __init__(self, *args, xsa_projection=True, rope_theta=10000.0, attention_bias=False,
|
| 7 |
+
prelude_layers=4, recurrent_layers=12, coda_layers=16,
|
| 8 |
+
gradient_checkpointing=True, use_flash_attn=True, **kwargs):
|
| 9 |
+
kwargs["num_hidden_layers"] = prelude_layers + recurrent_layers + coda_layers
|
| 10 |
+
kwargs.setdefault("use_cache", False)
|
| 11 |
+
super().__init__(*args, rope_theta=rope_theta, attention_bias=attention_bias, **kwargs)
|
| 12 |
+
self.xsa_projection = xsa_projection
|
| 13 |
+
self.rope_theta = rope_theta
|
| 14 |
+
self.attention_bias = attention_bias
|
| 15 |
+
self.prelude_layers = prelude_layers
|
| 16 |
+
self.recurrent_layers = recurrent_layers
|
| 17 |
+
self.coda_layers = coda_layers
|
| 18 |
+
self.gradient_checkpointing = gradient_checkpointing
|
| 19 |
+
self.use_flash_attn = use_flash_attn
|
| 20 |
+
if not hasattr(self, 'rope_parameters') or self.rope_parameters is None:
|
| 21 |
+
self.rope_parameters = {"rope_type": "default", "factor": 1.0, "rope_theta": rope_theta}
|
checkpoint-12000/generation_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 0,
|
| 4 |
+
"eos_token_id": 2,
|
| 5 |
+
"output_attentions": false,
|
| 6 |
+
"output_hidden_states": false,
|
| 7 |
+
"pad_token_id": 1,
|
| 8 |
+
"transformers_version": "5.15.0",
|
| 9 |
+
"use_cache": false
|
| 10 |
+
}
|
checkpoint-12000/model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2bc6ed1a32f0a30eafd2490c41a01f3319aceb1d9765f97c46471b021d296d76
|
| 3 |
+
size 521611856
|
checkpoint-12000/modeling_surjo_exp.py
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import torch.utils.checkpoint
|
| 6 |
+
from transformers import LlamaConfig, LlamaModel, LlamaForCausalLM
|
| 7 |
+
from transformers.models.llama.modeling_llama import LlamaRMSNorm
|
| 8 |
+
from transformers.models.llama.modeling_llama import LlamaMLP
|
| 9 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 10 |
+
from transformers.models.llama.modeling_llama import LlamaRotaryEmbedding, apply_rotary_pos_emb
|
| 11 |
+
from transformers.cache_utils import DynamicCache
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
from .configuration_surjo_exp import SurjoExpConfig
|
| 15 |
+
except ImportError:
|
| 16 |
+
from configuration_surjo_exp import SurjoExpConfig
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
from flash_attn import flash_attn_varlen_func
|
| 20 |
+
FLASH_ATTN_AVAILABLE = True
|
| 21 |
+
except ImportError:
|
| 22 |
+
FLASH_ATTN_AVAILABLE = False
|
| 23 |
+
|
| 24 |
+
@torch._dynamo.disable()
|
| 25 |
+
def _flash_varlen(q, k, v, cu_seqlens, max_seqlen, dropout_p):
|
| 26 |
+
ms = int(max_seqlen.item()) if torch.is_tensor(max_seqlen) else int(max_seqlen)
|
| 27 |
+
return flash_attn_varlen_func(
|
| 28 |
+
q, k, v, cu_seqlens, cu_seqlens, ms, ms,
|
| 29 |
+
dropout_p=dropout_p, causal=True,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
class ClampedLlamaMLP(LlamaMLP):
|
| 33 |
+
def forward(self, x):
|
| 34 |
+
gate = F.silu(self.gate_proj(x).clamp(-15.0, 15.0))
|
| 35 |
+
up = self.up_proj(x)
|
| 36 |
+
return self.down_proj(gate * up)
|
| 37 |
+
|
| 38 |
+
class XSAAttention(nn.Module):
|
| 39 |
+
def __init__(self, config, layer_idx=None):
|
| 40 |
+
super().__init__()
|
| 41 |
+
self.config = config
|
| 42 |
+
self.layer_idx = layer_idx
|
| 43 |
+
self.recurrent_cache_idx = None
|
| 44 |
+
self._use_recurrent_slot = False
|
| 45 |
+
self.hidden_size = config.hidden_size
|
| 46 |
+
self.num_heads = config.num_attention_heads
|
| 47 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 48 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 49 |
+
self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
|
| 50 |
+
self.attention_bias = getattr(config, "attention_bias", False)
|
| 51 |
+
|
| 52 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=self.attention_bias)
|
| 53 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=self.attention_bias)
|
| 54 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=self.attention_bias)
|
| 55 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=self.attention_bias)
|
| 56 |
+
|
| 57 |
+
self.q_norm = LlamaRMSNorm(self.head_dim, eps=1e-6)
|
| 58 |
+
self.k_norm = LlamaRMSNorm(self.head_dim, eps=1e-6)
|
| 59 |
+
|
| 60 |
+
def forward(self, hidden_states, attention_mask=None, position_ids=None, past_key_value=None,
|
| 61 |
+
output_attentions=False, use_cache=False, cache_position=None, position_embeddings=None,
|
| 62 |
+
expected_batch_size=None, cu_seqlens=None, max_seqlen=None, **kwargs):
|
| 63 |
+
past_kv = past_key_value if past_key_value is not None else kwargs.get("past_key_values", None)
|
| 64 |
+
|
| 65 |
+
if hidden_states.ndim == 2:
|
| 66 |
+
if expected_batch_size is None:
|
| 67 |
+
raise RuntimeError(
|
| 68 |
+
f"XSAAttention received 2D hidden_states {hidden_states.shape} "
|
| 69 |
+
f"without an expected_batch_size to safely restore the batch dim."
|
| 70 |
+
)
|
| 71 |
+
hidden_states = hidden_states.reshape(expected_batch_size, -1, self.hidden_size)
|
| 72 |
+
|
| 73 |
+
bsz, q_len, _ = hidden_states.size()
|
| 74 |
+
|
| 75 |
+
if expected_batch_size is not None and bsz != expected_batch_size:
|
| 76 |
+
raise RuntimeError(
|
| 77 |
+
f"XSAAttention: hidden_states batch size {bsz} does not match "
|
| 78 |
+
f"expected_batch_size {expected_batch_size}."
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim)
|
| 82 |
+
key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim)
|
| 83 |
+
value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim)
|
| 84 |
+
|
| 85 |
+
query_states = self.q_norm(query_states)
|
| 86 |
+
key_states = self.k_norm(key_states)
|
| 87 |
+
|
| 88 |
+
cos, sin = position_embeddings
|
| 89 |
+
|
| 90 |
+
use_flash = (
|
| 91 |
+
cu_seqlens is not None
|
| 92 |
+
and past_kv is None
|
| 93 |
+
and getattr(self.config, "use_flash_attn", False)
|
| 94 |
+
and FLASH_ATTN_AVAILABLE
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
if use_flash:
|
| 98 |
+
total = bsz * q_len
|
| 99 |
+
q = query_states.reshape(total, self.num_heads, self.head_dim)
|
| 100 |
+
k = key_states.reshape(total, self.num_key_value_heads, self.head_dim)
|
| 101 |
+
v = value_states.reshape(total, self.num_key_value_heads, self.head_dim)
|
| 102 |
+
|
| 103 |
+
q = q.to(torch.bfloat16)
|
| 104 |
+
k = k.to(torch.bfloat16)
|
| 105 |
+
v = v.to(torch.bfloat16)
|
| 106 |
+
|
| 107 |
+
cos_f = cos.reshape(-1, cos.shape[-1]).to(torch.bfloat16)
|
| 108 |
+
sin_f = sin.reshape(-1, sin.shape[-1]).to(torch.bfloat16)
|
| 109 |
+
q, k = apply_rotary_pos_emb(q, k, cos_f, sin_f, unsqueeze_dim=1)
|
| 110 |
+
|
| 111 |
+
attn_output = _flash_varlen(
|
| 112 |
+
q, k, v, cu_seqlens, max_seqlen,
|
| 113 |
+
self.config.attention_dropout if self.training else 0.0,
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
if getattr(self.config, 'xsa_projection', True):
|
| 117 |
+
y = attn_output.view(total, self.num_key_value_heads, self.num_key_value_groups, self.head_dim)
|
| 118 |
+
v_grouped = v.unsqueeze(2)
|
| 119 |
+
dot_yv = (y * v_grouped).sum(dim=-1, keepdim=True).float()
|
| 120 |
+
dot_vv = v_grouped.pow(2).sum(dim=-1, keepdim=True).clamp_min(1e-4).float()
|
| 121 |
+
scale = (dot_yv / dot_vv).to(y.dtype)
|
| 122 |
+
attn_output = (y - scale * v_grouped).reshape(total, self.num_heads, self.head_dim)
|
| 123 |
+
|
| 124 |
+
attn_output = self.o_proj(attn_output.reshape(bsz, q_len, self.hidden_size))
|
| 125 |
+
return (attn_output, None)
|
| 126 |
+
|
| 127 |
+
query_states = query_states.transpose(1, 2)
|
| 128 |
+
key_states = key_states.transpose(1, 2)
|
| 129 |
+
value_states = value_states.transpose(1, 2)
|
| 130 |
+
|
| 131 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 132 |
+
|
| 133 |
+
current_v = value_states
|
| 134 |
+
|
| 135 |
+
target_idx = self.layer_idx
|
| 136 |
+
if self._use_recurrent_slot and self.recurrent_cache_idx is not None:
|
| 137 |
+
target_idx = self.recurrent_cache_idx
|
| 138 |
+
|
| 139 |
+
if past_kv is not None:
|
| 140 |
+
while len(past_kv) <= target_idx:
|
| 141 |
+
past_kv.update(
|
| 142 |
+
torch.empty(bsz, self.num_key_value_heads, 0, self.head_dim, dtype=key_states.dtype, device=key_states.device),
|
| 143 |
+
torch.empty(bsz, self.num_key_value_heads, 0, self.head_dim, dtype=value_states.dtype, device=value_states.device),
|
| 144 |
+
len(past_kv)
|
| 145 |
+
)
|
| 146 |
+
key_states, value_states = past_kv.update(key_states, value_states, target_idx)
|
| 147 |
+
|
| 148 |
+
key_states = key_states.repeat_interleave(self.num_key_value_groups, dim=1)
|
| 149 |
+
value_states = value_states.repeat_interleave(self.num_key_value_groups, dim=1)
|
| 150 |
+
|
| 151 |
+
kv_len = key_states.shape[-2]
|
| 152 |
+
|
| 153 |
+
if attention_mask is not None:
|
| 154 |
+
if attention_mask.ndim == 2:
|
| 155 |
+
if attention_mask.shape[-1] < kv_len:
|
| 156 |
+
attention_mask = F.pad(attention_mask, (0, kv_len - attention_mask.shape[-1]), value=1)
|
| 157 |
+
elif attention_mask.shape[-1] > kv_len:
|
| 158 |
+
attention_mask = attention_mask[:, -kv_len:]
|
| 159 |
+
|
| 160 |
+
pad_mask = (1.0 - attention_mask[:, None, None, :].to(query_states.dtype)) * torch.finfo(query_states.dtype).min
|
| 161 |
+
|
| 162 |
+
if q_len > 1:
|
| 163 |
+
if cache_position is None:
|
| 164 |
+
cache_position = torch.arange(kv_len - q_len, kv_len, device=query_states.device)
|
| 165 |
+
kv_positions = torch.arange(kv_len, device=query_states.device)
|
| 166 |
+
|
| 167 |
+
neg_inf = torch.finfo(query_states.dtype).min
|
| 168 |
+
causal_mask = torch.zeros((q_len, kv_len), dtype=query_states.dtype, device=query_states.device)
|
| 169 |
+
causal_mask = causal_mask.masked_fill(kv_positions[None, :] > cache_position[:, None], neg_inf)
|
| 170 |
+
attn_mask = causal_mask[None, None, :, :] + pad_mask
|
| 171 |
+
|
| 172 |
+
diag_idx = torch.arange(q_len, device=attn_mask.device)
|
| 173 |
+
start_idx = attn_mask.shape[-1] - q_len
|
| 174 |
+
attn_mask[:, :, diag_idx, start_idx + diag_idx] = 0.0
|
| 175 |
+
else:
|
| 176 |
+
attn_mask = pad_mask
|
| 177 |
+
else:
|
| 178 |
+
if attention_mask.shape[0] != bsz:
|
| 179 |
+
raise RuntimeError(
|
| 180 |
+
f"attention_mask batch size {attention_mask.shape[0]} does not "
|
| 181 |
+
f"match hidden_states batch size {bsz}."
|
| 182 |
+
)
|
| 183 |
+
attn_mask = attention_mask.to(dtype=query_states.dtype)
|
| 184 |
+
is_causal = False
|
| 185 |
+
else:
|
| 186 |
+
is_causal = True
|
| 187 |
+
attn_mask = None
|
| 188 |
+
|
| 189 |
+
attn_output = F.scaled_dot_product_attention(
|
| 190 |
+
query_states, key_states, value_states, attn_mask=attn_mask,
|
| 191 |
+
dropout_p=0.0 if not self.training else self.config.attention_dropout, is_causal=is_causal
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
if getattr(self.config, 'xsa_projection', True):
|
| 195 |
+
y = attn_output.reshape(bsz, self.num_key_value_heads, self.num_key_value_groups, q_len, self.head_dim)
|
| 196 |
+
v_grouped = current_v.unsqueeze(2)
|
| 197 |
+
dot_yv = (y * v_grouped).sum(dim=-1, keepdim=True).float()
|
| 198 |
+
dot_vv = v_grouped.pow(2).sum(dim=-1, keepdim=True).clamp_min(1e-4).float()
|
| 199 |
+
scale = (dot_yv / dot_vv).to(y.dtype)
|
| 200 |
+
attn_output = (y - scale * v_grouped).reshape(bsz, self.num_heads, q_len, self.head_dim)
|
| 201 |
+
|
| 202 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 203 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
| 204 |
+
attn_output = self.o_proj(attn_output)
|
| 205 |
+
|
| 206 |
+
return (attn_output, None)
|
| 207 |
+
|
| 208 |
+
@torch._dynamo.disable()
|
| 209 |
+
def _checkpointed_layer_forward(layer, hidden_states, attention_mask, position_ids,
|
| 210 |
+
cache_position, cos, sin, expected_batch_size, cu_seqlens, max_seqlen):
|
| 211 |
+
out = layer(
|
| 212 |
+
hidden_states, attention_mask=attention_mask, position_ids=position_ids,
|
| 213 |
+
past_key_value=None, use_cache=False,
|
| 214 |
+
cache_position=cache_position, position_embeddings=(cos, sin),
|
| 215 |
+
expected_batch_size=expected_batch_size,
|
| 216 |
+
cu_seqlens=cu_seqlens, max_seqlen=max_seqlen,
|
| 217 |
+
)
|
| 218 |
+
hs_out = out[0] if isinstance(out, tuple) else out
|
| 219 |
+
if hs_out.ndim != 3 or hs_out.shape[0] != expected_batch_size:
|
| 220 |
+
raise RuntimeError(
|
| 221 |
+
f"Layer output shape {tuple(hs_out.shape)} does not match expected "
|
| 222 |
+
f"batch size {expected_batch_size}."
|
| 223 |
+
)
|
| 224 |
+
return hs_out
|
| 225 |
+
|
| 226 |
+
class SurjoExpModel(LlamaModel):
|
| 227 |
+
def __init__(self, config):
|
| 228 |
+
super().__init__(config)
|
| 229 |
+
|
| 230 |
+
assert config.prelude_layers + config.recurrent_layers + config.coda_layers == config.num_hidden_layers, \
|
| 231 |
+
"prelude_layers + recurrent_layers + coda_layers must equal num_hidden_layers"
|
| 232 |
+
|
| 233 |
+
if getattr(config, "use_flash_attn", False) and not FLASH_ATTN_AVAILABLE:
|
| 234 |
+
raise ImportError(
|
| 235 |
+
"config.use_flash_attn=True but flash_attn is not importable. "
|
| 236 |
+
"Install the FA2 wheel or set use_flash_attn=False."
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
p1 = config.prelude_layers
|
| 240 |
+
r1 = p1 + config.recurrent_layers
|
| 241 |
+
|
| 242 |
+
for i, layer in enumerate(self.layers):
|
| 243 |
+
layer.self_attn = XSAAttention(config, layer_idx=i)
|
| 244 |
+
layer.mlp = ClampedLlamaMLP(config)
|
| 245 |
+
|
| 246 |
+
for i, layer in enumerate(self.layers[p1:r1]):
|
| 247 |
+
layer.self_attn.recurrent_cache_idx = config.num_hidden_layers + p1 + i
|
| 248 |
+
|
| 249 |
+
self.gradient_checkpointing = getattr(config, "gradient_checkpointing", True)
|
| 250 |
+
|
| 251 |
+
def gradient_checkpointing_enable(self):
|
| 252 |
+
self.gradient_checkpointing = True
|
| 253 |
+
|
| 254 |
+
def gradient_checkpointing_disable(self):
|
| 255 |
+
self.gradient_checkpointing = False
|
| 256 |
+
|
| 257 |
+
def forward(self, input_ids=None, attention_mask=None, position_ids=None, inputs_embeds=None,
|
| 258 |
+
past_key_values=None, use_cache=None, output_attentions=False, output_hidden_states=False,
|
| 259 |
+
cache_position=None, return_dict=True, cu_seqlens=None, max_seqlen=None, **kwargs):
|
| 260 |
+
if use_cache is None:
|
| 261 |
+
use_cache = False
|
| 262 |
+
|
| 263 |
+
if inputs_embeds is None:
|
| 264 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 265 |
+
|
| 266 |
+
bsz, seq_len = inputs_embeds.shape[0], inputs_embeds.shape[1]
|
| 267 |
+
|
| 268 |
+
if cache_position is None:
|
| 269 |
+
past_seen = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 270 |
+
cache_position = torch.arange(past_seen, past_seen + seq_len, dtype=torch.long, device=inputs_embeds.device)
|
| 271 |
+
if position_ids is None:
|
| 272 |
+
position_ids = cache_position.unsqueeze(0).expand(bsz, -1)
|
| 273 |
+
|
| 274 |
+
hidden_states = inputs_embeds
|
| 275 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 276 |
+
cos, sin = position_embeddings
|
| 277 |
+
|
| 278 |
+
if use_cache and past_key_values is None:
|
| 279 |
+
past_key_values = DynamicCache()
|
| 280 |
+
|
| 281 |
+
p1 = self.config.prelude_layers
|
| 282 |
+
r1 = p1 + self.config.recurrent_layers
|
| 283 |
+
c1 = r1 + self.config.coda_layers
|
| 284 |
+
|
| 285 |
+
prelude = self.layers[:p1]
|
| 286 |
+
recurrent = self.layers[p1:r1]
|
| 287 |
+
coda = self.layers[r1:c1]
|
| 288 |
+
|
| 289 |
+
use_ckpt = self.training and self.gradient_checkpointing and not use_cache
|
| 290 |
+
|
| 291 |
+
def run_layer(layer, hs):
|
| 292 |
+
if cu_seqlens is not None:
|
| 293 |
+
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
| 294 |
+
|
| 295 |
+
out = layer(
|
| 296 |
+
hs, attention_mask=attention_mask, position_ids=position_ids,
|
| 297 |
+
past_key_value=past_key_values if use_cache else None, use_cache=use_cache,
|
| 298 |
+
cache_position=cache_position, position_embeddings=position_embeddings,
|
| 299 |
+
expected_batch_size=bsz, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen,
|
| 300 |
+
)
|
| 301 |
+
hs_out = out[0] if isinstance(out, tuple) else out
|
| 302 |
+
if hs_out.ndim != 3 or hs_out.shape[0] != bsz:
|
| 303 |
+
raise RuntimeError(
|
| 304 |
+
f"Layer output shape {tuple(hs_out.shape)} does not match expected "
|
| 305 |
+
f"batch size {bsz}."
|
| 306 |
+
)
|
| 307 |
+
return hs_out
|
| 308 |
+
|
| 309 |
+
def run_layer_maybe_ckpt(layer, hs):
|
| 310 |
+
if use_ckpt:
|
| 311 |
+
return torch.utils.checkpoint.checkpoint(
|
| 312 |
+
_checkpointed_layer_forward,
|
| 313 |
+
layer, hs, attention_mask, position_ids, cache_position, cos, sin, bsz,
|
| 314 |
+
cu_seqlens, max_seqlen,
|
| 315 |
+
use_reentrant=False,
|
| 316 |
+
)
|
| 317 |
+
return run_layer(layer, hs)
|
| 318 |
+
|
| 319 |
+
for layer in prelude:
|
| 320 |
+
hidden_states = run_layer_maybe_ckpt(layer, hidden_states)
|
| 321 |
+
|
| 322 |
+
if self.training:
|
| 323 |
+
hidden_states = hidden_states + torch.randn_like(hidden_states) * 0.02
|
| 324 |
+
|
| 325 |
+
for layer in recurrent:
|
| 326 |
+
hidden_states = run_layer_maybe_ckpt(layer, hidden_states)
|
| 327 |
+
|
| 328 |
+
if self.training:
|
| 329 |
+
hidden_states = hidden_states + torch.randn_like(hidden_states) * 0.02
|
| 330 |
+
|
| 331 |
+
for layer in recurrent:
|
| 332 |
+
layer.self_attn._use_recurrent_slot = True
|
| 333 |
+
try:
|
| 334 |
+
hidden_states = run_layer_maybe_ckpt(layer, hidden_states)
|
| 335 |
+
finally:
|
| 336 |
+
layer.self_attn._use_recurrent_slot = False
|
| 337 |
+
|
| 338 |
+
for layer in coda:
|
| 339 |
+
hidden_states = run_layer_maybe_ckpt(layer, hidden_states)
|
| 340 |
+
|
| 341 |
+
hidden_states = self.norm(hidden_states)
|
| 342 |
+
return BaseModelOutputWithPast(last_hidden_state=hidden_states, past_key_values=past_key_values)
|
| 343 |
+
|
| 344 |
+
class SurjoExpForCausalLM(LlamaForCausalLM):
|
| 345 |
+
config_class = SurjoExpConfig
|
| 346 |
+
def __init__(self, config):
|
| 347 |
+
super(LlamaForCausalLM, self).__init__(config)
|
| 348 |
+
self.model = SurjoExpModel(config)
|
| 349 |
+
self.vocab_size = config.vocab_size
|
| 350 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 351 |
+
self.post_init()
|
| 352 |
+
|
| 353 |
+
def gradient_checkpointing_enable(self, **kwargs):
|
| 354 |
+
self.model.gradient_checkpointing_enable()
|
| 355 |
+
|
| 356 |
+
def gradient_checkpointing_disable(self):
|
| 357 |
+
self.model.gradient_checkpointing_disable()
|
| 358 |
+
|
| 359 |
+
def forward(self, input_ids=None, attention_mask=None, labels=None, inputs_embeds=None,
|
| 360 |
+
use_cache=None, num_logits_to_keep=0, position_ids=None, past_key_values=None,
|
| 361 |
+
cache_position=None, cu_seqlens=None, max_seqlen=None, **kwargs):
|
| 362 |
+
if use_cache is None:
|
| 363 |
+
use_cache = False if (self.training or labels is not None) else True
|
| 364 |
+
|
| 365 |
+
if num_logits_to_keep == 0 and "logits_to_keep" in kwargs:
|
| 366 |
+
num_logits_to_keep = kwargs["logits_to_keep"]
|
| 367 |
+
|
| 368 |
+
outputs = self.model(
|
| 369 |
+
input_ids=input_ids,
|
| 370 |
+
attention_mask=attention_mask,
|
| 371 |
+
position_ids=position_ids,
|
| 372 |
+
inputs_embeds=inputs_embeds,
|
| 373 |
+
past_key_values=past_key_values,
|
| 374 |
+
use_cache=use_cache,
|
| 375 |
+
cache_position=cache_position,
|
| 376 |
+
cu_seqlens=cu_seqlens,
|
| 377 |
+
max_seqlen=max_seqlen,
|
| 378 |
+
)
|
| 379 |
+
hidden_states = outputs[0]
|
| 380 |
+
|
| 381 |
+
expected_bsz = input_ids.shape[0] if input_ids is not None else inputs_embeds.shape[0]
|
| 382 |
+
if hidden_states.ndim != 3 or hidden_states.shape[0] != expected_bsz:
|
| 383 |
+
raise RuntimeError(
|
| 384 |
+
f"SurjoExpModel returned hidden_states with shape {tuple(hidden_states.shape)}, "
|
| 385 |
+
f"expected batch size {expected_bsz}."
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
loss = None
|
| 389 |
+
logits = None
|
| 390 |
+
|
| 391 |
+
if labels is not None:
|
| 392 |
+
shift_hidden = hidden_states[..., :-1, :].contiguous()
|
| 393 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 394 |
+
|
| 395 |
+
num_chunks = 8
|
| 396 |
+
h_chunks = shift_hidden.chunk(num_chunks, dim=0)
|
| 397 |
+
l_chunks = shift_labels.chunk(num_chunks, dim=0)
|
| 398 |
+
|
| 399 |
+
total_loss = hidden_states.new_zeros((), dtype=torch.float32)
|
| 400 |
+
total_tokens = 0
|
| 401 |
+
for h_c, l_c in zip(h_chunks, l_chunks):
|
| 402 |
+
logits_c = self.lm_head(h_c)
|
| 403 |
+
chunk_loss = F.cross_entropy(
|
| 404 |
+
logits_c.view(-1, logits_c.size(-1)).float(),
|
| 405 |
+
l_c.view(-1),
|
| 406 |
+
reduction="sum",
|
| 407 |
+
)
|
| 408 |
+
total_loss = total_loss + chunk_loss
|
| 409 |
+
total_tokens += l_c.numel()
|
| 410 |
+
loss = (total_loss / total_tokens).to(hidden_states.dtype)
|
| 411 |
+
else:
|
| 412 |
+
slice_hidden = hidden_states if num_logits_to_keep == 0 else hidden_states[:, -num_logits_to_keep:, :]
|
| 413 |
+
logits = self.lm_head(slice_hidden)
|
| 414 |
+
|
| 415 |
+
return CausalLMOutputWithPast(
|
| 416 |
+
loss=loss, logits=logits, past_key_values=outputs.past_key_values
|
| 417 |
+
)
|
checkpoint-12000/optimizer.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8c498e428a0a63472403e0c60d9f3de286aac9fbb273490f6446fce09681360f
|
| 3 |
+
size 445974859
|
checkpoint-12000/optimizer_1.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:88716252e80cf72aea12282702bc0985ba19ca4c680c0579d652c3f54b0deab5
|
| 3 |
+
size 151436195
|
checkpoint-12000/random_states_0.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5a688b2534134342f5196e7149ccbe74607e5be59ee3798bf931226a58eb5d4c
|
| 3 |
+
size 14821
|
checkpoint-12000/tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
checkpoint-12000/tokenizer_config.json
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"bos_token": "<|bos|>",
|
| 4 |
+
"clean_up_tokenization_spaces": false,
|
| 5 |
+
"eos_token": "<|eos|>",
|
| 6 |
+
"extra_special_tokens": [
|
| 7 |
+
"<|unk|>",
|
| 8 |
+
"<|pad|>",
|
| 9 |
+
"<|bos|>",
|
| 10 |
+
"<|eos|>",
|
| 11 |
+
"<|mask|>",
|
| 12 |
+
"<|im_start|>",
|
| 13 |
+
"<|im_end|>",
|
| 14 |
+
"<|system|>",
|
| 15 |
+
"<|user|>",
|
| 16 |
+
"<|assistant|>",
|
| 17 |
+
"<think>",
|
| 18 |
+
"</think>",
|
| 19 |
+
"<|begin_of_thought|>",
|
| 20 |
+
"<|end_of_thought|>",
|
| 21 |
+
"<answer>",
|
| 22 |
+
"</answer>",
|
| 23 |
+
"<|step|>",
|
| 24 |
+
"<|/step|>",
|
| 25 |
+
"<context>",
|
| 26 |
+
"</context>",
|
| 27 |
+
"<|doc_start|>",
|
| 28 |
+
"<|doc_end|>",
|
| 29 |
+
"<|search|>",
|
| 30 |
+
"<|search_results|>",
|
| 31 |
+
"<|tool_list_start|>",
|
| 32 |
+
"<|tool_list_end|>",
|
| 33 |
+
"<tools>",
|
| 34 |
+
"</tools>",
|
| 35 |
+
"<|tool_call_start|>",
|
| 36 |
+
"<|tool_call_end|>",
|
| 37 |
+
"<|tool_call|>",
|
| 38 |
+
"<|/tool_call|>",
|
| 39 |
+
"<|tool_response_start|>",
|
| 40 |
+
"<|tool_response_end|>",
|
| 41 |
+
"<|tool_response|>",
|
| 42 |
+
"<|/tool_response|>",
|
| 43 |
+
"<|image|>",
|
| 44 |
+
"<|image_pad|>",
|
| 45 |
+
"<|image_placeholder|>",
|
| 46 |
+
"<|audio|>",
|
| 47 |
+
"<|audio_pad|>",
|
| 48 |
+
"<|audio_placeholder|>",
|
| 49 |
+
"<|video|>",
|
| 50 |
+
"<|video_pad|>",
|
| 51 |
+
"<|fim_prefix|>",
|
| 52 |
+
"<|fim_suffix|>",
|
| 53 |
+
"<|fim_middle|>",
|
| 54 |
+
"<|repo_name|>",
|
| 55 |
+
"<|file_separator|>",
|
| 56 |
+
"<|reward|>",
|
| 57 |
+
"<|reserved_0|>",
|
| 58 |
+
"<|reserved_1|>",
|
| 59 |
+
"<|reserved_2|>",
|
| 60 |
+
"<|reserved_3|>",
|
| 61 |
+
"<|reserved_4|>",
|
| 62 |
+
"<|reserved_5|>",
|
| 63 |
+
"<|reserved_6|>",
|
| 64 |
+
"<|reserved_7|>",
|
| 65 |
+
"<|reserved_8|>",
|
| 66 |
+
"<|reserved_9|>",
|
| 67 |
+
"<|reserved_10|>",
|
| 68 |
+
"<|reserved_11|>",
|
| 69 |
+
"<|reserved_12|>",
|
| 70 |
+
"<|reserved_13|>",
|
| 71 |
+
"<|reserved_14|>",
|
| 72 |
+
"<|reserved_15|>",
|
| 73 |
+
"<|reserved_16|>",
|
| 74 |
+
"<|reserved_17|>",
|
| 75 |
+
"<|reserved_18|>",
|
| 76 |
+
"<|reserved_19|>"
|
| 77 |
+
],
|
| 78 |
+
"is_local": false,
|
| 79 |
+
"local_files_only": false,
|
| 80 |
+
"mask_token": "<|mask|>",
|
| 81 |
+
"model_max_length": 10000000,
|
| 82 |
+
"pad_token": "<|pad|>",
|
| 83 |
+
"tokenizer_class": "TokenizersBackend",
|
| 84 |
+
"unk_token": "<|unk|>"
|
| 85 |
+
}
|
checkpoint-13000/chat_template.jinja
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{ bos_token }}{% for message in messages %}{{ '<|im_start|>' + message['role'] + '
|
| 2 |
+
' + message['content'] + '<|im_end|>
|
| 3 |
+
' }}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant
|
| 4 |
+
' }}{% endif %}
|
checkpoint-13000/config.json
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"SurjoExpForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"attention_bias": false,
|
| 6 |
+
"attention_dropout": 0.0,
|
| 7 |
+
"auto_map": {
|
| 8 |
+
"AutoConfig": "configuration_surjo_exp.SurjoExpConfig",
|
| 9 |
+
"AutoModelForCausalLM": "modeling_surjo_exp.SurjoExpForCausalLM"
|
| 10 |
+
},
|
| 11 |
+
"bos_token_id": 0,
|
| 12 |
+
"coda_layers": 16,
|
| 13 |
+
"dtype": "float32",
|
| 14 |
+
"eos_token_id": 2,
|
| 15 |
+
"gradient_checkpointing": false,
|
| 16 |
+
"head_dim": 72,
|
| 17 |
+
"hidden_act": "silu",
|
| 18 |
+
"hidden_size": 576,
|
| 19 |
+
"initializer_range": 0.02,
|
| 20 |
+
"intermediate_size": 1536,
|
| 21 |
+
"max_position_embeddings": 2048,
|
| 22 |
+
"mlp_bias": false,
|
| 23 |
+
"model_type": "surjo_exp",
|
| 24 |
+
"num_attention_heads": 8,
|
| 25 |
+
"num_hidden_layers": 32,
|
| 26 |
+
"num_key_value_heads": 2,
|
| 27 |
+
"pad_token_id": 1,
|
| 28 |
+
"prelude_layers": 4,
|
| 29 |
+
"pretraining_tp": 1,
|
| 30 |
+
"recurrent_layers": 12,
|
| 31 |
+
"rms_norm_eps": 1e-05,
|
| 32 |
+
"rope_parameters": {
|
| 33 |
+
"rope_theta": 10000.0,
|
| 34 |
+
"rope_type": "default"
|
| 35 |
+
},
|
| 36 |
+
"rope_theta": 10000.0,
|
| 37 |
+
"tie_word_embeddings": true,
|
| 38 |
+
"transformers_version": "5.15.0",
|
| 39 |
+
"use_cache": false,
|
| 40 |
+
"use_flash_attn": false,
|
| 41 |
+
"vocab_size": 32768,
|
| 42 |
+
"xsa_projection": true
|
| 43 |
+
}
|
checkpoint-13000/configuration_surjo_exp.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from transformers import LlamaConfig
|
| 3 |
+
|
| 4 |
+
class SurjoExpConfig(LlamaConfig):
|
| 5 |
+
model_type = "surjo_exp"
|
| 6 |
+
def __init__(self, *args, xsa_projection=True, rope_theta=10000.0, attention_bias=False,
|
| 7 |
+
prelude_layers=4, recurrent_layers=12, coda_layers=16,
|
| 8 |
+
gradient_checkpointing=True, use_flash_attn=True, **kwargs):
|
| 9 |
+
kwargs["num_hidden_layers"] = prelude_layers + recurrent_layers + coda_layers
|
| 10 |
+
kwargs.setdefault("use_cache", False)
|
| 11 |
+
super().__init__(*args, rope_theta=rope_theta, attention_bias=attention_bias, **kwargs)
|
| 12 |
+
self.xsa_projection = xsa_projection
|
| 13 |
+
self.rope_theta = rope_theta
|
| 14 |
+
self.attention_bias = attention_bias
|
| 15 |
+
self.prelude_layers = prelude_layers
|
| 16 |
+
self.recurrent_layers = recurrent_layers
|
| 17 |
+
self.coda_layers = coda_layers
|
| 18 |
+
self.gradient_checkpointing = gradient_checkpointing
|
| 19 |
+
self.use_flash_attn = use_flash_attn
|
| 20 |
+
if not hasattr(self, 'rope_parameters') or self.rope_parameters is None:
|
| 21 |
+
self.rope_parameters = {"rope_type": "default", "factor": 1.0, "rope_theta": rope_theta}
|