Upload checkpoint (step 2000)
Browse files- README.md +94 -0
- ckpt_last.pt +3 -0
- config.json +15 -0
- generate.py +132 -0
- model.py +271 -0
- optim.py +69 -0
- training_state.json +5 -0
README.md
CHANGED
|
@@ -1,3 +1,97 @@
|
|
| 1 |
---
|
| 2 |
license: apache-2.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
license: apache-2.0
|
| 3 |
+
library_name: pytorch
|
| 4 |
+
pipeline_tag: text-generation
|
| 5 |
+
tags:
|
| 6 |
+
- code
|
| 7 |
+
- reasoning
|
| 8 |
+
- gated-linear-attention
|
| 9 |
+
- hybrid-attention
|
| 10 |
+
- long-context
|
| 11 |
+
- from-scratch
|
| 12 |
+
language:
|
| 13 |
+
- en
|
| 14 |
---
|
| 15 |
+
|
| 16 |
+
# FLATest — Hybrid GLA + Attention code/reasoning LM
|
| 17 |
+
|
| 18 |
+
A **308M-parameter** decoder-only language model trained **from scratch** on a single
|
| 19 |
+
RTX PRO 6000 (Blackwell). It mixes **Gated Linear Attention (GLA)** layers with sparse
|
| 20 |
+
full-attention layers — a hybrid sequence mixer in the spirit of Jamba / MiniMax —
|
| 21 |
+
to get **O(N) long-context** behaviour while keeping the **exact associative recall**
|
| 22 |
+
that pure linear attention loses.
|
| 23 |
+
|
| 24 |
+
This is an **educational / research** model: trained on a single GPU for a limited
|
| 25 |
+
token budget. It is **not** a SOTA code assistant. Its purpose is to demonstrate a
|
| 26 |
+
correct, scalable architecture for long-context + reasoning, and the GrokAdamW
|
| 27 |
+
optimizer recipe.
|
| 28 |
+
|
| 29 |
+
## Architecture
|
| 30 |
+
|
| 31 |
+
| | |
|
| 32 |
+
|---|---|
|
| 33 |
+
| Params | ~308M |
|
| 34 |
+
| `d_model` | 1024 |
|
| 35 |
+
| Layers | 24 |
|
| 36 |
+
| Heads | 16 (GQA, 4 KV-heads) |
|
| 37 |
+
| Mixer | **hybrid** — GLA on most layers, attention every 4th layer (`gggAgggAgggAgggAgggAgggA`) |
|
| 38 |
+
| Train context | 4096 |
|
| 39 |
+
| Vocab | 49152 (StarCoder2 BPE) |
|
| 40 |
+
| Position | RoPE on attention layers; GLA uses learned decay (no RoPE) |
|
| 41 |
+
| Norm / MLP | RMSNorm + SwiGLU |
|
| 42 |
+
| Embeddings | tied input/output |
|
| 43 |
+
|
| 44 |
+
**Why hybrid:** pure GLA fails exact associative recall (recall ≈ chance on an
|
| 45 |
+
induction probe), while a few interleaved attention layers restore it (recall ≈ 1.0).
|
| 46 |
+
The GLA layers keep the model linear in context length, so the real payoff is
|
| 47 |
+
**long-form generation**: in our decode benchmark GLA's recurrent state is **~8.7×
|
| 48 |
+
faster and ~20× lighter** than an attention KV-cache at 64k output tokens.
|
| 49 |
+
|
| 50 |
+
## Training
|
| 51 |
+
|
| 52 |
+
- **Optimizer:** GrokAdamW — decoupled weight decay (0.1), betas (0.9, 0.95),
|
| 53 |
+
cautious update, optional Grokfast EMA. The weight-decay-driven recipe was verified
|
| 54 |
+
to reproduce **grokking** on modular addition (val acc 0 → 1.0).
|
| 55 |
+
- **Data:** infinite mixed stream — code documents (`bigcode/starcoderdata`) +
|
| 56 |
+
reasoning traces (`open-r1/OpenR1-Math-220k`, ratio 0.3). Reasoning examples are
|
| 57 |
+
**prompt-masked** (loss only on `<think>…</think>` + answer).
|
| 58 |
+
- **Schedule:** warmup + cosine, bf16 autocast, grad clip 1.0, effective batch 64
|
| 59 |
+
(262k tokens/step), `torch.compile`.
|
| 60 |
+
- **Throughput:** ~81k tok/s, ~58 GB peak on the PRO 6000.
|
| 61 |
+
- **Reasoning format:** special tokens `<think>` / `</think>`; the model learns to
|
| 62 |
+
reason in text before answering.
|
| 63 |
+
|
| 64 |
+
Validation perplexity dropped steadily (ppl 33 → ~4 within a few thousand steps).
|
| 65 |
+
See `config.json` and `training_state.json` for the exact step the uploaded
|
| 66 |
+
checkpoint corresponds to.
|
| 67 |
+
|
| 68 |
+
## Files
|
| 69 |
+
|
| 70 |
+
- `ckpt_last.pt` — checkpoint: `{model, opt, step, cfg}` (PyTorch).
|
| 71 |
+
- `config.json` — the `ModelConfig` used to build the model.
|
| 72 |
+
- `model.py`, `optim.py` — model + optimizer definitions (the `codetrain` package).
|
| 73 |
+
- `generate.py` — inference / sampling script.
|
| 74 |
+
|
| 75 |
+
## Inference
|
| 76 |
+
|
| 77 |
+
```bash
|
| 78 |
+
pip install torch transformers flash-linear-attention
|
| 79 |
+
python generate.py --ckpt ckpt_last.pt --prompt "Write a Python function that reverses a linked list."
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
`generate.py` seeds a `<think>` block to elicit reasoning, then samples the answer.
|
| 83 |
+
Requires `flash-linear-attention` (Triton) for the GLA layers.
|
| 84 |
+
|
| 85 |
+
## Limitations
|
| 86 |
+
|
| 87 |
+
- Single-GPU, limited token budget → expect incoherent or repetitive output on hard
|
| 88 |
+
prompts. It is a scaffold, not a product.
|
| 89 |
+
- GLA layers require `flash-linear-attention` + a Triton-capable GPU.
|
| 90 |
+
- `generate.py` uses full-recompute decoding (simple, correct for both layer types);
|
| 91 |
+
the O(1) recurrent GLA decode that gives the long-context speedup is not yet wired
|
| 92 |
+
into the sampler.
|
| 93 |
+
|
| 94 |
+
## Citation / lineage
|
| 95 |
+
|
| 96 |
+
Builds on: Gated Linear Attention (Yang et al. 2023), Grokfast (Lee et al. 2024),
|
| 97 |
+
grokking (Power et al. 2022), hybrid linear/attention stacks (Jamba, MiniMax).
|
ckpt_last.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c97c327a41304598853f89ac14bd57b51900d09a02d01ca27f610fbccadb56fc
|
| 3 |
+
size 2152241611
|
config.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"vocab_size": 49154,
|
| 3 |
+
"d_model": 1024,
|
| 4 |
+
"n_layers": 24,
|
| 5 |
+
"n_heads": 16,
|
| 6 |
+
"n_kv_heads": 4,
|
| 7 |
+
"block_size": 4096,
|
| 8 |
+
"mlp_ratio": 2.6666666666666665,
|
| 9 |
+
"rope_theta": 100000.0,
|
| 10 |
+
"dropout": 0.0,
|
| 11 |
+
"grad_checkpoint": false,
|
| 12 |
+
"mixer": "hybrid",
|
| 13 |
+
"attn_every": 4,
|
| 14 |
+
"gla_chunk": 64
|
| 15 |
+
}
|
generate.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""generate.py — запуск обученной reasoning-модели по чекпойнту.
|
| 2 |
+
|
| 3 |
+
Даёшь задачу по коду/математике -> модель рассуждает в <think>...</think> и
|
| 4 |
+
выдаёт ответ. Декодинг: полный пересчёт растущей последовательности (просто и
|
| 5 |
+
корректно для hybrid: и GLA-, и attn-слои работают через обычный forward).
|
| 6 |
+
|
| 7 |
+
Запуск:
|
| 8 |
+
python generate.py --ckpt out_reason/ckpt_last.pt --prompt "Напиши функцию..."
|
| 9 |
+
python generate.py --ckpt out_reason/ckpt_last.pt # интерактивно
|
| 10 |
+
python generate.py --ckpt out_reason/ckpt_last.pt --no_think # без затравки <think>
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import argparse, os
|
| 14 |
+
import torch
|
| 15 |
+
import torch.nn.functional as F
|
| 16 |
+
|
| 17 |
+
from codetrain.model import CodeLM, ModelConfig
|
| 18 |
+
|
| 19 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 20 |
+
THINK, ENDTHINK = "<think>", "</think>"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def load_model(ckpt_path):
|
| 24 |
+
ck = torch.load(ckpt_path, map_location=DEVICE)
|
| 25 |
+
cfg = ModelConfig(**ck["cfg"])
|
| 26 |
+
cfg.grad_checkpoint = False # инференс: без чекпойнтинга
|
| 27 |
+
model = CodeLM(cfg).to(DEVICE).to(torch.bfloat16)
|
| 28 |
+
model.load_state_dict(ck["model"])
|
| 29 |
+
model.eval()
|
| 30 |
+
step = ck.get("step", "?")
|
| 31 |
+
print(f"Загружен чекпойнт: шаг {step} | {model.num_params()/1e6:.0f}M "
|
| 32 |
+
f"| ctx {cfg.block_size} | mixer {cfg.mixer}")
|
| 33 |
+
return model, cfg
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def build_tokenizer(name="bigcode/starcoder2-15b"):
|
| 37 |
+
from transformers import AutoTokenizer
|
| 38 |
+
tok = AutoTokenizer.from_pretrained(name)
|
| 39 |
+
if tok.eos_token_id is None:
|
| 40 |
+
tok.add_special_tokens({"eos_token": "<|endoftext|>"})
|
| 41 |
+
add = [t for t in (THINK, ENDTHINK) if t not in tok.get_vocab()]
|
| 42 |
+
if add:
|
| 43 |
+
tok.add_special_tokens({"additional_special_tokens": add})
|
| 44 |
+
return tok
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _sample(logits, temperature, top_p):
|
| 48 |
+
"""Один токен из распределения. temperature=0 -> жадно (argmax)."""
|
| 49 |
+
if temperature <= 0:
|
| 50 |
+
return int(logits.argmax(-1))
|
| 51 |
+
logits = logits / temperature
|
| 52 |
+
probs = F.softmax(logits, dim=-1)
|
| 53 |
+
if 0 < top_p < 1: # nucleus: оставляем ядро массы top_p
|
| 54 |
+
sp, si = torch.sort(probs, descending=True)
|
| 55 |
+
csum = torch.cumsum(sp, dim=-1)
|
| 56 |
+
keep = csum - sp <= top_p # держим, пока кумулятив не превысил
|
| 57 |
+
sp = sp * keep
|
| 58 |
+
sp = sp / sp.sum()
|
| 59 |
+
nxt = si[torch.multinomial(sp, 1)]
|
| 60 |
+
return int(nxt)
|
| 61 |
+
return int(torch.multinomial(probs, 1))
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@torch.no_grad()
|
| 65 |
+
def generate(model, cfg, tok, prompt, max_new=512, temperature=0.7, top_p=0.95,
|
| 66 |
+
seed_think=True, stream=True):
|
| 67 |
+
"""Сгенерировать продолжение. seed_think=True добавляет '<think>\\n' к затравке,
|
| 68 |
+
подталкивая модель сначала рассуждать. Останов по EOS. Печатает по токенам."""
|
| 69 |
+
text = prompt.rstrip() + "\n"
|
| 70 |
+
if seed_think:
|
| 71 |
+
text += THINK + "\n"
|
| 72 |
+
ids = tok.encode(text)
|
| 73 |
+
if stream:
|
| 74 |
+
print("\n--- генерация ---")
|
| 75 |
+
print(text, end="", flush=True)
|
| 76 |
+
ids = torch.tensor([ids], device=DEVICE)
|
| 77 |
+
eos = tok.eos_token_id
|
| 78 |
+
out_ids = []
|
| 79 |
+
for _ in range(max_new):
|
| 80 |
+
ctx = ids[:, -cfg.block_size:] # не выходим за обученный контекст
|
| 81 |
+
logits, _ = model(ctx) # (1, 1, vocab) — последний шаг
|
| 82 |
+
nxt = _sample(logits[0, -1], temperature, top_p)
|
| 83 |
+
if nxt == eos:
|
| 84 |
+
break
|
| 85 |
+
out_ids.append(nxt)
|
| 86 |
+
ids = torch.cat([ids, torch.tensor([[nxt]], device=DEVICE)], dim=1)
|
| 87 |
+
if stream:
|
| 88 |
+
print(tok.decode([nxt]), end="", flush=True)
|
| 89 |
+
if stream:
|
| 90 |
+
print("\n--- конец ---")
|
| 91 |
+
return tok.decode(out_ids)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def main():
|
| 95 |
+
ap = argparse.ArgumentParser()
|
| 96 |
+
ap.add_argument("--ckpt", required=True)
|
| 97 |
+
ap.add_argument("--tokenizer", default="bigcode/starcoder2-15b")
|
| 98 |
+
ap.add_argument("--prompt", default=None, help="одноразовый запрос (иначе интерактив)")
|
| 99 |
+
ap.add_argument("--max_new", type=int, default=512)
|
| 100 |
+
ap.add_argument("--temperature", type=float, default=0.7)
|
| 101 |
+
ap.add_argument("--top_p", type=float, default=0.95)
|
| 102 |
+
ap.add_argument("--no_think", action="store_true",
|
| 103 |
+
help="не добавлять <think> в затравку (модель сама решит)")
|
| 104 |
+
args = ap.parse_args()
|
| 105 |
+
|
| 106 |
+
if not os.path.exists(args.ckpt):
|
| 107 |
+
print(f"Чекпойнт не найден: {args.ckpt}"); return
|
| 108 |
+
tok = build_tokenizer(args.tokenizer)
|
| 109 |
+
model, cfg = load_model(args.ckpt)
|
| 110 |
+
|
| 111 |
+
def run(p):
|
| 112 |
+
generate(model, cfg, tok, p, max_new=args.max_new,
|
| 113 |
+
temperature=args.temperature, top_p=args.top_p,
|
| 114 |
+
seed_think=not args.no_think, stream=True)
|
| 115 |
+
|
| 116 |
+
if args.prompt is not None:
|
| 117 |
+
run(args.prompt)
|
| 118 |
+
else:
|
| 119 |
+
print("Интерактив. Пустая строка / Ctrl-C — выход.")
|
| 120 |
+
while True:
|
| 121 |
+
try:
|
| 122 |
+
p = input("\n>>> запрос: ").strip()
|
| 123 |
+
except (EOFError, KeyboardInterrupt):
|
| 124 |
+
print(); break
|
| 125 |
+
if not p:
|
| 126 |
+
break
|
| 127 |
+
run(p)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
if __name__ == "__main__":
|
| 131 |
+
main()
|
| 132 |
+
|
model.py
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Современный decoder-only трансформер для обучения кодинг-модели с нуля.
|
| 2 |
+
|
| 3 |
+
Компоненты (всё — проверенная практика для код-моделей):
|
| 4 |
+
- RoPE (rotary position embeddings): позволяет расширять контекст за пределы
|
| 5 |
+
обученной длины; нет обучаемых позиционных эмбеддингов.
|
| 6 |
+
- RMSNorm: дешевле и стабильнее LayerNorm.
|
| 7 |
+
- SwiGLU MLP: лучше GELU при том же бюджете параметров.
|
| 8 |
+
- Flash attention через F.scaled_dot_product_attention: память O(N) на практике,
|
| 9 |
+
causal-маска бесплатно.
|
| 10 |
+
- Gradient checkpointing (опц.): торгуем счёт за память -> длинный контекст
|
| 11 |
+
на одной карте.
|
| 12 |
+
- Tied embeddings (вход = выход): экономит параметры, обычно не вредит.
|
| 13 |
+
|
| 14 |
+
Конфиг масштабируется от ~120M до ~1B; дефолт ~0.35B комфортно влезает в 96GB
|
| 15 |
+
с длинным контекстом и grad checkpointing.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
import math
|
| 20 |
+
import torch
|
| 21 |
+
import torch.nn as nn
|
| 22 |
+
import torch.nn.functional as F
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@dataclass
|
| 26 |
+
class ModelConfig:
|
| 27 |
+
vocab_size: int = 49152 # StarCoder2 BPE
|
| 28 |
+
d_model: int = 1024
|
| 29 |
+
n_layers: int = 24
|
| 30 |
+
n_heads: int = 16
|
| 31 |
+
n_kv_heads: int = 4 # GQA: меньше KV-голов -> дешевле память/кэш
|
| 32 |
+
block_size: int = 4096 # тренируемый контекст
|
| 33 |
+
mlp_ratio: float = 8 / 3 # SwiGLU -> hidden ~ 8/3 * d_model, кратно 256
|
| 34 |
+
rope_theta: float = 100_000.0 # большая база -> легче расширять контекст
|
| 35 |
+
dropout: float = 0.0
|
| 36 |
+
grad_checkpoint: bool = True
|
| 37 |
+
# выбор смесителя последовательности:
|
| 38 |
+
# "attn" — обычное внимание во всех слоях (O(N^2), точный recall);
|
| 39 |
+
# "gla" — линейное внимание fla во всех слоях (O(N), но без точного recall);
|
| 40 |
+
# "hybrid" — GLA везде + attention каждый attn_every-й слой (O(N) + recall).
|
| 41 |
+
mixer: str = "attn"
|
| 42 |
+
attn_every: int = 4 # для hybrid: каждый attn_every-й слой = attention
|
| 43 |
+
gla_chunk: int = 64 # размер чанка для fla chunk_gla
|
| 44 |
+
|
| 45 |
+
@property
|
| 46 |
+
def head_dim(self):
|
| 47 |
+
return self.d_model // self.n_heads
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class RMSNorm(nn.Module):
|
| 51 |
+
def __init__(self, dim, eps=1e-5):
|
| 52 |
+
super().__init__()
|
| 53 |
+
self.eps = eps
|
| 54 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 55 |
+
|
| 56 |
+
def forward(self, x):
|
| 57 |
+
dt = x.dtype
|
| 58 |
+
x = x.float()
|
| 59 |
+
x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 60 |
+
return (x * self.weight.float()).to(dt)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def build_rope_cache(seq_len, head_dim, theta, device, dtype):
|
| 64 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim))
|
| 65 |
+
t = torch.arange(seq_len, device=device).float()
|
| 66 |
+
freqs = torch.outer(t, inv_freq) # (T, head_dim/2)
|
| 67 |
+
cos = freqs.cos().to(dtype)
|
| 68 |
+
sin = freqs.sin().to(dtype)
|
| 69 |
+
return cos, sin
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def apply_rope(x, cos, sin):
|
| 73 |
+
# x: (B, H, T, D). Поворачиваем пары (x1, x2).
|
| 74 |
+
T = x.shape[-2]
|
| 75 |
+
cos, sin = cos[:T], sin[:T]
|
| 76 |
+
x1, x2 = x[..., 0::2], x[..., 1::2]
|
| 77 |
+
cos = cos[None, None]; sin = sin[None, None]
|
| 78 |
+
rx1 = x1 * cos - x2 * sin
|
| 79 |
+
rx2 = x1 * sin + x2 * cos
|
| 80 |
+
out = torch.empty_like(x)
|
| 81 |
+
out[..., 0::2] = rx1
|
| 82 |
+
out[..., 1::2] = rx2
|
| 83 |
+
return out
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class Attention(nn.Module):
|
| 87 |
+
"""Causal multi-head attention с GQA и RoPE, flash через SDPA."""
|
| 88 |
+
|
| 89 |
+
def __init__(self, cfg: ModelConfig):
|
| 90 |
+
super().__init__()
|
| 91 |
+
self.n_heads = cfg.n_heads
|
| 92 |
+
self.n_kv = cfg.n_kv_heads
|
| 93 |
+
self.hd = cfg.head_dim
|
| 94 |
+
assert cfg.n_heads % cfg.n_kv_heads == 0, "n_heads должно делиться на n_kv_heads"
|
| 95 |
+
self.q_proj = nn.Linear(cfg.d_model, cfg.n_heads * self.hd, bias=False)
|
| 96 |
+
self.k_proj = nn.Linear(cfg.d_model, self.n_kv * self.hd, bias=False)
|
| 97 |
+
self.v_proj = nn.Linear(cfg.d_model, self.n_kv * self.hd, bias=False)
|
| 98 |
+
self.o_proj = nn.Linear(cfg.n_heads * self.hd, cfg.d_model, bias=False)
|
| 99 |
+
self.dropout = cfg.dropout
|
| 100 |
+
|
| 101 |
+
def forward(self, x, cos, sin):
|
| 102 |
+
B, T, _ = x.shape
|
| 103 |
+
q = self.q_proj(x).view(B, T, self.n_heads, self.hd).transpose(1, 2)
|
| 104 |
+
k = self.k_proj(x).view(B, T, self.n_kv, self.hd).transpose(1, 2)
|
| 105 |
+
v = self.v_proj(x).view(B, T, self.n_kv, self.hd).transpose(1, 2)
|
| 106 |
+
q = apply_rope(q, cos, sin)
|
| 107 |
+
k = apply_rope(k, cos, sin)
|
| 108 |
+
if self.n_kv != self.n_heads: # GQA: расширяем KV-головы
|
| 109 |
+
rep = self.n_heads // self.n_kv
|
| 110 |
+
k = k.repeat_interleave(rep, dim=1)
|
| 111 |
+
v = v.repeat_interleave(rep, dim=1)
|
| 112 |
+
y = F.scaled_dot_product_attention(
|
| 113 |
+
q, k, v, is_causal=True,
|
| 114 |
+
dropout_p=self.dropout if self.training else 0.0)
|
| 115 |
+
y = y.transpose(1, 2).contiguous().view(B, T, -1)
|
| 116 |
+
return self.o_proj(y)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
# fla (flash-linear-attention): рабочее fused Triton-ядро GLA (fwd+bwd).
|
| 120 |
+
# Проверено на RTX PRO 6000: 4x быстрее flash-attn на 32k, обучается (recall грокнул).
|
| 121 |
+
# Импорт защищён: если fla нет (нет triton/Blackwell), GLAMixer недоступен и train
|
| 122 |
+
# должен откатиться на attention (см. _make_mixer).
|
| 123 |
+
try:
|
| 124 |
+
from fla.ops.gla import chunk_gla as _fla_chunk_gla
|
| 125 |
+
_HAS_FLA = True
|
| 126 |
+
except Exception:
|
| 127 |
+
_fla_chunk_gla = None
|
| 128 |
+
_HAS_FLA = False
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class GLAMixer(nn.Module):
|
| 132 |
+
"""Gated Linear Attention через fla. O(N) по контексту, без RoPE
|
| 133 |
+
(затухание само кодирует позицию). Обучаемый ВЕКТОРНЫЙ гейт затухания
|
| 134 |
+
g = logsigmoid(W_g x) — каноническая форма GLA (мощнее скалярного gamma).
|
| 135 |
+
Раскладка для fla 0.5.0: (B, T, H, K), без kwargs (откалибровано отдельно).
|
| 136 |
+
GQA: KV-головы расширяются до n_heads (fla ждёт одинаковое число голов)."""
|
| 137 |
+
|
| 138 |
+
def __init__(self, cfg: ModelConfig):
|
| 139 |
+
super().__init__()
|
| 140 |
+
assert _HAS_FLA, "GLAMixer требует flash-linear-attention (pip install)"
|
| 141 |
+
self.n_heads = cfg.n_heads
|
| 142 |
+
self.n_kv = cfg.n_kv_heads
|
| 143 |
+
self.hd = cfg.head_dim
|
| 144 |
+
self.chunk = cfg.gla_chunk
|
| 145 |
+
self.q_proj = nn.Linear(cfg.d_model, cfg.n_heads * self.hd, bias=False)
|
| 146 |
+
self.k_proj = nn.Linear(cfg.d_model, self.n_kv * self.hd, bias=False)
|
| 147 |
+
self.v_proj = nn.Linear(cfg.d_model, self.n_kv * self.hd, bias=False)
|
| 148 |
+
# гейт затухания на каждый канал q-голов (в лог-пространстве через logsigmoid)
|
| 149 |
+
self.g_proj = nn.Linear(cfg.d_model, cfg.n_heads * self.hd, bias=False)
|
| 150 |
+
self.o_proj = nn.Linear(cfg.n_heads * self.hd, cfg.d_model, bias=False)
|
| 151 |
+
# выходной гейт (как в GLA): сигмоида, стабилизирует амплитуду
|
| 152 |
+
self.out_gate = nn.Linear(cfg.d_model, cfg.n_heads * self.hd, bias=False)
|
| 153 |
+
|
| 154 |
+
def forward(self, x, cos=None, sin=None): # cos/sin игнорируем: GLA без RoPE
|
| 155 |
+
B, T, _ = x.shape
|
| 156 |
+
H, KV, Dh = self.n_heads, self.n_kv, self.hd
|
| 157 |
+
# fla ждёт раскладку (B, T, H, Dh)
|
| 158 |
+
q = self.q_proj(x).view(B, T, H, Dh)
|
| 159 |
+
k = self.k_proj(x).view(B, T, KV, Dh)
|
| 160 |
+
v = self.v_proj(x).view(B, T, KV, Dh)
|
| 161 |
+
if KV != H: # GQA -> расширяем KV до H голов
|
| 162 |
+
rep = H // KV
|
| 163 |
+
k = k.repeat_interleave(rep, dim=2)
|
| 164 |
+
v = v.repeat_interleave(rep, dim=2)
|
| 165 |
+
q = F.normalize(q, dim=-1)
|
| 166 |
+
k = F.normalize(k, dim=-1)
|
| 167 |
+
# лог-гейт затухания в (-inf, 0): logsigmoid -> устойчиво, gamma=exp(g) in (0,1)
|
| 168 |
+
g = F.logsigmoid(self.g_proj(x).view(B, T, H, Dh).float())
|
| 169 |
+
# ЕДИНЫЙ dtype для fla: под autocast F.normalize даёт fp32, а v_proj — bf16;
|
| 170 |
+
# fla-ядро падает на смешении типов в tl.dot. Приводим всё к dtype входа.
|
| 171 |
+
dt = x.dtype
|
| 172 |
+
q, k, v, g = q.to(dt), k.to(dt), v.to(dt), g.to(dt)
|
| 173 |
+
out = _fla_chunk_gla(q, k, v, g) # (B, T, H, Dh), layout bthd
|
| 174 |
+
o = out[0] if isinstance(out, (tuple, list)) else out
|
| 175 |
+
o = o.reshape(B, T, H * Dh) * torch.sigmoid(self.out_gate(x))
|
| 176 |
+
return self.o_proj(o)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class SwiGLU(nn.Module):
|
| 180 |
+
def __init__(self, cfg: ModelConfig):
|
| 181 |
+
super().__init__()
|
| 182 |
+
hidden = int(cfg.mlp_ratio * cfg.d_model)
|
| 183 |
+
hidden = 256 * ((hidden + 255) // 256) # кратно 256 для тензорных ядер
|
| 184 |
+
self.gate = nn.Linear(cfg.d_model, hidden, bias=False)
|
| 185 |
+
self.up = nn.Linear(cfg.d_model, hidden, bias=False)
|
| 186 |
+
self.down = nn.Linear(hidden, cfg.d_model, bias=False)
|
| 187 |
+
|
| 188 |
+
def forward(self, x):
|
| 189 |
+
return self.down(F.silu(self.gate(x)) * self.up(x))
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _layer_is_attn(cfg: ModelConfig, layer_idx: int) -> bool:
|
| 193 |
+
"""Какой смеситель в слое layer_idx. hybrid: attention каждый attn_every-й слой
|
| 194 |
+
(на индексах attn_every-1, 2*attn_every-1, ...), остальное — GLA."""
|
| 195 |
+
if cfg.mixer == "attn":
|
| 196 |
+
return True
|
| 197 |
+
if cfg.mixer == "gla":
|
| 198 |
+
return False
|
| 199 |
+
# hybrid
|
| 200 |
+
return (layer_idx + 1) % cfg.attn_every == 0
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class Block(nn.Module):
|
| 204 |
+
def __init__(self, cfg: ModelConfig, layer_idx: int = 0):
|
| 205 |
+
super().__init__()
|
| 206 |
+
self.is_attn = _layer_is_attn(cfg, layer_idx)
|
| 207 |
+
self.attn_norm = RMSNorm(cfg.d_model)
|
| 208 |
+
self.mixer = Attention(cfg) if self.is_attn else GLAMixer(cfg)
|
| 209 |
+
self.mlp_norm = RMSNorm(cfg.d_model)
|
| 210 |
+
self.mlp = SwiGLU(cfg)
|
| 211 |
+
|
| 212 |
+
def forward(self, x, cos, sin):
|
| 213 |
+
# GLA-слой игнорирует cos/sin (нет RoPE); attention использует.
|
| 214 |
+
x = x + self.mixer(self.attn_norm(x), cos, sin)
|
| 215 |
+
x = x + self.mlp(self.mlp_norm(x))
|
| 216 |
+
return x
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
class CodeLM(nn.Module):
|
| 220 |
+
def __init__(self, cfg: ModelConfig):
|
| 221 |
+
super().__init__()
|
| 222 |
+
self.cfg = cfg
|
| 223 |
+
self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.d_model)
|
| 224 |
+
self.drop = nn.Dropout(cfg.dropout)
|
| 225 |
+
self.blocks = nn.ModuleList([Block(cfg, i) for i in range(cfg.n_layers)])
|
| 226 |
+
self.norm_f = RMSNorm(cfg.d_model)
|
| 227 |
+
self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
|
| 228 |
+
self.lm_head.weight = self.tok_emb.weight # tied
|
| 229 |
+
self._rope = None
|
| 230 |
+
self.apply(self._init)
|
| 231 |
+
# масштабирование инициализации остаточных проекций по глубине (GPT-2 трюк)
|
| 232 |
+
for n, p in self.named_parameters():
|
| 233 |
+
if n.endswith("o_proj.weight") or n.endswith("down.weight"):
|
| 234 |
+
nn.init.normal_(p, std=0.02 / math.sqrt(2 * cfg.n_layers))
|
| 235 |
+
|
| 236 |
+
def _init(self, m):
|
| 237 |
+
if isinstance(m, nn.Linear):
|
| 238 |
+
nn.init.normal_(m.weight, std=0.02)
|
| 239 |
+
elif isinstance(m, nn.Embedding):
|
| 240 |
+
nn.init.normal_(m.weight, std=0.02)
|
| 241 |
+
|
| 242 |
+
def _rope_cache(self, T, device, dtype):
|
| 243 |
+
if self._rope is None or self._rope[0].shape[0] < T or self._rope[0].device != device:
|
| 244 |
+
self._rope = build_rope_cache(max(T, self.cfg.block_size),
|
| 245 |
+
self.cfg.head_dim, self.cfg.rope_theta,
|
| 246 |
+
device, dtype)
|
| 247 |
+
return self._rope
|
| 248 |
+
|
| 249 |
+
def forward(self, idx, targets=None):
|
| 250 |
+
B, T = idx.shape
|
| 251 |
+
x = self.drop(self.tok_emb(idx))
|
| 252 |
+
cos, sin = self._rope_cache(T, idx.device, x.dtype)
|
| 253 |
+
for blk in self.blocks:
|
| 254 |
+
if self.cfg.grad_checkpoint and self.training:
|
| 255 |
+
x = torch.utils.checkpoint.checkpoint(blk, x, cos, sin, use_reentrant=False)
|
| 256 |
+
else:
|
| 257 |
+
x = blk(x, cos, sin)
|
| 258 |
+
x = self.norm_f(x)
|
| 259 |
+
if targets is None: # инференс: только последний шаг
|
| 260 |
+
logits = self.lm_head(x[:, -1:])
|
| 261 |
+
return logits, None
|
| 262 |
+
logits = self.lm_head(x)
|
| 263 |
+
loss = F.cross_entropy(logits.reshape(-1, logits.size(-1)),
|
| 264 |
+
targets.reshape(-1), ignore_index=-100)
|
| 265 |
+
return logits, loss
|
| 266 |
+
|
| 267 |
+
def num_params(self, non_embed=True):
|
| 268 |
+
n = sum(p.numel() for p in self.parameters())
|
| 269 |
+
if non_embed:
|
| 270 |
+
n -= self.tok_emb.weight.numel() # tied -> один раз
|
| 271 |
+
return n
|
optim.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""GrokAdamW: AdamW c уклоном в обобщение.
|
| 2 |
+
|
| 3 |
+
- decoupled weight decay (только на матрицах, не на нормах/эмбеддингах);
|
| 4 |
+
- cautious-маскинг (C-AdamW): применяем компоненты шага, согласованные по
|
| 5 |
+
знаку с градиентом -> стабильнее и чуть быстрее сходимость;
|
| 6 |
+
- Grokfast (опц., gf_lambda>0): усиление медленной компоненты градиента.
|
| 7 |
+
Для большого претрейна обычно держим gf_lambda=0 (нужен для grokking на
|
| 8 |
+
маленьких алгоритмических задачах, не для масштабного обучения).
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import math
|
| 12 |
+
import torch
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class GrokAdamW(torch.optim.Optimizer):
|
| 16 |
+
def __init__(self, params, lr=3e-4, betas=(0.9, 0.95), eps=1e-8,
|
| 17 |
+
weight_decay=0.1, grokfast_lambda=0.0, grokfast_alpha=0.98,
|
| 18 |
+
cautious=True):
|
| 19 |
+
defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay,
|
| 20 |
+
grokfast_lambda=grokfast_lambda, grokfast_alpha=grokfast_alpha,
|
| 21 |
+
cautious=cautious)
|
| 22 |
+
super().__init__(params, defaults)
|
| 23 |
+
|
| 24 |
+
@torch.no_grad()
|
| 25 |
+
def step(self, closure=None):
|
| 26 |
+
loss = closure() if closure is not None else None
|
| 27 |
+
for grp in self.param_groups:
|
| 28 |
+
lr, (b1, b2), eps = grp["lr"], grp["betas"], grp["eps"]
|
| 29 |
+
wd, gfl, gfa, caut = (grp["weight_decay"], grp["grokfast_lambda"],
|
| 30 |
+
grp["grokfast_alpha"], grp["cautious"])
|
| 31 |
+
for p in grp["params"]:
|
| 32 |
+
if p.grad is None:
|
| 33 |
+
continue
|
| 34 |
+
g = p.grad
|
| 35 |
+
st = self.state[p]
|
| 36 |
+
if not st:
|
| 37 |
+
st["step"] = 0
|
| 38 |
+
st["m"] = torch.zeros_like(p)
|
| 39 |
+
st["v"] = torch.zeros_like(p)
|
| 40 |
+
if gfl > 0:
|
| 41 |
+
st["ema"] = g.clone()
|
| 42 |
+
if gfl > 0:
|
| 43 |
+
ema = st["ema"]; ema.mul_(gfa).add_(g, alpha=1 - gfa)
|
| 44 |
+
g = g.add(ema, alpha=gfl)
|
| 45 |
+
m, v = st["m"], st["v"]
|
| 46 |
+
st["step"] += 1; t = st["step"]
|
| 47 |
+
m.mul_(b1).add_(g, alpha=1 - b1)
|
| 48 |
+
v.mul_(b2).addcmul_(g, g, value=1 - b2)
|
| 49 |
+
denom = (v.sqrt() / math.sqrt(1 - b2 ** t)).add_(eps)
|
| 50 |
+
step_size = lr / (1 - b1 ** t)
|
| 51 |
+
if wd != 0:
|
| 52 |
+
p.mul_(1 - lr * wd)
|
| 53 |
+
upd = m / denom
|
| 54 |
+
if caut:
|
| 55 |
+
mask = (upd * g > 0).to(upd.dtype)
|
| 56 |
+
mask.mul_(mask.numel() / (mask.sum() + 1))
|
| 57 |
+
upd.mul_(mask)
|
| 58 |
+
p.add_(upd, alpha=-step_size)
|
| 59 |
+
return loss
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def param_groups(model, weight_decay):
|
| 63 |
+
decay, no_decay = [], []
|
| 64 |
+
for name, p in model.named_parameters():
|
| 65 |
+
if not p.requires_grad:
|
| 66 |
+
continue
|
| 67 |
+
(no_decay if p.ndim < 2 or name.endswith(".bias") else decay).append(p)
|
| 68 |
+
return [{"params": decay, "weight_decay": weight_decay},
|
| 69 |
+
{"params": no_decay, "weight_decay": 0.0}]
|
training_state.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"step": 2000,
|
| 3 |
+
"param_count": 408998912,
|
| 4 |
+
"checkpoint": "ckpt_last.pt"
|
| 5 |
+
}
|