Text Generation
Transformers
Safetensors
English
aquila_slm
kestrel
aquila
small-language-model
base
pretrained
hybrid
gated-deltanet-2
attnres
tngram
custom_code
Instructions to use Emergent-Knowledge/kestrel-preview with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Emergent-Knowledge/kestrel-preview with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Emergent-Knowledge/kestrel-preview", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("Emergent-Knowledge/kestrel-preview", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Emergent-Knowledge/kestrel-preview with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Emergent-Knowledge/kestrel-preview" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Emergent-Knowledge/kestrel-preview", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/Emergent-Knowledge/kestrel-preview
- SGLang
How to use Emergent-Knowledge/kestrel-preview with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "Emergent-Knowledge/kestrel-preview" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Emergent-Knowledge/kestrel-preview", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "Emergent-Knowledge/kestrel-preview" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Emergent-Knowledge/kestrel-preview", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use Emergent-Knowledge/kestrel-preview with Docker Model Runner:
docker model run hf.co/Emergent-Knowledge/kestrel-preview
Upload Kestrel Preview (98.6M base, Intelligence Index 19.94)
Browse files- README.md +93 -0
- config.json +45 -0
- configuration_aquila.py +73 -0
- generation_config.json +71 -0
- model.safetensors +3 -0
- modeling_aquila.py +385 -0
- special_tokens_map.json +11 -0
- tokenizer.json +0 -0
- tokenizer_config.json +20 -0
README.md
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
pipeline_tag: text-generation
|
| 6 |
+
library_name: transformers
|
| 7 |
+
tags:
|
| 8 |
+
- kestrel
|
| 9 |
+
- aquila
|
| 10 |
+
- small-language-model
|
| 11 |
+
- base
|
| 12 |
+
- pretrained
|
| 13 |
+
- hybrid
|
| 14 |
+
- gated-deltanet-2
|
| 15 |
+
- attnres
|
| 16 |
+
- tngram
|
| 17 |
+
- custom_code
|
| 18 |
+
---
|
| 19 |
+
|
| 20 |
+
# Kestrel Preview
|
| 21 |
+
|
| 22 |
+
**Kestrel Preview** is a small, experimental 98.6M-parameter English base language model trained from scratch in a single 8-hour run on one GPU. It is our first working checkpoint from the Kestrel (formerly Aquila) research preview — built to test whether modern recurrent-hybrid architectures, tensorized n-gram memory, and token-superposition training can make small models meaningfully more sample-efficient before scaling up.
|
| 23 |
+
|
| 24 |
+
It is still very early. With only 7.85B raw tokens seen (3.15B forward positions), Kestrel Preview is not meant to compete with heavily trained models yet — it is a transparent baseline and a starting point for what comes next.
|
| 25 |
+
|
| 26 |
+
---
|
| 27 |
+
|
| 28 |
+
## Results
|
| 29 |
+
|
| 30 |
+
Evaluated zero-shot on the [Open SLM Leaderboard](https://huggingface.co/spaces/AxiomicLabs/Open_SLM_Leaderboard) suite (`lm-eval` 0.4.13, `acc_norm` on ARC/HellaSwag/PIQA; official continuation log-likelihood scoring on ArithMark-3):
|
| 31 |
+
|
| 32 |
+
| Benchmark | Kestrel Preview (98.6M, 7.85B raw) |
|
| 33 |
+
|---|---:|
|
| 34 |
+
| **ARC-Easy** | 53.24% |
|
| 35 |
+
| **ARC-Challenge** | 25.85% |
|
| 36 |
+
| **HellaSwag** | 34.49% |
|
| 37 |
+
| **PIQA** | 63.60% |
|
| 38 |
+
| **ArithMark-3** | 40.60% |
|
| 39 |
+
| **Intelligence Index** | **19.94** |
|
| 40 |
+
|
| 41 |
+
For context, reaching an Intelligence Index near 20 typically takes 15B–50B tokens for standard 100M–150M Transformers on the same leaderboard. We are encouraged by the efficiency, while mindful that commonsense fluency (especially HellaSwag and PIQA) still has a long way to go with more training tokens.
|
| 42 |
+
|
| 43 |
+
---
|
| 44 |
+
|
| 45 |
+
## Architecture & Training
|
| 46 |
+
|
| 47 |
+
Kestrel Preview is a 24-layer hybrid model built in plain PyTorch for portable inference (`trust_remote_code=True`, runs on CUDA, Apple Silicon, or CPU without custom kernels):
|
| 48 |
+
|
| 49 |
+
- **Parameters:** 98,631,096 (tied input/output embeddings)
|
| 50 |
+
- **Backbone:** 24 layers, hidden size 576, 3:1 **Gated DeltaNet-2** (18 layers, 4 heads × 128) to **Grouped-Query Attention** (6 layers, 9 Q / 3 KV heads × 64, RoPE, QK-norm, value residual mixing)
|
| 51 |
+
- **Feed-forward:** SwiGLU (hidden size 1,088)
|
| 52 |
+
- **Residuals:** Block Attention Residuals (8 blocks of 3 layers)
|
| 53 |
+
- **Memory:** TN-gram tensorized n-gram embeddings (orders 2, 3, 4, and 5; CP rank 224; inserted before layers 2 and 18)
|
| 54 |
+
- **Context & Tokenizer:** 2,048 tokens; reuses the 4,100-token (4,160-padded) Apache-2.0 tokenizer from [MinimaLabs/KLM-1.6](https://huggingface.co/MinimaLabs/KLM-1.6)
|
| 55 |
+
- **Training Recipe:** 12,000 steps (128 × 2,048) on 1× RTX PRO 6000 Blackwell (~8.1 hours):
|
| 56 |
+
1. **Superposition phase (steps 0–2,999):** Token-Superposition Training (`s = 7`, ~5.50B raw tokens of ClimbMix) with TN-gram bypassed.
|
| 57 |
+
2. **Next-token & `1−√t` decay phase (steps 3,000–11,999):** ~2.35B tokens from a balanced, strictly decontaminated mix (ClimbMix, FinePhrase, Cosmopedia v2, FineWeb-Edu, Dolmino Q&A & flashcards, WikiHow, Pretrain-Behaviors, FineMath-4+, OpenMathInstruct-2, Dolmino math, SciQ/QASC train splits, and procedural arithmetic), with TN-gram ramped smoothly over 763 steps.
|
| 58 |
+
3. **Optimization:** Row-equilibrated Muon (`MuonEq-R`, lr `0.01`, decoupled weight decay `0.05`) for 2-D linear weights and AdamW (`lr 3e-3`) for embeddings, norms, convolutions, and memory factors.
|
| 59 |
+
|
| 60 |
+
---
|
| 61 |
+
|
| 62 |
+
## Quick Start
|
| 63 |
+
|
| 64 |
+
```python
|
| 65 |
+
import torch
|
| 66 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 67 |
+
|
| 68 |
+
model_id = "Emergent-Knowledge/kestrel-preview"
|
| 69 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 70 |
+
|
| 71 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
| 72 |
+
model = AutoModelForCausalLM.from_pretrained(model_id, trust_remote_code=True).to(device).eval()
|
| 73 |
+
|
| 74 |
+
inputs = tokenizer("The reason birds migrate south in winter is", return_tensors="pt").to(device)
|
| 75 |
+
out = model.generate(**inputs, max_new_tokens=60, do_sample=True, temperature=0.7, top_p=0.9)
|
| 76 |
+
print(tokenizer.decode(out[0], skip_special_tokens=True))
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
---
|
| 80 |
+
|
| 81 |
+
## Limitations
|
| 82 |
+
|
| 83 |
+
- **Base model only:** Kestrel Preview is not instruction-tuned or aligned for chat. It simply continues text.
|
| 84 |
+
- **Small training budget:** At 7.85B raw tokens and 98.6M parameters, its world knowledge is thin and it will frequently state incorrect facts.
|
| 85 |
+
- **English & 2,048 context:** Trained on English text up to 2,048 tokens.
|
| 86 |
+
|
| 87 |
+
---
|
| 88 |
+
|
| 89 |
+
## Acknowledgements & License
|
| 90 |
+
|
| 91 |
+
Kestrel Preview builds directly on open research and open weights from the community — especially [MinimaLabs/KLM-1.6](https://huggingface.co/MinimaLabs/KLM-1.6) (Apache-2.0) for its tokenizer and architectural inspiration, alongside Gated DeltaNet-2 (`arXiv:2605.22791`), Attention Residuals (`arXiv:2603.15031`), TN-gram (`arXiv:2606.08347`), Token-Superposition Training (`arXiv:2605.06546`), and MuonEq (`arXiv:2603.28254`).
|
| 92 |
+
|
| 93 |
+
Released under the **Apache-2.0** license.
|
config.json
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"vocab_size": 4160,
|
| 3 |
+
"hidden_size": 576,
|
| 4 |
+
"num_hidden_layers": 24,
|
| 5 |
+
"attention_every": 4,
|
| 6 |
+
"intermediate_size": 1088,
|
| 7 |
+
"num_attention_heads": 9,
|
| 8 |
+
"num_key_value_heads": 3,
|
| 9 |
+
"gdn_heads": 4,
|
| 10 |
+
"gdn_head_dim": 128,
|
| 11 |
+
"decay_floor": -20.0,
|
| 12 |
+
"gdn_norm_eps": 1e-05,
|
| 13 |
+
"rms_norm_eps": 1e-06,
|
| 14 |
+
"rope_theta": 10000.0,
|
| 15 |
+
"bos_token_id": 1,
|
| 16 |
+
"eos_token_id": 2,
|
| 17 |
+
"pad_token_id": 0,
|
| 18 |
+
"memory": "tngram",
|
| 19 |
+
"tn_orders": [
|
| 20 |
+
2,
|
| 21 |
+
3,
|
| 22 |
+
4,
|
| 23 |
+
5
|
| 24 |
+
],
|
| 25 |
+
"tn_rank": 224,
|
| 26 |
+
"tn_insert_before": [
|
| 27 |
+
2,
|
| 28 |
+
18
|
| 29 |
+
],
|
| 30 |
+
"tn_conv": 3,
|
| 31 |
+
"attnres_group": 3,
|
| 32 |
+
"tn_scale": 1.0,
|
| 33 |
+
"trained_steps": 12000,
|
| 34 |
+
"architectures": [
|
| 35 |
+
"AquilaForCausalLM"
|
| 36 |
+
],
|
| 37 |
+
"model_type": "aquila_slm",
|
| 38 |
+
"torch_dtype": "float32",
|
| 39 |
+
"max_position_embeddings": 2048,
|
| 40 |
+
"tie_word_embeddings": true,
|
| 41 |
+
"auto_map": {
|
| 42 |
+
"AutoConfig": "configuration_aquila.AquilaConfig",
|
| 43 |
+
"AutoModelForCausalLM": "modeling_aquila.AquilaForCausalLM"
|
| 44 |
+
}
|
| 45 |
+
}
|
configuration_aquila.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""AquilaConfig: Transformers config for Aquila (KLM-1.6-style GDN-2 / attention hybrid with
|
| 2 |
+
Block Attention Residuals and TN-gram n-gram embeddings)."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from transformers import PretrainedConfig
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class AquilaConfig(PretrainedConfig):
|
| 9 |
+
model_type = "aquila_slm"
|
| 10 |
+
|
| 11 |
+
def __init__(
|
| 12 |
+
self,
|
| 13 |
+
vocab_size: int = 4160,
|
| 14 |
+
hidden_size: int = 576,
|
| 15 |
+
num_hidden_layers: int = 24,
|
| 16 |
+
attention_every: int = 4,
|
| 17 |
+
intermediate_size: int = 1088,
|
| 18 |
+
num_attention_heads: int = 9,
|
| 19 |
+
num_key_value_heads: int = 3,
|
| 20 |
+
gdn_heads: int = 4,
|
| 21 |
+
gdn_head_dim: int = 128,
|
| 22 |
+
decay_floor: float = -20.0,
|
| 23 |
+
gdn_norm_eps: float = 1e-5,
|
| 24 |
+
rms_norm_eps: float = 1e-6,
|
| 25 |
+
rope_theta: float = 10000.0,
|
| 26 |
+
max_position_embeddings: int = 2048,
|
| 27 |
+
memory: str = "tngram",
|
| 28 |
+
n_bigrams: int = 125000,
|
| 29 |
+
n_trigrams: int = 38000,
|
| 30 |
+
ngram_dim: int = 32,
|
| 31 |
+
tn_orders=(2, 3, 4, 5),
|
| 32 |
+
tn_rank: int = 224,
|
| 33 |
+
tn_insert_before=(2, 18),
|
| 34 |
+
tn_conv: int = 3,
|
| 35 |
+
tn_scale: float = 1.0,
|
| 36 |
+
attnres_group: int = 3,
|
| 37 |
+
trained_steps: int = 0,
|
| 38 |
+
bos_token_id: int = 1,
|
| 39 |
+
eos_token_id: int = 2,
|
| 40 |
+
pad_token_id: int = 0,
|
| 41 |
+
tie_word_embeddings: bool = True,
|
| 42 |
+
**kwargs,
|
| 43 |
+
):
|
| 44 |
+
self.vocab_size = vocab_size
|
| 45 |
+
self.hidden_size = hidden_size
|
| 46 |
+
self.num_hidden_layers = num_hidden_layers
|
| 47 |
+
self.attention_every = attention_every
|
| 48 |
+
self.intermediate_size = intermediate_size
|
| 49 |
+
self.num_attention_heads = num_attention_heads
|
| 50 |
+
self.num_key_value_heads = num_key_value_heads
|
| 51 |
+
self.gdn_heads = gdn_heads
|
| 52 |
+
self.gdn_head_dim = gdn_head_dim
|
| 53 |
+
self.decay_floor = decay_floor
|
| 54 |
+
self.gdn_norm_eps = gdn_norm_eps
|
| 55 |
+
self.rms_norm_eps = rms_norm_eps
|
| 56 |
+
self.rope_theta = rope_theta
|
| 57 |
+
self.max_position_embeddings = max_position_embeddings
|
| 58 |
+
self.memory = memory
|
| 59 |
+
self.n_bigrams = n_bigrams
|
| 60 |
+
self.n_trigrams = n_trigrams
|
| 61 |
+
self.ngram_dim = ngram_dim
|
| 62 |
+
self.tn_orders = tuple(tn_orders)
|
| 63 |
+
self.tn_rank = tn_rank
|
| 64 |
+
self.tn_insert_before = tuple(tn_insert_before)
|
| 65 |
+
self.tn_conv = tn_conv
|
| 66 |
+
self.tn_scale = tn_scale # TN-gram output scale at this checkpoint (0 during superposition)
|
| 67 |
+
self.attnres_group = attnres_group # layers per Block-AttnRes block (1 = full AttnRes)
|
| 68 |
+
self.trained_steps = trained_steps
|
| 69 |
+
super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, pad_token_id=pad_token_id,
|
| 70 |
+
tie_word_embeddings=tie_word_embeddings, **kwargs)
|
| 71 |
+
|
| 72 |
+
def is_attention(self, layer: int) -> bool:
|
| 73 |
+
return layer % self.attention_every == self.attention_every - 1
|
generation_config.json
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token_id": 1,
|
| 3 |
+
"eos_token_id": [
|
| 4 |
+
4097,
|
| 5 |
+
2
|
| 6 |
+
],
|
| 7 |
+
"pad_token_id": 0,
|
| 8 |
+
"suppress_tokens": [
|
| 9 |
+
4100,
|
| 10 |
+
4101,
|
| 11 |
+
4102,
|
| 12 |
+
4103,
|
| 13 |
+
4104,
|
| 14 |
+
4105,
|
| 15 |
+
4106,
|
| 16 |
+
4107,
|
| 17 |
+
4108,
|
| 18 |
+
4109,
|
| 19 |
+
4110,
|
| 20 |
+
4111,
|
| 21 |
+
4112,
|
| 22 |
+
4113,
|
| 23 |
+
4114,
|
| 24 |
+
4115,
|
| 25 |
+
4116,
|
| 26 |
+
4117,
|
| 27 |
+
4118,
|
| 28 |
+
4119,
|
| 29 |
+
4120,
|
| 30 |
+
4121,
|
| 31 |
+
4122,
|
| 32 |
+
4123,
|
| 33 |
+
4124,
|
| 34 |
+
4125,
|
| 35 |
+
4126,
|
| 36 |
+
4127,
|
| 37 |
+
4128,
|
| 38 |
+
4129,
|
| 39 |
+
4130,
|
| 40 |
+
4131,
|
| 41 |
+
4132,
|
| 42 |
+
4133,
|
| 43 |
+
4134,
|
| 44 |
+
4135,
|
| 45 |
+
4136,
|
| 46 |
+
4137,
|
| 47 |
+
4138,
|
| 48 |
+
4139,
|
| 49 |
+
4140,
|
| 50 |
+
4141,
|
| 51 |
+
4142,
|
| 52 |
+
4143,
|
| 53 |
+
4144,
|
| 54 |
+
4145,
|
| 55 |
+
4146,
|
| 56 |
+
4147,
|
| 57 |
+
4148,
|
| 58 |
+
4149,
|
| 59 |
+
4150,
|
| 60 |
+
4151,
|
| 61 |
+
4152,
|
| 62 |
+
4153,
|
| 63 |
+
4154,
|
| 64 |
+
4155,
|
| 65 |
+
4156,
|
| 66 |
+
4157,
|
| 67 |
+
4158,
|
| 68 |
+
4159
|
| 69 |
+
],
|
| 70 |
+
"use_cache": false
|
| 71 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:688edf8a8a7023c5720e1bec6f3e9573010172abfc4374bf5eb6e133baef5ff2
|
| 3 |
+
size 394576584
|
modeling_aquila.py
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Aquila for Transformers, in plain PyTorch, so it runs on CPU, CUDA or Apple MPS without custom kernels.
|
| 2 |
+
|
| 3 |
+
Parameter names match the training code (aquila/model.py, which uses flash-linear-attention kernels);
|
| 4 |
+
export_hf.py converts a training checkpoint into this format. A sequence may hold several documents
|
| 5 |
+
separated by <eos>: after each <eos> the attention mask, the Gated DeltaNet-2 state, its short
|
| 6 |
+
convolutions and the TN-gram / n-gram history restart, as in training. Generation recomputes the
|
| 7 |
+
whole prefix each step (no cache): fine for scoring and short samples.
|
| 8 |
+
|
| 9 |
+
Architecture follows MinimaLabs/KLM-1.6's modeling_klm.py (Apache-2.0), with Block Attention
|
| 10 |
+
Residuals (arXiv 2603.15031) and TN-gram n-gram embeddings (arXiv 2606.08347).
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import math
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn as nn
|
| 18 |
+
import torch.nn.functional as F
|
| 19 |
+
from transformers import PreTrainedModel
|
| 20 |
+
from transformers.generation import GenerationMixin
|
| 21 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
from .configuration_aquila import AquilaConfig
|
| 25 |
+
except ImportError:
|
| 26 |
+
from configuration_aquila import AquilaConfig
|
| 27 |
+
|
| 28 |
+
CONV = 4
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class RMSNorm(nn.Module):
|
| 32 |
+
def __init__(self, dim, eps):
|
| 33 |
+
super().__init__()
|
| 34 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 35 |
+
self.eps = eps
|
| 36 |
+
|
| 37 |
+
def forward(self, x):
|
| 38 |
+
return F.rms_norm(x, (x.shape[-1],), self.weight.to(x.dtype), self.eps)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def segments(tokens, eos_id):
|
| 42 |
+
B, T = tokens.shape
|
| 43 |
+
starts = torch.zeros_like(tokens, dtype=torch.bool)
|
| 44 |
+
starts[:, 1:] = tokens[:, :-1] == eos_id
|
| 45 |
+
starts[:, 0] = True
|
| 46 |
+
idx = torch.arange(T, device=tokens.device).expand(B, T)
|
| 47 |
+
pos = idx - torch.where(starts, idx, 0).cummax(1).values
|
| 48 |
+
return starts, starts.cumsum(1), pos
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def rope(x, positions, theta):
|
| 52 |
+
"""Half-rotation RoPE on (B, H, T, D)."""
|
| 53 |
+
dim = x.shape[-1]
|
| 54 |
+
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2, device=x.device).float() / dim))
|
| 55 |
+
ang = positions.float()[:, None] * freqs
|
| 56 |
+
cos, sin = ang.cos().to(x.dtype), ang.sin().to(x.dtype)
|
| 57 |
+
x1, x2 = x.chunk(2, dim=-1)
|
| 58 |
+
return torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], dim=-1)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def attnres(query, residuals, rms_weight, out_weight, eps):
|
| 62 |
+
"""Block-AttnRes mix (same math as fla's naive_attnres): softmax over sources of
|
| 63 |
+
RMSNorm(source) . query, weighted sum of the raw sources, then the output RMSNorm."""
|
| 64 |
+
v = torch.stack(residuals, 0).float()
|
| 65 |
+
k = F.rms_norm(v, (v.shape[-1],), rms_weight.float(), eps)
|
| 66 |
+
p = (k @ query.float()).softmax(0)
|
| 67 |
+
o = (p.unsqueeze(-1) * v).sum(0)
|
| 68 |
+
return F.rms_norm(o, (o.shape[-1],), out_weight.float(), eps).to(residuals[0].dtype)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# ----------------------------------------------------------------------------- memories
|
| 72 |
+
|
| 73 |
+
def lookup(keys, queries):
|
| 74 |
+
queries = queries.to(keys.dtype)
|
| 75 |
+
p = torch.searchsorted(keys, queries).clamp_(max=keys.numel() - 1)
|
| 76 |
+
return torch.where(keys[p] == queries, p + 1, 0)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class NgramMemory(nn.Module):
|
| 80 |
+
def __init__(self, cfg):
|
| 81 |
+
super().__init__()
|
| 82 |
+
self.vocab_size = cfg.vocab_size
|
| 83 |
+
self.register_buffer("bigram_keys", torch.zeros(cfg.n_bigrams, dtype=torch.int32))
|
| 84 |
+
self.register_buffer("trigram_keys", torch.zeros(cfg.n_trigrams, dtype=torch.int64))
|
| 85 |
+
self.bigram = nn.Embedding(cfg.n_bigrams + 1, cfg.ngram_dim)
|
| 86 |
+
self.trigram = nn.Embedding(cfg.n_trigrams + 1, cfg.ngram_dim)
|
| 87 |
+
self.bigram_proj = nn.Linear(cfg.ngram_dim, cfg.hidden_size, bias=False)
|
| 88 |
+
self.trigram_proj = nn.Linear(cfg.ngram_dim, cfg.hidden_size, bias=False)
|
| 89 |
+
|
| 90 |
+
def forward(self, tokens, eos_id):
|
| 91 |
+
t = tokens.long()
|
| 92 |
+
n, v = t.shape[1], self.vocab_size
|
| 93 |
+
prev1 = F.pad(t, (1, 0))[:, :n]
|
| 94 |
+
prev2 = F.pad(t, (2, 0))[:, :n]
|
| 95 |
+
reset = prev1 == eos_id
|
| 96 |
+
prev1 = prev1.masked_fill(reset, 0)
|
| 97 |
+
prev2 = prev2.masked_fill(reset | (prev2 == eos_id), 0)
|
| 98 |
+
return (self.bigram_proj(self.bigram(lookup(self.bigram_keys, prev1 * v + t)))
|
| 99 |
+
+ self.trigram_proj(self.trigram(lookup(self.trigram_keys, (prev2 * v + prev1) * v + t))))
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class TNGram(nn.Module):
|
| 103 |
+
def __init__(self, cfg):
|
| 104 |
+
super().__init__()
|
| 105 |
+
self.orders = tuple(sorted(cfg.tn_orders))
|
| 106 |
+
self.N = max(self.orders)
|
| 107 |
+
R = cfg.tn_rank
|
| 108 |
+
self.factors = nn.Parameter(torch.zeros(self.N, cfg.vocab_size, R))
|
| 109 |
+
self.absorb = nn.Parameter(torch.ones(max(self.N - 2, 1), R))
|
| 110 |
+
self.log_s = nn.Parameter(torch.zeros(len(self.orders)))
|
| 111 |
+
self.out_dim = len(self.orders) * R
|
| 112 |
+
|
| 113 |
+
def forward(self, tokens, pos):
|
| 114 |
+
N = self.N
|
| 115 |
+
prod = F.embedding(tokens, self.factors[N - 1]).float()
|
| 116 |
+
outs = []
|
| 117 |
+
for lag in range(1, N):
|
| 118 |
+
prev = F.pad(tokens, (lag, 0))[:, : tokens.shape[1]]
|
| 119 |
+
prod = prod * F.embedding(prev, self.factors[N - 1 - lag]).float()
|
| 120 |
+
n = lag + 1
|
| 121 |
+
if n in self.orders:
|
| 122 |
+
unused = N - n
|
| 123 |
+
b = prod * self.absorb[:unused].float().prod(0) if unused > 0 else prod
|
| 124 |
+
e = F.rms_norm(b, (b.shape[-1],), eps=1e-6) * self.log_s[self.orders.index(n)].float().exp()
|
| 125 |
+
outs.append(e * (pos >= lag).unsqueeze(-1))
|
| 126 |
+
return torch.cat(outs, -1)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class TNGramHead(nn.Module):
|
| 130 |
+
def __init__(self, cfg, in_dim, dilation):
|
| 131 |
+
super().__init__()
|
| 132 |
+
d = cfg.hidden_size
|
| 133 |
+
self.k_proj = nn.Linear(in_dim, d, bias=False)
|
| 134 |
+
self.v_proj = nn.Linear(in_dim, d, bias=False)
|
| 135 |
+
self.h_norm = RMSNorm(d, cfg.rms_norm_eps)
|
| 136 |
+
self.k_norm = RMSNorm(d, cfg.rms_norm_eps)
|
| 137 |
+
self.v_norm = RMSNorm(d, cfg.rms_norm_eps)
|
| 138 |
+
self.conv = nn.Parameter(torch.zeros(d, cfg.tn_conv))
|
| 139 |
+
self.dilation = dilation
|
| 140 |
+
|
| 141 |
+
def forward(self, h_normed, e, pos):
|
| 142 |
+
e = e.to(h_normed.dtype)
|
| 143 |
+
k, v = self.k_proj(e), self.v_proj(e)
|
| 144 |
+
alpha = (h_normed.float() * self.k_norm(k).float()).sum(-1) / math.sqrt(k.shape[-1])
|
| 145 |
+
gate = torch.sigmoid(alpha.sign() * alpha.abs().clamp_min(1e-6).sqrt())
|
| 146 |
+
vt = gate.unsqueeze(-1).to(v.dtype) * v
|
| 147 |
+
z = self.v_norm(vt)
|
| 148 |
+
K, T = self.conv.shape[1], z.shape[1]
|
| 149 |
+
acc = 0
|
| 150 |
+
for i in range(K):
|
| 151 |
+
lag = (K - 1 - i) * self.dilation
|
| 152 |
+
zl = z if lag == 0 else F.pad(z, (0, 0, lag, 0))[:, :T]
|
| 153 |
+
if lag:
|
| 154 |
+
zl = zl * (pos >= lag).unsqueeze(-1).to(zl.dtype)
|
| 155 |
+
acc = acc + zl * self.conv[:, i].to(zl.dtype)
|
| 156 |
+
return vt + F.silu(acc)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
# ----------------------------------------------------------------------------- mixers
|
| 160 |
+
|
| 161 |
+
class Attention(nn.Module):
|
| 162 |
+
def __init__(self, cfg):
|
| 163 |
+
super().__init__()
|
| 164 |
+
d = cfg.hidden_size
|
| 165 |
+
self.n_heads, self.n_kv = cfg.num_attention_heads, cfg.num_key_value_heads
|
| 166 |
+
self.head_dim = d // self.n_heads
|
| 167 |
+
self.theta = cfg.rope_theta
|
| 168 |
+
self.q_proj = nn.Linear(d, self.n_heads * self.head_dim, bias=False)
|
| 169 |
+
self.k_proj = nn.Linear(d, self.n_kv * self.head_dim, bias=False)
|
| 170 |
+
self.v_proj = nn.Linear(d, self.n_kv * self.head_dim, bias=False)
|
| 171 |
+
self.gate_proj = nn.Linear(d, d, bias=False)
|
| 172 |
+
self.o_proj = nn.Linear(d, d, bias=False)
|
| 173 |
+
self.q_norm = RMSNorm(self.head_dim, cfg.rms_norm_eps)
|
| 174 |
+
self.k_norm = RMSNorm(self.head_dim, cfg.rms_norm_eps)
|
| 175 |
+
self.value_mix = nn.Parameter(torch.tensor([0.5, 0.5]))
|
| 176 |
+
|
| 177 |
+
def forward(self, x, v_first, positions, mask):
|
| 178 |
+
B, T, d = x.shape
|
| 179 |
+
q = self.q_proj(x).view(B, T, self.n_heads, self.head_dim)
|
| 180 |
+
k = self.k_proj(x).view(B, T, self.n_kv, self.head_dim)
|
| 181 |
+
v = self.v_proj(x).view(B, T, self.n_kv, self.head_dim)
|
| 182 |
+
if v_first is None:
|
| 183 |
+
v_first = v
|
| 184 |
+
mix = self.value_mix.float()
|
| 185 |
+
values = (mix[0] * v.float() + mix[1] * v_first.float()).to(x.dtype).transpose(1, 2)
|
| 186 |
+
q = rope(self.q_norm(q.float()).transpose(1, 2), positions, self.theta).to(x.dtype)
|
| 187 |
+
k = rope(self.k_norm(k.float()).transpose(1, 2), positions, self.theta).to(x.dtype)
|
| 188 |
+
rep = self.n_heads // self.n_kv
|
| 189 |
+
k, values = k.repeat_interleave(rep, 1), values.repeat_interleave(rep, 1)
|
| 190 |
+
out = F.scaled_dot_product_attention(q, k, values, attn_mask=mask)
|
| 191 |
+
out = out.transpose(1, 2).reshape(B, T, d)
|
| 192 |
+
return self.o_proj(out * torch.sigmoid(self.gate_proj(x))), v_first
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def short_conv(weight, x, taps_valid):
|
| 196 |
+
B, T, C = x.shape
|
| 197 |
+
ext = torch.cat([x.new_zeros(B, CONV - 1, C), x], 1)
|
| 198 |
+
windows = ext.unfold(1, CONV, 1) # (B, T, C, CONV), oldest first
|
| 199 |
+
out = (windows * weight.view(C, CONV).to(x.dtype) * taps_valid.unsqueeze(2)).sum(-1)
|
| 200 |
+
return F.silu(out)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def l2norm(x):
|
| 204 |
+
return x * torch.rsqrt((x * x).sum(-1, keepdim=True) + 1e-6)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def recurrence(q, k, v, g, b, w, starts):
|
| 208 |
+
"""GDN-2 step by step in fp32: S <- (I - k (b*k)^T) diag(exp g) S + k (w*v)^T; o = q^T S / sqrt(K)."""
|
| 209 |
+
B, T, H, K = k.shape
|
| 210 |
+
q = q * K ** -0.5
|
| 211 |
+
state = q.new_zeros(B, H, K, v.shape[-1])
|
| 212 |
+
keep = (~starts).float()
|
| 213 |
+
out = []
|
| 214 |
+
for t in range(T):
|
| 215 |
+
state = state * (keep[:, t, None, None, None] * g[:, t].exp().unsqueeze(-1))
|
| 216 |
+
erase = torch.einsum("bhk,bhkv->bhv", b[:, t] * k[:, t], state)
|
| 217 |
+
state = state + k[:, t].unsqueeze(-1) * (w[:, t] * v[:, t] - erase).unsqueeze(-2)
|
| 218 |
+
out.append(torch.einsum("bhk,bhkv->bhv", q[:, t], state))
|
| 219 |
+
return torch.stack(out, 1)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
class GatedDeltaNet2(nn.Module):
|
| 223 |
+
def __init__(self, cfg):
|
| 224 |
+
super().__init__()
|
| 225 |
+
d, self.heads, self.head_dim = cfg.hidden_size, cfg.gdn_heads, cfg.gdn_head_dim
|
| 226 |
+
inner = self.heads * self.head_dim
|
| 227 |
+
self.decay_floor = cfg.decay_floor
|
| 228 |
+
self.q_proj = nn.Linear(d, inner, bias=False)
|
| 229 |
+
self.k_proj = nn.Linear(d, inner, bias=False)
|
| 230 |
+
self.v_proj = nn.Linear(d, inner, bias=False)
|
| 231 |
+
self.q_conv1d = nn.Conv1d(inner, inner, CONV, groups=inner, bias=False)
|
| 232 |
+
self.k_conv1d = nn.Conv1d(inner, inner, CONV, groups=inner, bias=False)
|
| 233 |
+
self.v_conv1d = nn.Conv1d(inner, inner, CONV, groups=inner, bias=False)
|
| 234 |
+
self.f_proj = nn.Sequential(nn.Linear(d, self.head_dim, bias=False),
|
| 235 |
+
nn.Linear(self.head_dim, inner, bias=False))
|
| 236 |
+
self.b_proj = nn.Linear(d, inner, bias=False)
|
| 237 |
+
self.w_proj = nn.Linear(d, inner, bias=False)
|
| 238 |
+
self.A_log = nn.Parameter(torch.zeros(self.heads))
|
| 239 |
+
self.dt_bias = nn.Parameter(torch.zeros(inner))
|
| 240 |
+
self.g_proj = nn.Sequential(nn.Linear(d, self.head_dim, bias=False),
|
| 241 |
+
nn.Linear(self.head_dim, inner, bias=True))
|
| 242 |
+
self.o_norm = RMSNorm(self.head_dim, cfg.gdn_norm_eps)
|
| 243 |
+
self.o_proj = nn.Linear(inner, d, bias=False)
|
| 244 |
+
|
| 245 |
+
def log_decay(self, x):
|
| 246 |
+
s = self.f_proj(x).float().unflatten(-1, (self.heads, self.head_dim)) + \
|
| 247 |
+
self.dt_bias.float().view(self.heads, self.head_dim)
|
| 248 |
+
log_act = torch.where(s < -20, s, F.softplus(s.clamp_min(-20)).log())
|
| 249 |
+
log_mag = self.A_log.float().unsqueeze(-1) + log_act
|
| 250 |
+
ceiling = math.log(-self.decay_floor)
|
| 251 |
+
return torch.where(log_mag >= ceiling, torch.full_like(log_mag, self.decay_floor),
|
| 252 |
+
-log_mag.clamp(max=ceiling).exp())
|
| 253 |
+
|
| 254 |
+
def forward(self, x, starts, taps_valid):
|
| 255 |
+
B, T, _ = x.shape
|
| 256 |
+
q = short_conv(self.q_conv1d.weight, self.q_proj(x), taps_valid)
|
| 257 |
+
k = short_conv(self.k_conv1d.weight, self.k_proj(x), taps_valid)
|
| 258 |
+
v = short_conv(self.v_conv1d.weight, self.v_proj(x), taps_valid)
|
| 259 |
+
heads = lambda t: t.float().view(B, T, self.heads, self.head_dim) # noqa: E731
|
| 260 |
+
o = recurrence(l2norm(heads(q)), l2norm(heads(k)), heads(v), self.log_decay(x),
|
| 261 |
+
torch.sigmoid(heads(self.b_proj(x))), torch.sigmoid(heads(self.w_proj(x))), starts)
|
| 262 |
+
gate = self.g_proj(x).view(B, T, self.heads, self.head_dim)
|
| 263 |
+
o = self.o_norm(o.to(x.dtype)) * torch.sigmoid(gate)
|
| 264 |
+
return self.o_proj(o.reshape(B, T, -1))
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
class SwiGLU(nn.Module):
|
| 268 |
+
def __init__(self, d, hidden):
|
| 269 |
+
super().__init__()
|
| 270 |
+
self.gate = nn.Linear(d, hidden, bias=False)
|
| 271 |
+
self.up = nn.Linear(d, hidden, bias=False)
|
| 272 |
+
self.down = nn.Linear(hidden, d, bias=False)
|
| 273 |
+
|
| 274 |
+
def forward(self, x):
|
| 275 |
+
return self.down(F.silu(self.gate(x)) * self.up(x))
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
class Block(nn.Module):
|
| 279 |
+
def __init__(self, cfg, index):
|
| 280 |
+
super().__init__()
|
| 281 |
+
self.is_attention = cfg.is_attention(index)
|
| 282 |
+
self.mixer_norm = RMSNorm(cfg.hidden_size, cfg.rms_norm_eps)
|
| 283 |
+
self.mixer = Attention(cfg) if self.is_attention else GatedDeltaNet2(cfg)
|
| 284 |
+
self.ffn_norm = RMSNorm(cfg.hidden_size, cfg.rms_norm_eps)
|
| 285 |
+
self.ffn = SwiGLU(cfg.hidden_size, cfg.intermediate_size)
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
class AquilaModel(nn.Module):
|
| 289 |
+
def __init__(self, cfg: AquilaConfig):
|
| 290 |
+
super().__init__()
|
| 291 |
+
self.cfg = cfg
|
| 292 |
+
d, L = cfg.hidden_size, cfg.num_hidden_layers
|
| 293 |
+
self.embed = nn.Embedding(cfg.vocab_size, d)
|
| 294 |
+
if cfg.memory == "klm":
|
| 295 |
+
self.memory = NgramMemory(cfg)
|
| 296 |
+
elif cfg.memory == "tngram":
|
| 297 |
+
self.tngram = TNGram(cfg)
|
| 298 |
+
self.tn_heads = nn.ModuleList([TNGramHead(cfg, self.tngram.out_dim, self.tngram.N)
|
| 299 |
+
for _ in cfg.tn_insert_before])
|
| 300 |
+
n = len(cfg.tn_insert_before)
|
| 301 |
+
self.tn_query = nn.Parameter(torch.zeros(n, d))
|
| 302 |
+
self.tn_query_norm = nn.Parameter(torch.ones(n, d))
|
| 303 |
+
self.blocks = nn.ModuleList([Block(cfg, i) for i in range(L)])
|
| 304 |
+
self.attn_res_query = nn.Parameter(torch.zeros(2 * L + 1, d))
|
| 305 |
+
self.attn_res_norm = nn.Parameter(torch.ones(2 * L + 1, d))
|
| 306 |
+
self.norm = RMSNorm(d, cfg.rms_norm_eps)
|
| 307 |
+
|
| 308 |
+
def _mix(self, i, sources, out_norm, partial=None):
|
| 309 |
+
res = sources if partial is None else sources + [partial]
|
| 310 |
+
return attnres(self.attn_res_query[i], res, self.attn_res_norm[i], out_norm, self.cfg.rms_norm_eps)
|
| 311 |
+
|
| 312 |
+
def forward(self, tokens):
|
| 313 |
+
cfg, eps = self.cfg, self.cfg.rms_norm_eps
|
| 314 |
+
B, T = tokens.shape
|
| 315 |
+
starts, docs, pos = segments(tokens, cfg.eos_token_id)
|
| 316 |
+
positions = torch.arange(T, device=tokens.device)
|
| 317 |
+
causal = positions[None, :] <= positions[:, None]
|
| 318 |
+
mask = ((docs[:, :, None] == docs[:, None, :]) & causal).unsqueeze(1)
|
| 319 |
+
lags = torch.arange(CONV - 1, -1, -1, device=tokens.device)
|
| 320 |
+
taps_valid = (pos[..., None] >= lags).to(self.embed.weight.dtype)
|
| 321 |
+
first = self.embed(tokens)
|
| 322 |
+
dt = first.dtype
|
| 323 |
+
sources = [first]
|
| 324 |
+
if cfg.memory == "klm":
|
| 325 |
+
sources.append(self.memory(tokens, cfg.eos_token_id).to(dt))
|
| 326 |
+
e_tn = None
|
| 327 |
+
if cfg.memory == "tngram" and cfg.tn_scale > 0:
|
| 328 |
+
e_tn = self.tngram(tokens, pos)
|
| 329 |
+
G, partial, v_first = cfg.attnres_group, None, None
|
| 330 |
+
for i, block in enumerate(self.blocks):
|
| 331 |
+
if partial is not None and i % G == 0:
|
| 332 |
+
sources.append(partial)
|
| 333 |
+
partial = None
|
| 334 |
+
if e_tn is not None and i in cfg.tn_insert_before:
|
| 335 |
+
j = cfg.tn_insert_before.index(i)
|
| 336 |
+
head = self.tn_heads[j]
|
| 337 |
+
res = sources if partial is None else sources + [partial]
|
| 338 |
+
h = attnres(self.tn_query[j], res, self.tn_query_norm[j], head.h_norm.weight, eps)
|
| 339 |
+
sources.append((cfg.tn_scale * head(h, e_tn, pos)).to(dt))
|
| 340 |
+
h = self._mix(2 * i, sources, block.mixer_norm.weight, partial)
|
| 341 |
+
if block.is_attention:
|
| 342 |
+
out, v_first = block.mixer(h, v_first, positions, mask)
|
| 343 |
+
else:
|
| 344 |
+
out = block.mixer(h, starts, taps_valid)
|
| 345 |
+
out = out.to(dt)
|
| 346 |
+
partial = out if partial is None else partial + out
|
| 347 |
+
f = block.ffn(self._mix(2 * i + 1, sources, block.ffn_norm.weight, partial))
|
| 348 |
+
partial = (partial + f).to(dt)
|
| 349 |
+
x = self._mix(2 * cfg.num_hidden_layers, sources, self.norm.weight, partial)
|
| 350 |
+
return F.linear(x, self.embed.weight.to(x.dtype))
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
class AquilaForCausalLM(PreTrainedModel, GenerationMixin):
|
| 354 |
+
config_class = AquilaConfig
|
| 355 |
+
base_model_prefix = "model"
|
| 356 |
+
main_input_name = "input_ids"
|
| 357 |
+
_no_split_modules = ["Block"]
|
| 358 |
+
|
| 359 |
+
def __init__(self, config: AquilaConfig):
|
| 360 |
+
super().__init__(config)
|
| 361 |
+
self.model = AquilaModel(config)
|
| 362 |
+
self.post_init()
|
| 363 |
+
|
| 364 |
+
def _init_weights(self, module):
|
| 365 |
+
pass # every weight comes from the checkpoint
|
| 366 |
+
|
| 367 |
+
def get_input_embeddings(self):
|
| 368 |
+
return self.model.embed
|
| 369 |
+
|
| 370 |
+
def set_input_embeddings(self, value):
|
| 371 |
+
self.model.embed = value
|
| 372 |
+
|
| 373 |
+
def get_output_embeddings(self):
|
| 374 |
+
return self.model.embed # tied: logits use the input embedding matrix
|
| 375 |
+
|
| 376 |
+
def forward(self, input_ids, attention_mask=None, labels=None, **kwargs):
|
| 377 |
+
logits = self.model(input_ids)
|
| 378 |
+
loss = None
|
| 379 |
+
if labels is not None:
|
| 380 |
+
loss = F.cross_entropy(logits[:, :-1].float().reshape(-1, logits.shape[-1]),
|
| 381 |
+
labels[:, 1:].reshape(-1), ignore_index=-100)
|
| 382 |
+
return CausalLMOutputWithPast(loss=loss, logits=logits)
|
| 383 |
+
|
| 384 |
+
def prepare_inputs_for_generation(self, input_ids, **kwargs):
|
| 385 |
+
return {"input_ids": input_ids}
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"pad_token": "<pad>",
|
| 3 |
+
"bos_token": "<bos>",
|
| 4 |
+
"eos_token": "<eos>",
|
| 5 |
+
"additional_special_tokens": [
|
| 6 |
+
"<|im_start|>",
|
| 7 |
+
"<|im_end|>",
|
| 8 |
+
"<think>",
|
| 9 |
+
"</think>"
|
| 10 |
+
]
|
| 11 |
+
}
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"tokenizer_class": "PreTrainedTokenizerFast",
|
| 3 |
+
"model_max_length": 2048,
|
| 4 |
+
"pad_token": "<pad>",
|
| 5 |
+
"bos_token": "<bos>",
|
| 6 |
+
"eos_token": "<eos>",
|
| 7 |
+
"additional_special_tokens": [
|
| 8 |
+
"<|im_start|>",
|
| 9 |
+
"<|im_end|>",
|
| 10 |
+
"<think>",
|
| 11 |
+
"</think>"
|
| 12 |
+
],
|
| 13 |
+
"add_bos_token": false,
|
| 14 |
+
"add_eos_token": false,
|
| 15 |
+
"clean_up_tokenization_spaces": false,
|
| 16 |
+
"model_input_names": [
|
| 17 |
+
"input_ids",
|
| 18 |
+
"attention_mask"
|
| 19 |
+
]
|
| 20 |
+
}
|