Text Generation
Transformers
Safetensors
Nepali
Maithili
Bhojpuri
amadablam
nepali
maithili
bhojpuri
devanagari
iast
transliteration
linear-attention
hybrid-attention
conversational
custom_code
Instructions to use spandyie/amadablam-322m with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use spandyie/amadablam-322m with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="spandyie/amadablam-322m", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("spandyie/amadablam-322m", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use spandyie/amadablam-322m with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "spandyie/amadablam-322m" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "spandyie/amadablam-322m", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/spandyie/amadablam-322m
- SGLang
How to use spandyie/amadablam-322m 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 "spandyie/amadablam-322m" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "spandyie/amadablam-322m", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'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 "spandyie/amadablam-322m" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "spandyie/amadablam-322m", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use spandyie/amadablam-322m with Docker Model Runner:
docker model run hf.co/spandyie/amadablam-322m
Upload folder using huggingface_hub
Browse files- README.md +44 -0
- chat_template.jinja +1 -0
- config.json +25 -0
- configuration_amadablam.py +33 -0
- generation_config.json +5 -0
- model.safetensors +3 -0
- modeling_amadablam.py +324 -0
- tokenizer.json +0 -0
- tokenizer_config.json +8 -0
README.md
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language: [ne, mai, bho]
|
| 3 |
+
license: apache-2.0
|
| 4 |
+
library_name: transformers
|
| 5 |
+
pipeline_tag: text-generation
|
| 6 |
+
tags: [nepali, maithili, bhojpuri, devanagari, iast, transliteration, linear-attention, hybrid-attention]
|
| 7 |
+
---
|
| 8 |
+
|
| 9 |
+
# Ama Dablam 322M (base)
|
| 10 |
+
|
| 11 |
+
A 322M-parameter decoder-only LM pretrained **from scratch** on Nepali, Maithili, and
|
| 12 |
+
Bhojpuri in three writing systems: Devanagari, IAST, and natural phonetic
|
| 13 |
+
romanization. 12 of 14 layers use linear attention with per-head exponential decay
|
| 14 |
+
(base 0.7); 2 use full softmax. 17.1B training tokens, 16,384-entry trilingual BPE.
|
| 15 |
+
|
| 16 |
+
| val bpb (lower=better) | ne | mai | bho | iast_ne | phon_ne |
|
| 17 |
+
|---|---|---|---|---|---|
|
| 18 |
+
| Ama Dablam base | **0.406** | **0.368** | **0.546** | 0.326 | 0.942 |
|
| 19 |
+
| Manaslu 491M dense (prior) | 0.432 | 0.438 | 0.632 | 0.386 | — |
|
| 20 |
+
|
| 21 |
+
## Usage
|
| 22 |
+
|
| 23 |
+
```python
|
| 24 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 25 |
+
tok = AutoTokenizer.from_pretrained("spandyie/amadablam-322m")
|
| 26 |
+
model = AutoModelForCausalLM.from_pretrained("spandyie/amadablam-322m",
|
| 27 |
+
trust_remote_code=True)
|
| 28 |
+
ids = tok("नेपालको इतिहास", return_tensors="pt").input_ids
|
| 29 |
+
print(tok.decode(model.generate(ids, max_new_tokens=100, do_sample=True)[0]))
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
## Details & limitations
|
| 33 |
+
|
| 34 |
+
- Config serializes `linear_decay=0.7` — required at construction; handled
|
| 35 |
+
automatically here.
|
| 36 |
+
- Base model: no instruction following (see `spandyie/amadablam-322m-instruct`).
|
| 37 |
+
- **This model is cacheless by design.** `generation_config.json` sets
|
| 38 |
+
`use_cache: false` by default. If you override generation kwargs, do not set
|
| 39 |
+
`use_cache=True` — it will silently produce incoherent, context-free output
|
| 40 |
+
rather than an error (only the last token gets fed back each step).
|
| 41 |
+
- Right-pad with the BOS token (id 16368); attention_mask is accepted but unused.
|
| 42 |
+
- 322M params / 17.1B tokens: factual knowledge is limited; single-seed training run.
|
| 43 |
+
- Pretraining corpus: web/news/wiki + curated Nepali sets, dedup + quality-gated;
|
| 44 |
+
phonetic slices generated by deterministic transliteration.
|
chat_template.jinja
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{{ '<|reserved_0|>' }}{% for message in messages %}{% if message['role'] == 'user' %}{{ '<|reserved_1|>' + message['content'] }}{% elif message['role'] == 'assistant' %}{{ '<|reserved_2|>' + message['content'] + '<|reserved_3|>' }}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '<|reserved_2|>' }}{% endif %}
|
config.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"AmadablamForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "configuration_amadablam.AmadablamConfig",
|
| 7 |
+
"AutoModelForCausalLM": "modeling_amadablam.AmadablamForCausalLM"
|
| 8 |
+
},
|
| 9 |
+
"dense_every": 8,
|
| 10 |
+
"dtype": "float32",
|
| 11 |
+
"hidden_size": 1280,
|
| 12 |
+
"linear_chunk": 128,
|
| 13 |
+
"linear_decay": 0.7,
|
| 14 |
+
"logit_softcap": 15.0,
|
| 15 |
+
"max_position_embeddings": 8192,
|
| 16 |
+
"model_type": "amadablam",
|
| 17 |
+
"num_attention_heads": 10,
|
| 18 |
+
"num_hidden_layers": 14,
|
| 19 |
+
"num_key_value_heads": 5,
|
| 20 |
+
"rope_theta": 10000.0,
|
| 21 |
+
"tie_word_embeddings": false,
|
| 22 |
+
"transformers_version": "5.14.1",
|
| 23 |
+
"use_cache": false,
|
| 24 |
+
"vocab_size": 16384
|
| 25 |
+
}
|
configuration_amadablam.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# configuration_amadablam.py
|
| 2 |
+
"""HF config for Ama Dablam. Crucially serializes linear_decay and dense_every —
|
| 3 |
+
architecture constants that the research checkpoints do NOT store (a loader
|
| 4 |
+
without them silently builds a different model)."""
|
| 5 |
+
|
| 6 |
+
from transformers import PretrainedConfig
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class AmadablamConfig(PretrainedConfig):
|
| 10 |
+
model_type = "amadablam"
|
| 11 |
+
|
| 12 |
+
def __init__(self, vocab_size=16384, hidden_size=1280, num_hidden_layers=14,
|
| 13 |
+
num_attention_heads=10, num_key_value_heads=5,
|
| 14 |
+
max_position_embeddings=8192, linear_decay=0.7, dense_every=8,
|
| 15 |
+
linear_chunk=128, logit_softcap=15.0, rope_theta=10000.0,
|
| 16 |
+
use_cache=False, tie_word_embeddings=False, **kwargs):
|
| 17 |
+
self.vocab_size = vocab_size
|
| 18 |
+
self.hidden_size = hidden_size
|
| 19 |
+
self.num_hidden_layers = num_hidden_layers
|
| 20 |
+
self.num_attention_heads = num_attention_heads
|
| 21 |
+
self.num_key_value_heads = num_key_value_heads
|
| 22 |
+
self.max_position_embeddings = max_position_embeddings
|
| 23 |
+
self.linear_decay = linear_decay
|
| 24 |
+
self.dense_every = dense_every
|
| 25 |
+
self.linear_chunk = linear_chunk
|
| 26 |
+
self.logit_softcap = logit_softcap
|
| 27 |
+
self.rope_theta = rope_theta
|
| 28 |
+
self.use_cache = use_cache
|
| 29 |
+
self.auto_map = {
|
| 30 |
+
"AutoConfig": "configuration_amadablam.AmadablamConfig",
|
| 31 |
+
"AutoModelForCausalLM": "modeling_amadablam.AmadablamForCausalLM",
|
| 32 |
+
}
|
| 33 |
+
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
|
generation_config.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token_id": 16368,
|
| 3 |
+
"pad_token_id": 16368,
|
| 4 |
+
"use_cache": false
|
| 5 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:03ac3cb0f3b9d667f6b77f8d65314f3c799b503190807d439094f00b728e1998
|
| 3 |
+
size 1287142504
|
modeling_amadablam.py
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# modeling_amadablam.py
|
| 2 |
+
"""Ama Dablam: linear-attention (per-head decayed, chunked O(T)) + 1-in-`dense_every`
|
| 3 |
+
softmax layers (last layer forced dense). Faithful port of the research model
|
| 4 |
+
(`version2_linear_pretrain_inference.py` / `version2_pretrain_inference.py`);
|
| 5 |
+
parameter names are identical, so research checkpoints convert by strict copy.
|
| 6 |
+
|
| 7 |
+
Cacheless v1: `attention_mask` and `past_key_values` are accepted and ignored;
|
| 8 |
+
right-pad with BOS (id 16368) to match training. The math (feature map, per-head
|
| 9 |
+
decay gammas, chunked linear attention, RoPE, GQA softmax, value-embed gating,
|
| 10 |
+
residual/x0 lambdas, logit softcap) is copied verbatim from the research source;
|
| 11 |
+
the only changes are (a) module globals -> config fields (`linear_decay`,
|
| 12 |
+
`dense_every`, `linear_chunk`) and (b) research config names -> HF names. Numerics
|
| 13 |
+
verified against the research model to <=1e-4."""
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torch.nn.functional as F
|
| 17 |
+
from torch import nn
|
| 18 |
+
from transformers import PreTrainedModel, GenerationMixin
|
| 19 |
+
from transformers.modeling_outputs import CausalLMOutput
|
| 20 |
+
|
| 21 |
+
try: # trust_remote_code: loaded as a package sibling
|
| 22 |
+
from .configuration_amadablam import AmadablamConfig
|
| 23 |
+
except ImportError: # direct/test usage: loaded as a top-level module
|
| 24 |
+
from configuration_amadablam import AmadablamConfig
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# ---------------------------------------------------------------------------
|
| 28 |
+
# Base helpers (verbatim from version2_pretrain_inference.py)
|
| 29 |
+
# ---------------------------------------------------------------------------
|
| 30 |
+
|
| 31 |
+
def norm(x):
|
| 32 |
+
return F.rms_norm(x, (x.size(-1),))
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def has_ve(layer_idx, n_layer):
|
| 36 |
+
return layer_idx % 2 == (n_layer - 1) % 2
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def apply_rotary_emb(x, cos, sin):
|
| 40 |
+
assert x.ndim == 4
|
| 41 |
+
d = x.shape[3] // 2
|
| 42 |
+
x1, x2 = x[..., :d], x[..., d:]
|
| 43 |
+
return torch.cat([x1 * cos + x2 * sin, x1 * (-sin) + x2 * cos], 3)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# ---------------------------------------------------------------------------
|
| 47 |
+
# Linear attention (linear transformer, causal, normalised) — verbatim math
|
| 48 |
+
# from version2_linear_pretrain_inference.py, with LINEAR_DECAY/LINEAR_CHUNK
|
| 49 |
+
# threaded as arguments (gammas precomputed; None = vanilla no-decay path).
|
| 50 |
+
# ---------------------------------------------------------------------------
|
| 51 |
+
|
| 52 |
+
def feature_map(x):
|
| 53 |
+
return F.elu(x) + 1.0 # positive feature map
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _head_gammas(H, device, linear_decay):
|
| 57 |
+
"""Per-head decay rates in (0,1), log-spaced around `linear_decay` (larger ->
|
| 58 |
+
longer memory). Returns float32 [H]. Matches research `_head_gammas` with the
|
| 59 |
+
module-global LINEAR_DECAY replaced by the `linear_decay` argument."""
|
| 60 |
+
expo = torch.linspace(1.0, 2.0, H, device=device, dtype=torch.float32)
|
| 61 |
+
return 1.0 - (1.0 - float(linear_decay)) ** expo # [H]
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _exclusive_cumsum(x, dim):
|
| 65 |
+
"""Prefix sum EXCLUDING the current element (state entering each chunk)."""
|
| 66 |
+
return torch.cumsum(x, dim=dim) - x
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def linear_attention_chunked(q, k, v, gammas, chunk, eps=1e-6):
|
| 70 |
+
"""O(T) causal normalised linear attention, VECTORISED over chunks. q,k,v:
|
| 71 |
+
[B, H, T, D]. `gammas` is the per-head decay tensor [H] (None -> vanilla, no
|
| 72 |
+
decay). `chunk` is the chunk size. Verbatim from the research kernel with the
|
| 73 |
+
module-global decay/chunk replaced by arguments."""
|
| 74 |
+
B, H, T, D = q.shape
|
| 75 |
+
qf, kf = feature_map(q), feature_map(k)
|
| 76 |
+
n = (T + chunk - 1) // chunk
|
| 77 |
+
pad = n * chunk - T
|
| 78 |
+
if pad: # right-pad to a whole #chunks
|
| 79 |
+
qf = F.pad(qf, (0, 0, 0, pad)); kf = F.pad(kf, (0, 0, 0, pad))
|
| 80 |
+
vc = F.pad(v, (0, 0, 0, pad))
|
| 81 |
+
else:
|
| 82 |
+
vc = v
|
| 83 |
+
c = chunk
|
| 84 |
+
qf = qf.view(B, H, n, c, D) # [B,H,n,c,D]
|
| 85 |
+
kf = kf.view(B, H, n, c, D)
|
| 86 |
+
vc = vc.view(B, H, n, c, D)
|
| 87 |
+
a = torch.arange(c, device=q.device)
|
| 88 |
+
causal = (a[:, None] >= a[None, :]) # [c,c] within-chunk mask
|
| 89 |
+
|
| 90 |
+
if gammas is None:
|
| 91 |
+
A = (qf @ kf.transpose(-1, -2)).masked_fill(~causal, 0.0) # [B,H,n,c,c] intra
|
| 92 |
+
num = A @ vc
|
| 93 |
+
den = A.sum(-1, keepdim=True)
|
| 94 |
+
chunk_S = kf.transpose(-1, -2) @ vc # [B,H,n,D,D] per-chunk KV
|
| 95 |
+
chunk_Z = kf.sum(3) # [B,H,n,D]
|
| 96 |
+
S = _exclusive_cumsum(chunk_S, 2) # state entering each chunk
|
| 97 |
+
Z = _exclusive_cumsum(chunk_Z, 2)
|
| 98 |
+
num = num + qf @ S # + inter-chunk (past state)
|
| 99 |
+
den = den + qf @ Z.unsqueeze(-1)
|
| 100 |
+
out = num / (den + eps)
|
| 101 |
+
return out.reshape(B, H, n * c, D)[:, :, :T].contiguous()
|
| 102 |
+
|
| 103 |
+
# decayed path: gamma_h^(i-j) recency weighting; run in float32 for stability.
|
| 104 |
+
g = gammas # [H]
|
| 105 |
+
qf, kf, vc = qf.float(), kf.float(), vc.float()
|
| 106 |
+
af = a.float()
|
| 107 |
+
within = g.view(H, 1, 1) ** (af[:, None] - af[None, :]).clamp(min=0)
|
| 108 |
+
within = (within * causal).view(1, H, 1, c, c) # [1,H,1,c,c]
|
| 109 |
+
A = (qf @ kf.transpose(-1, -2)) * within # [B,H,n,c,c] intra (batched)
|
| 110 |
+
num = A @ vc
|
| 111 |
+
den = A.sum(-1, keepdim=True)
|
| 112 |
+
# per-chunk state contribution (keys decayed to chunk end) + query read decay
|
| 113 |
+
kdec = (g[:, None] ** (c - 1.0 - af)).view(1, H, 1, c, 1)
|
| 114 |
+
qdec = (g[:, None] ** (af + 1.0)).view(1, H, 1, c, 1)
|
| 115 |
+
chunk_S = (kf * kdec).transpose(-1, -2) @ vc # [B,H,n,D,D]
|
| 116 |
+
chunk_Z = (kf * kdec).sum(3) # [B,H,n,D]
|
| 117 |
+
carry = g.view(H, 1, 1) ** float(c) # [H,1,1] per-full-chunk carry
|
| 118 |
+
# inter-chunk weighted prefix: S_i = carry*S_{i-1} + chunk_S_{i-1} (exclusive).
|
| 119 |
+
S = torch.empty_like(chunk_S)
|
| 120 |
+
Z = torch.empty_like(chunk_Z)
|
| 121 |
+
Sacc = qf.new_zeros(B, H, D, D)
|
| 122 |
+
Zacc = qf.new_zeros(B, H, D)
|
| 123 |
+
cS = carry.view(1, H, 1, 1)
|
| 124 |
+
cZ = carry.view(1, H, 1)
|
| 125 |
+
for i in range(n):
|
| 126 |
+
S[:, :, i] = Sacc
|
| 127 |
+
Z[:, :, i] = Zacc
|
| 128 |
+
Sacc = cS * Sacc + chunk_S[:, :, i]
|
| 129 |
+
Zacc = cZ * Zacc + chunk_Z[:, :, i]
|
| 130 |
+
num = num + (qf @ S) * qdec
|
| 131 |
+
den = den + (qf @ Z.unsqueeze(-1)) * qdec
|
| 132 |
+
out = (num / (den + eps)).to(v.dtype)
|
| 133 |
+
return out.reshape(B, H, n * c, D)[:, :, :T].contiguous()
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def linear_attn(q, k, v, gammas, chunk):
|
| 137 |
+
"""sdpa_attn-shaped wrapper: q,k,v are [B,T,Hq,D]/[B,T,Hkv,D]; returns
|
| 138 |
+
[B,T,Hq,D]. Verbatim from research `linear_attn`, threading gammas/chunk."""
|
| 139 |
+
q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2) # -> [B,H,T,D]
|
| 140 |
+
Hq, Hkv = q.shape[1], k.shape[1]
|
| 141 |
+
if Hkv < Hq:
|
| 142 |
+
# GQA: replicate KV per query group, matching sdpa_attn.
|
| 143 |
+
k = k.repeat_interleave(Hq // Hkv, dim=1)
|
| 144 |
+
v = v.repeat_interleave(Hq // Hkv, dim=1)
|
| 145 |
+
y = linear_attention_chunked(q, k, v, gammas, chunk)
|
| 146 |
+
return y.transpose(1, 2).contiguous()
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def sdpa_attn(q, k, v):
|
| 150 |
+
"""GQA full-causal softmax attention. q,k,v: [B,T,H,D]. Mirrors research
|
| 151 |
+
`sdpa_attn` with attn_arg=None (full causal, no window)."""
|
| 152 |
+
B, T, Hq, D = q.shape
|
| 153 |
+
Hkv = k.shape[2]
|
| 154 |
+
q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
|
| 155 |
+
if Hkv < Hq:
|
| 156 |
+
k = k.repeat_interleave(Hq // Hkv, dim=1)
|
| 157 |
+
v = v.repeat_interleave(Hq // Hkv, dim=1)
|
| 158 |
+
y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
|
| 159 |
+
return y.transpose(1, 2).contiguous()
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
# ---------------------------------------------------------------------------
|
| 163 |
+
# MLP / attention / block (config-name changes only)
|
| 164 |
+
# ---------------------------------------------------------------------------
|
| 165 |
+
|
| 166 |
+
class MLP(nn.Module):
|
| 167 |
+
def __init__(self, config):
|
| 168 |
+
super().__init__()
|
| 169 |
+
self.c_fc = nn.Linear(config.hidden_size, 4 * config.hidden_size, bias=False)
|
| 170 |
+
self.c_proj = nn.Linear(2 * config.hidden_size, config.hidden_size, bias=False)
|
| 171 |
+
|
| 172 |
+
def forward(self, x):
|
| 173 |
+
gate, val = self.c_fc(x).chunk(2, dim=-1)
|
| 174 |
+
return self.c_proj(gate * F.silu(val))
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class HybridAttention(nn.Module):
|
| 178 |
+
def __init__(self, config, layer_idx, is_linear):
|
| 179 |
+
super().__init__()
|
| 180 |
+
self.is_linear = is_linear
|
| 181 |
+
self.n_head = config.num_attention_heads
|
| 182 |
+
self.n_kv_head = config.num_key_value_heads
|
| 183 |
+
self.head_dim = config.hidden_size // config.num_attention_heads
|
| 184 |
+
self.c_q = nn.Linear(config.hidden_size, self.n_head * self.head_dim, bias=False)
|
| 185 |
+
self.c_k = nn.Linear(config.hidden_size, self.n_kv_head * self.head_dim, bias=False)
|
| 186 |
+
self.c_v = nn.Linear(config.hidden_size, self.n_kv_head * self.head_dim, bias=False)
|
| 187 |
+
self.c_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
|
| 188 |
+
self.ve_gate_channels = 32
|
| 189 |
+
self.ve_gate = (nn.Linear(self.ve_gate_channels, self.n_kv_head, bias=False)
|
| 190 |
+
if has_ve(layer_idx, config.num_hidden_layers) else None)
|
| 191 |
+
|
| 192 |
+
def forward(self, x, ve, cos_sin, gammas, chunk):
|
| 193 |
+
B, T, C = x.size()
|
| 194 |
+
q = self.c_q(x).view(B, T, self.n_head, self.head_dim)
|
| 195 |
+
k = self.c_k(x).view(B, T, self.n_kv_head, self.head_dim)
|
| 196 |
+
v = self.c_v(x).view(B, T, self.n_kv_head, self.head_dim)
|
| 197 |
+
if ve is not None:
|
| 198 |
+
ve = ve.view(B, T, self.n_kv_head, self.head_dim)
|
| 199 |
+
gate = 2 * torch.sigmoid(self.ve_gate(x[..., :self.ve_gate_channels]))
|
| 200 |
+
v = v + gate.unsqueeze(-1) * ve
|
| 201 |
+
cos, sin = cos_sin
|
| 202 |
+
q, k = apply_rotary_emb(q, cos, sin), apply_rotary_emb(k, cos, sin)
|
| 203 |
+
q, k = norm(q), norm(k)
|
| 204 |
+
y = linear_attn(q, k, v, gammas, chunk) if self.is_linear else sdpa_attn(q, k, v)
|
| 205 |
+
return self.c_proj(y.view(B, T, -1))
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
class HybridBlock(nn.Module):
|
| 209 |
+
def __init__(self, config, layer_idx, is_linear):
|
| 210 |
+
super().__init__()
|
| 211 |
+
self.attn = HybridAttention(config, layer_idx, is_linear)
|
| 212 |
+
self.mlp = MLP(config)
|
| 213 |
+
|
| 214 |
+
def forward(self, x, ve, cos_sin, gammas, chunk):
|
| 215 |
+
x = x + self.attn(norm(x), ve, cos_sin, gammas, chunk)
|
| 216 |
+
return x + self.mlp(norm(x))
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def _linear_pattern(n_layer, dense_every):
|
| 220 |
+
"""is_linear[i]: True for linear layers. 1 dense per `dense_every`; last dense."""
|
| 221 |
+
is_linear = [(i % dense_every) != (dense_every - 1) for i in range(n_layer)]
|
| 222 |
+
is_linear[-1] = False
|
| 223 |
+
return is_linear
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
# ---------------------------------------------------------------------------
|
| 227 |
+
# HF wrapper
|
| 228 |
+
# ---------------------------------------------------------------------------
|
| 229 |
+
|
| 230 |
+
class AmadablamForCausalLM(PreTrainedModel, GenerationMixin):
|
| 231 |
+
config_class = AmadablamConfig
|
| 232 |
+
_no_split_modules = ["HybridBlock"]
|
| 233 |
+
|
| 234 |
+
def __init__(self, config):
|
| 235 |
+
super().__init__(config)
|
| 236 |
+
n_layer = config.num_hidden_layers
|
| 237 |
+
n_embd = config.hidden_size
|
| 238 |
+
self.is_linear = _linear_pattern(n_layer, config.dense_every)
|
| 239 |
+
self.linear_chunk = config.linear_chunk
|
| 240 |
+
self.softcap = config.logit_softcap
|
| 241 |
+
self.transformer = nn.ModuleDict({
|
| 242 |
+
"wte": nn.Embedding(config.vocab_size, n_embd),
|
| 243 |
+
"h": nn.ModuleList([HybridBlock(config, i, self.is_linear[i])
|
| 244 |
+
for i in range(n_layer)]),
|
| 245 |
+
})
|
| 246 |
+
self.lm_head = nn.Linear(n_embd, config.vocab_size, bias=False)
|
| 247 |
+
self.resid_lambdas = nn.Parameter(torch.ones(n_layer))
|
| 248 |
+
self.x0_lambdas = nn.Parameter(torch.zeros(n_layer))
|
| 249 |
+
self.head_dim = n_embd // config.num_attention_heads
|
| 250 |
+
kv_dim = config.num_key_value_heads * self.head_dim
|
| 251 |
+
self.value_embeds = nn.ModuleDict({
|
| 252 |
+
str(i): nn.Embedding(config.vocab_size, kv_dim)
|
| 253 |
+
for i in range(n_layer) if has_ve(i, n_layer)
|
| 254 |
+
})
|
| 255 |
+
self.rotary_seq_len = config.max_position_embeddings * 10
|
| 256 |
+
# NOTE: gammas / cos / sin are DERIVED (config-driven, not checkpoint weights)
|
| 257 |
+
# and are recomputed lazily at forward time on the input's device — see
|
| 258 |
+
# `_get_gammas` / `_get_rope`. They are deliberately NOT registered as buffers:
|
| 259 |
+
# non-persistent buffers get materialised to all-zeros by `from_pretrained`'s
|
| 260 |
+
# meta-device init (they aren't in safetensors), which zeroed the decay/RoPE
|
| 261 |
+
# tables and produced NaN/garbage logits; persistent buffers would instead add
|
| 262 |
+
# keys absent from the research state_dict and break the strict key-parity copy.
|
| 263 |
+
# Plain (non-buffer, non-parameter) caches keyed by device sidestep both.
|
| 264 |
+
self._gamma_cache = {} # device -> gammas [H] float32
|
| 265 |
+
self._rope_cache = {} # device -> (cos, sin) bf16, length rotary_seq_len
|
| 266 |
+
self.post_init()
|
| 267 |
+
|
| 268 |
+
def _get_gammas(self, device):
|
| 269 |
+
"""Per-head linear-attention decay tensor [H] (float32), recomputed on
|
| 270 |
+
`device` and cached. Config-derived (`config.linear_decay`); survives
|
| 271 |
+
`from_pretrained` because it is not a load-materialised buffer."""
|
| 272 |
+
g = self._gamma_cache.get(device)
|
| 273 |
+
if g is None:
|
| 274 |
+
g = _head_gammas(self.config.num_attention_heads, device,
|
| 275 |
+
self.config.linear_decay)
|
| 276 |
+
self._gamma_cache[device] = g
|
| 277 |
+
return g
|
| 278 |
+
|
| 279 |
+
def _get_rope(self, T, device):
|
| 280 |
+
"""RoPE (cos, sin) tables sliced to length `T`, recomputed on `device` and
|
| 281 |
+
cached at the full precomputed length. Config-derived; survives reload."""
|
| 282 |
+
cs = self._rope_cache.get(device)
|
| 283 |
+
if cs is None:
|
| 284 |
+
cs = self._precompute_rotary_embeddings(
|
| 285 |
+
self.rotary_seq_len, self.head_dim,
|
| 286 |
+
base=self.config.rope_theta, device=device)
|
| 287 |
+
self._rope_cache[device] = cs
|
| 288 |
+
cos, sin = cs
|
| 289 |
+
return cos[:, :T], sin[:, :T]
|
| 290 |
+
|
| 291 |
+
def _precompute_rotary_embeddings(self, seq_len, head_dim, base=10000, device=None):
|
| 292 |
+
if device is None:
|
| 293 |
+
device = self.transformer.wte.weight.device
|
| 294 |
+
channel_range = torch.arange(0, head_dim, 2, dtype=torch.float32, device=device)
|
| 295 |
+
inv_freq = 1.0 / (base ** (channel_range / head_dim))
|
| 296 |
+
t = torch.arange(seq_len, dtype=torch.float32, device=device)
|
| 297 |
+
freqs = torch.outer(t, inv_freq)
|
| 298 |
+
cos, sin = freqs.cos().bfloat16(), freqs.sin().bfloat16()
|
| 299 |
+
return cos[None, :, None, :], sin[None, :, None, :]
|
| 300 |
+
|
| 301 |
+
def forward(self, input_ids, attention_mask=None, labels=None,
|
| 302 |
+
past_key_values=None, use_cache=None, **kwargs):
|
| 303 |
+
idx = input_ids
|
| 304 |
+
B, T = idx.size()
|
| 305 |
+
assert T <= self.rotary_seq_len
|
| 306 |
+
cos_sin = self._get_rope(T, idx.device)
|
| 307 |
+
gammas_all = self._get_gammas(idx.device)
|
| 308 |
+
x = norm(self.transformer.wte(idx))
|
| 309 |
+
x0 = x
|
| 310 |
+
for i, block in enumerate(self.transformer.h):
|
| 311 |
+
x = self.resid_lambdas[i] * x + self.x0_lambdas[i] * x0
|
| 312 |
+
ve = self.value_embeds[str(i)](idx) if str(i) in self.value_embeds else None
|
| 313 |
+
gammas = gammas_all if self.is_linear[i] else None
|
| 314 |
+
x = block(x, ve, cos_sin, gammas, self.linear_chunk)
|
| 315 |
+
x = norm(x)
|
| 316 |
+
logits = self.lm_head(x).float()
|
| 317 |
+
softcap = self.softcap
|
| 318 |
+
logits = softcap * torch.tanh(logits / softcap)
|
| 319 |
+
loss = None
|
| 320 |
+
if labels is not None:
|
| 321 |
+
V = logits.size(-1)
|
| 322 |
+
loss = F.cross_entropy(logits[:, :-1].reshape(-1, V),
|
| 323 |
+
labels[:, 1:].reshape(-1), ignore_index=-100)
|
| 324 |
+
return CausalLMOutput(loss=loss, logits=logits)
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"bos_token": "<|reserved_0|>",
|
| 4 |
+
"eos_token": "<|reserved_0|>",
|
| 5 |
+
"model_max_length": 8192,
|
| 6 |
+
"pad_token": "<|reserved_0|>",
|
| 7 |
+
"tokenizer_class": "TokenizersBackend"
|
| 8 |
+
}
|