MaxGPT-Mini: weights (safetensors), its model and tokenizer code, config, model card
Browse files- README.md +51 -0
- cfg.py +79 -0
- config.yaml +49 -0
- model.safetensors +3 -0
- model/__init__.py +5 -0
- model/config.py +58 -0
- model/generate.py +64 -0
- model/model.py +370 -0
- requirements.txt +4 -0
- run.py +18 -0
- tokenizer.json +0 -0
- tokenizer/__init__.py +0 -0
- tokenizer/tokenizer.py +96 -0
README.md
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
library_name: pytorch
|
| 6 |
+
tags:
|
| 7 |
+
- from-scratch
|
| 8 |
+
- small-language-model
|
| 9 |
+
- gpt
|
| 10 |
+
- pytorch
|
| 11 |
+
- safetensors
|
| 12 |
+
- dpo
|
| 13 |
+
pipeline_tag: text-generation
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
# MaxGPT-Mini (113M)
|
| 17 |
+
|
| 18 |
+
The first model of the Neo series: a modern decoder design at 113M parameters, pretrained from scratch, then chat-tuned with supervised fine-tuning and DPO. It was built to prove out the whole pipeline before the 1.09B MaxGPT-Ultra, and Max judged it better than the 235M MaxGPT-3 in side-by-side chats.
|
| 19 |
+
|
| 20 |
+
## What it is
|
| 21 |
+
|
| 22 |
+
- 113M parameters: 12 blocks, width 768, 12 query heads sharing 4 key/value heads (grouped-query attention), a SwiGLU feed-forward (2,048 wide), RMSNorm, rotary position embeddings, QK-norm, and tied input and output embeddings.
|
| 23 |
+
- A 1,024-token context and its own 49,152-token byte-level BPE tokenizer (digits split, byte fallback), with ChatML turns (`<|im_start|>user ... <|im_end|>`).
|
| 24 |
+
- Trained from scratch on one RTX 5070 (12 GB): pretraining, then supervised fine-tuning, then DPO. This checkpoint is the DPO stage's.
|
| 25 |
+
|
| 26 |
+
## Run it
|
| 27 |
+
|
| 28 |
+
```bash
|
| 29 |
+
pip install -r requirements.txt
|
| 30 |
+
python run.py "How do I make brownies?"
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
`run.py` builds the model from `config.yaml` with the code in this folder (`model/`, `tokenizer/`, `cfg.py`), loads `model.safetensors`, wraps your question as a chat turn and samples up to 200 tokens (temperature 0.8, top-k 50), stopping at the end of the reply. Runs on CUDA, Apple MPS or CPU.
|
| 34 |
+
|
| 35 |
+
## What to expect
|
| 36 |
+
|
| 37 |
+
Well-formed, assistant-style answers (numbered steps, on topic) whose content is often wrong: it is a 113M model. MaxGPT-Ultra adds gated attention, a normalized value residual, depth-scaled norms and the NorMuon optimizer, the recipe that won an A/B test of four variants at this model's size.
|
| 38 |
+
|
| 39 |
+
## The MaxGPT family
|
| 40 |
+
|
| 41 |
+
Built from scratch by [Maxwell Brohm](https://maxwellbrohm.com), a high school senior, in PyTorch with no pretrained weights and no `transformers` library. Code, training curves and write-up: [github.com/MaxwellBrohm/MaxGPT](https://github.com/MaxwellBrohm/MaxGPT).
|
| 42 |
+
|
| 43 |
+
| Model | Parameters | Layers x width | Context | What it shows |
|
| 44 |
+
|---|---|---|---|---|
|
| 45 |
+
| MaxGPT-1 | 23M | 6 x 384 | 256 | coherent English emerges |
|
| 46 |
+
| MaxGPT-2 | 110M | 12 x 768 | 512 | learns the USER/ASSISTANT chat format |
|
| 47 |
+
| MaxGPT-3 | 235M | 16 x 1024 | 1024 | a real-looking chatbot |
|
| 48 |
+
| MaxGPT-3.5 | 235M | MaxGPT-3 plus chat fine-tuning | 1024 | replies like an assistant |
|
| 49 |
+
| MaxGPT-Mini (Neo series) | 113M | 12 x 768, grouped-query attention, RoPE, SwiGLU | 1024 | the modern design, chat-tuned with SFT and DPO |
|
| 50 |
+
|
| 51 |
+
MaxGPT-Ultra, a 1.09B model on a modern decoder design, is in progress.
|
cfg.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Config YAML loading (torch-free, so the GUI server can use it without importing torch).
|
| 2 |
+
|
| 3 |
+
A top-level `extends: other.yaml` (relative to the file) pulls that file in first and overlays
|
| 4 |
+
this one on top, so a per-machine config (configs/ultra_lambda.yaml) can change training
|
| 5 |
+
knobs while the model block in configs/ultra.yaml stays the one source of truth.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
import yaml
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _deep_merge(base: dict, over: dict) -> dict:
|
| 15 |
+
out = dict(base)
|
| 16 |
+
for k, v in over.items():
|
| 17 |
+
out[k] = _deep_merge(out[k], v) if isinstance(v, dict) and isinstance(out.get(k), dict) else v
|
| 18 |
+
return out
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def load_yaml(path: str) -> dict:
|
| 22 |
+
with open(path, encoding="utf-8") as f:
|
| 23 |
+
raw = yaml.safe_load(f) or {}
|
| 24 |
+
base = raw.pop("extends", None)
|
| 25 |
+
if not base:
|
| 26 |
+
return raw
|
| 27 |
+
base_path = base if os.path.isabs(base) else os.path.join(os.path.dirname(os.path.abspath(path)), base)
|
| 28 |
+
return _deep_merge(load_yaml(base_path), raw)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def configure_triton_ptxas() -> str | None:
|
| 32 |
+
"""Old NVIDIA drivers (< 525, CUDA 11.x era) cannot load the kernels Triton builds with its
|
| 33 |
+
bundled CUDA 12 ptxas ("device kernel image is invalid"), which silently costs the whole
|
| 34 |
+
torch.compile speedup. If such a driver is found and the CUDA 11.8 ptxas is installed in this
|
| 35 |
+
environment (pip: nvidia-cuda-nvcc-cu11), point Triton at it. Returns the path used, or None.
|
| 36 |
+
Torch-free and cheap, so every training script can call it first thing."""
|
| 37 |
+
import glob
|
| 38 |
+
import subprocess
|
| 39 |
+
import sys
|
| 40 |
+
if os.environ.get("TRITON_PTXAS_PATH"):
|
| 41 |
+
return os.environ["TRITON_PTXAS_PATH"]
|
| 42 |
+
try:
|
| 43 |
+
out = subprocess.run(["nvidia-smi", "--query-gpu=driver_version", "--format=csv,noheader"],
|
| 44 |
+
capture_output=True, text=True, timeout=5).stdout.strip().splitlines()
|
| 45 |
+
major = int(out[0].split(".")[0]) if out else 0
|
| 46 |
+
except Exception:
|
| 47 |
+
return None
|
| 48 |
+
if major == 0 or major >= 525:
|
| 49 |
+
return None
|
| 50 |
+
hits = glob.glob(os.path.join(sys.prefix, "lib", "python*", "site-packages", "nvidia", "cuda_nvcc", "bin", "ptxas"))
|
| 51 |
+
if not hits:
|
| 52 |
+
print(f"[setup] driver {major} is too old for Triton's ptxas; install nvidia-cuda-nvcc-cu11==11.8.89 "
|
| 53 |
+
f"to get torch.compile (running without it)", flush=True)
|
| 54 |
+
return None
|
| 55 |
+
os.environ["TRITON_PTXAS_PATH"] = hits[0]
|
| 56 |
+
return hits[0]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _driver_major() -> int:
|
| 60 |
+
import subprocess
|
| 61 |
+
try:
|
| 62 |
+
out = subprocess.run(["nvidia-smi", "--query-gpu=driver_version", "--format=csv,noheader"],
|
| 63 |
+
capture_output=True, text=True, timeout=5).stdout.strip().splitlines()
|
| 64 |
+
return int(out[0].split(".")[0]) if out else 0
|
| 65 |
+
except Exception:
|
| 66 |
+
return 0
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def cuda_alloc_conf() -> None:
|
| 70 |
+
"""Enable PyTorch's expandable-segments allocator (less fragmentation, so a bigger micro_batch
|
| 71 |
+
fits) on drivers that support it well. On old drivers (< 525) it reports a near-OOM as
|
| 72 |
+
"CUDA driver error: invalid argument" and can corrupt the allocator after a failed kernel
|
| 73 |
+
launch (seen on the Lambda box), so there we keep the default allocator. Never overrides an
|
| 74 |
+
explicit PYTORCH_CUDA_ALLOC_CONF."""
|
| 75 |
+
if "PYTORCH_CUDA_ALLOC_CONF" in os.environ:
|
| 76 |
+
return
|
| 77 |
+
major = _driver_major()
|
| 78 |
+
if major == 0 or major >= 525:
|
| 79 |
+
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
|
config.yaml
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MaxGPT-Ultra - SHAKEDOWN (prototype) config (~124M params)
|
| 2 |
+
# An exact scaled-down replica of the 1B. Goal: validate the ENTIRE pipeline
|
| 3 |
+
# (arch, data, training, WSD, SFT, DPO, RAG, GUI, autosave, pause/play) in days,
|
| 4 |
+
# and measure real throughput on the 5070 before committing to the long run.
|
| 5 |
+
name: maxgpt-ultra-shakedown
|
| 6 |
+
|
| 7 |
+
model:
|
| 8 |
+
vocab_size: 49152 # ~49k byte-level BPE (digit-split + byte fallback)
|
| 9 |
+
d_model: 768
|
| 10 |
+
n_layers: 12
|
| 11 |
+
n_heads: 12
|
| 12 |
+
n_kv_heads: 4 # GQA
|
| 13 |
+
mlp: swiglu
|
| 14 |
+
mlp_hidden: 2048 # ~8/3 * d_model
|
| 15 |
+
norm: rmsnorm
|
| 16 |
+
pos: rope
|
| 17 |
+
rope_theta: 10000
|
| 18 |
+
qk_norm: true
|
| 19 |
+
tie_embeddings: true
|
| 20 |
+
seq_len: 1024
|
| 21 |
+
# ~113M parameters (measured by scripts/smoke_test.py)
|
| 22 |
+
|
| 23 |
+
train:
|
| 24 |
+
precision: auto # bf16 where the card has it, else fp16 + loss scaling
|
| 25 |
+
optimizer: adamw # 'muon' optional (see PLAN.md)
|
| 26 |
+
lr: 6.0e-4
|
| 27 |
+
betas: [0.9, 0.95]
|
| 28 |
+
weight_decay: 0.1
|
| 29 |
+
grad_clip: 1.0
|
| 30 |
+
schedule: wsd # warmup -> stable -> decay
|
| 31 |
+
warmup_tokens: 2.0e8
|
| 32 |
+
total_tokens: 5.0e9 # quick validation budget (hours-to-days)
|
| 33 |
+
decay_frac: 0.2 # last 20% of tokens decay the LR
|
| 34 |
+
z_loss: 1.0e-4
|
| 35 |
+
# Tuned for a 12GB card (RTX 5070). The killer at this vocab is the output
|
| 36 |
+
# logits tensor: micro_batch * seq_len * 49152, so keep micro_batch small and
|
| 37 |
+
# make up the effective batch with grad_accum. tokens/step stays 4*32*1024=131072,
|
| 38 |
+
# so the schedule and total_steps are unchanged from micro_batch 16 / accum 8.
|
| 39 |
+
micro_batch: 4 # was 16 (16*1024 logits over 49k vocab OOM'd the 5070)
|
| 40 |
+
grad_accum: 32 # was 8; keeps effective ~131k tokens/step at seq 1024
|
| 41 |
+
grad_checkpointing: true # was false; recompute activations in backward to save VRAM
|
| 42 |
+
optimizer_8bit: false
|
| 43 |
+
compile: true
|
| 44 |
+
compile_modes: [max-autotune-no-cudagraphs, default] # no CUDA graphs: they break the checkpointed chunked loss (see train/trainer.py)
|
| 45 |
+
|
| 46 |
+
io:
|
| 47 |
+
autosave_minutes: 10
|
| 48 |
+
keep_last_k: 3
|
| 49 |
+
keep_best: true
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:60a6a40bb9177684e9f2f3bc5cfe2837ba3c3ec30ce2f9e960a87351d5a78b94
|
| 3 |
+
size 604076112
|
model/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .config import ModelConfig, load_yaml
|
| 2 |
+
from .model import MaxGPTUltra, RMSNorm, Attention, SwiGLU, Block
|
| 3 |
+
from .generate import generate
|
| 4 |
+
|
| 5 |
+
__all__ = ["ModelConfig", "load_yaml", "MaxGPTUltra", "RMSNorm", "Attention", "SwiGLU", "Block", "generate"]
|
model/config.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Model configuration for MaxGPT-Ultra.
|
| 2 |
+
|
| 3 |
+
A single dataclass describes the architecture. It can be built by hand or loaded
|
| 4 |
+
from a YAML file in configs/ (the `model:` block). The training-loop reads the
|
| 5 |
+
`train:` block separately.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import dataclasses
|
| 10 |
+
from dataclasses import dataclass
|
| 11 |
+
|
| 12 |
+
from cfg import load_yaml
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@dataclass
|
| 16 |
+
class ModelConfig:
|
| 17 |
+
# --- core dimensions ---
|
| 18 |
+
vocab_size: int = 49152 # ~49k byte-level BPE (49152 = 3 * 2^14, tensor-core aligned)
|
| 19 |
+
d_model: int = 768 # residual stream width
|
| 20 |
+
n_layers: int = 12 # number of transformer blocks
|
| 21 |
+
n_heads: int = 12 # query heads
|
| 22 |
+
n_kv_heads: int = 4 # key/value heads (GQA: n_heads must be a multiple of this)
|
| 23 |
+
mlp_hidden: int = 2048 # SwiGLU inner width (~8/3 * d_model)
|
| 24 |
+
seq_len: int = 1024 # max context the RoPE table is built for
|
| 25 |
+
|
| 26 |
+
# --- knobs ---
|
| 27 |
+
rope_theta: float = 10000.0 # RoPE base frequency
|
| 28 |
+
qk_norm: bool = True # RMSNorm on per-head Q and K before attention
|
| 29 |
+
tie_embeddings: bool = True # share the token embedding with the output head
|
| 30 |
+
rms_eps: float = 1e-5 # RMSNorm epsilon
|
| 31 |
+
init_std: float = 0.02 # std for the normal weight init
|
| 32 |
+
|
| 33 |
+
# --- optional tweaks from the 2025/26 small-model literature (all off by default; A/B'd before use) ---
|
| 34 |
+
attn_gate: bool = False # per-head sigmoid gate on the attention output (Qwen "Gated Attention" 2025, IMU-1 2026)
|
| 35 |
+
value_residual: bool = False # normalized value residual: mix layer 1's values into every later layer (IMU-1 2026)
|
| 36 |
+
norm_scaling: bool = False # scale each block's pre-norm outputs by 1/sqrt(layer index) ("LayerNorm scaling", IMU-1)
|
| 37 |
+
|
| 38 |
+
@property
|
| 39 |
+
def head_dim(self) -> int:
|
| 40 |
+
assert self.d_model % self.n_heads == 0, "d_model must be divisible by n_heads"
|
| 41 |
+
return self.d_model // self.n_heads
|
| 42 |
+
|
| 43 |
+
def __post_init__(self) -> None:
|
| 44 |
+
assert self.n_heads % self.n_kv_heads == 0, \
|
| 45 |
+
f"n_heads ({self.n_heads}) must be divisible by n_kv_heads ({self.n_kv_heads}) for GQA"
|
| 46 |
+
assert self.head_dim % 2 == 0, "head_dim must be even for RoPE"
|
| 47 |
+
|
| 48 |
+
@classmethod
|
| 49 |
+
def from_yaml(cls, path: str) -> "ModelConfig":
|
| 50 |
+
raw = load_yaml(path)
|
| 51 |
+
m = dict(raw.get("model", {}))
|
| 52 |
+
# These are design commitments, not knobs - assert the YAML agrees.
|
| 53 |
+
assert m.pop("norm", "rmsnorm") == "rmsnorm", "this architecture is RMSNorm-only"
|
| 54 |
+
assert m.pop("pos", "rope") == "rope", "this architecture is RoPE-only"
|
| 55 |
+
assert m.pop("mlp", "swiglu") == "swiglu", "this architecture is SwiGLU-only"
|
| 56 |
+
valid = {f.name for f in dataclasses.fields(cls)}
|
| 57 |
+
kwargs = {k: v for k, v in m.items() if k in valid}
|
| 58 |
+
return cls(**kwargs)
|
model/generate.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Autoregressive text generation.
|
| 2 |
+
|
| 3 |
+
Standard sampling loop with temperature, top-k, and top-p (nucleus) filtering. Used by
|
| 4 |
+
the eval harness (sample generations) and by inference / RAG. Pure model logic, so it
|
| 5 |
+
runs anywhere the model does.
|
| 6 |
+
|
| 7 |
+
Uses a KV cache: the prompt is encoded once (prefill), then each new token comes from a
|
| 8 |
+
single-token forward that reuses the cached keys/values. That makes generation O(n)
|
| 9 |
+
instead of O(n^2) (the old loop re-ran the whole sequence every step), which is roughly
|
| 10 |
+
10-50x faster for the lengths we generate.
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
import torch.nn.functional as F
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _sample(logits: torch.Tensor, temperature: float, top_k: int | None, top_p: float | None) -> torch.Tensor:
|
| 19 |
+
"""logits: (B, vocab) -> (B, 1) next-token ids. temperature 0 => greedy argmax."""
|
| 20 |
+
if temperature <= 0.0:
|
| 21 |
+
return logits.argmax(dim=-1, keepdim=True)
|
| 22 |
+
logits = logits / temperature
|
| 23 |
+
if top_k:
|
| 24 |
+
k = min(top_k, logits.size(-1))
|
| 25 |
+
kth = torch.topk(logits, k, dim=-1).values[:, -1, None]
|
| 26 |
+
logits = logits.masked_fill(logits < kth, float("-inf"))
|
| 27 |
+
if top_p:
|
| 28 |
+
sorted_logits, sorted_idx = torch.sort(logits, descending=True, dim=-1)
|
| 29 |
+
probs = F.softmax(sorted_logits, dim=-1)
|
| 30 |
+
cum = probs.cumsum(dim=-1) - probs # cumulative prob *before* each token
|
| 31 |
+
drop = cum > top_p
|
| 32 |
+
sorted_logits = sorted_logits.masked_fill(drop, float("-inf"))
|
| 33 |
+
logits = torch.full_like(logits, float("-inf")).scatter(-1, sorted_idx, sorted_logits)
|
| 34 |
+
probs = F.softmax(logits, dim=-1)
|
| 35 |
+
return torch.multinomial(probs, num_samples=1)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@torch.no_grad()
|
| 39 |
+
def generate(model, ids: torch.Tensor, max_new_tokens: int = 64, temperature: float = 1.0,
|
| 40 |
+
top_k: int | None = None, top_p: float | None = None,
|
| 41 |
+
eos_id: int | None = None) -> torch.Tensor:
|
| 42 |
+
"""ids: (B, T) prompt token ids. Returns (B, T + n) with up to max_new_tokens appended.
|
| 43 |
+
temperature 0 => greedy. Stops early once every sequence has emitted eos_id."""
|
| 44 |
+
was_training = model.training
|
| 45 |
+
model.eval()
|
| 46 |
+
seq_len = model.cfg.seq_len
|
| 47 |
+
ids = ids[:, -seq_len:] # never start beyond the context window
|
| 48 |
+
finished = torch.zeros(ids.size(0), dtype=torch.bool, device=ids.device)
|
| 49 |
+
|
| 50 |
+
logits, past = model(ids, use_cache=True) # prefill: encode the prompt, build the cache
|
| 51 |
+
for _ in range(max_new_tokens):
|
| 52 |
+
nxt = _sample(logits[:, -1, :], temperature, top_k, top_p)
|
| 53 |
+
ids = torch.cat([ids, nxt], dim=1)
|
| 54 |
+
if eos_id is not None:
|
| 55 |
+
finished = finished | (nxt.squeeze(-1) == eos_id)
|
| 56 |
+
if bool(finished.all()):
|
| 57 |
+
break
|
| 58 |
+
if ids.size(1) >= seq_len: # context window full (this cache doesn't slide)
|
| 59 |
+
break
|
| 60 |
+
logits, past = model(nxt, past=past, use_cache=True) # decode: one new token, reuse the cache
|
| 61 |
+
|
| 62 |
+
if was_training:
|
| 63 |
+
model.train()
|
| 64 |
+
return ids
|
model/model.py
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""MaxGPT-Ultra - a modern decoder-only transformer.
|
| 2 |
+
|
| 3 |
+
Design (Llama / Qwen / SmolLM2 lineage), every choice documented in TECHNIQUES.md:
|
| 4 |
+
- RoPE rotary positions (no learned position embeddings)
|
| 5 |
+
- RMSNorm, pre-norm, no biases anywhere
|
| 6 |
+
- SwiGLU feed-forward
|
| 7 |
+
- Grouped-query attention (GQA)
|
| 8 |
+
- QK-norm (RMSNorm on per-head Q/K) for high-LR stability
|
| 9 |
+
- Tied input/output embeddings
|
| 10 |
+
- z-loss available in the loss for logit-scale control
|
| 11 |
+
|
| 12 |
+
Attention uses torch's scaled_dot_product_attention, which dispatches to
|
| 13 |
+
FlashAttention on supported GPUs (and a math fallback on CPU).
|
| 14 |
+
"""
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.nn as nn
|
| 21 |
+
import torch.nn.functional as F
|
| 22 |
+
from torch.utils.checkpoint import checkpoint as grad_checkpoint
|
| 23 |
+
|
| 24 |
+
from .config import ModelConfig
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# --------------------------------------------------------------------------- #
|
| 28 |
+
# Normalization
|
| 29 |
+
# --------------------------------------------------------------------------- #
|
| 30 |
+
class RMSNorm(nn.Module):
|
| 31 |
+
"""Root-mean-square norm: rescale by RMS over the feature dim, then a learned
|
| 32 |
+
per-feature gain. No mean-centering and no bias, so it's cheaper than LayerNorm
|
| 33 |
+
and empirically just as stable. Computed in fp32 for numerical safety."""
|
| 34 |
+
|
| 35 |
+
def __init__(self, dim: int, eps: float = 1e-5):
|
| 36 |
+
super().__init__()
|
| 37 |
+
self.eps = eps
|
| 38 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 39 |
+
|
| 40 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 41 |
+
dtype = x.dtype
|
| 42 |
+
x = x.float()
|
| 43 |
+
x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 44 |
+
return x.to(dtype) * self.weight
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# --------------------------------------------------------------------------- #
|
| 48 |
+
# Rotary position embeddings (RoPE)
|
| 49 |
+
# --------------------------------------------------------------------------- #
|
| 50 |
+
def precompute_rope(head_dim: int, seq_len: int, theta: float,
|
| 51 |
+
dtype: torch.dtype = torch.float32):
|
| 52 |
+
"""Build the (seq_len, head_dim) cos/sin tables once. Rotating Q/K by these
|
| 53 |
+
angles injects *relative* position into the dot product, which generalizes
|
| 54 |
+
better than absolute learned positions."""
|
| 55 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim)) # (hd/2,)
|
| 56 |
+
pos = torch.arange(seq_len).float() # (T,)
|
| 57 |
+
freqs = torch.outer(pos, inv_freq) # (T, hd/2)
|
| 58 |
+
emb = torch.cat((freqs, freqs), dim=-1) # (T, hd)
|
| 59 |
+
return emb.cos().to(dtype), emb.sin().to(dtype)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def rotate_half(x: torch.Tensor) -> torch.Tensor:
|
| 63 |
+
x1, x2 = x.chunk(2, dim=-1)
|
| 64 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
|
| 68 |
+
# x: (B, n_heads, T, head_dim); cos/sin: (T, head_dim)
|
| 69 |
+
cos = cos[None, None, :, :]
|
| 70 |
+
sin = sin[None, None, :, :]
|
| 71 |
+
return (x * cos) + (rotate_half(x) * sin)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 75 |
+
"""Expand (B, n_kv, T, hd) -> (B, n_kv*n_rep, T, hd) so each KV head is shared
|
| 76 |
+
by n_rep query heads (the GQA trick: fewer KV heads = smaller KV cache + less
|
| 77 |
+
memory bandwidth, at almost no quality cost)."""
|
| 78 |
+
if n_rep == 1:
|
| 79 |
+
return x
|
| 80 |
+
B, n_kv, T, hd = x.shape
|
| 81 |
+
return (x[:, :, None, :, :]
|
| 82 |
+
.expand(B, n_kv, n_rep, T, hd)
|
| 83 |
+
.reshape(B, n_kv * n_rep, T, hd))
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# --------------------------------------------------------------------------- #
|
| 87 |
+
# Attention (GQA + QK-norm + RoPE)
|
| 88 |
+
# --------------------------------------------------------------------------- #
|
| 89 |
+
class Attention(nn.Module):
|
| 90 |
+
def __init__(self, cfg: ModelConfig, layer_idx: int = 0):
|
| 91 |
+
super().__init__()
|
| 92 |
+
self.n_heads = cfg.n_heads
|
| 93 |
+
self.n_kv_heads = cfg.n_kv_heads
|
| 94 |
+
self.n_rep = cfg.n_heads // cfg.n_kv_heads
|
| 95 |
+
self.head_dim = cfg.head_dim
|
| 96 |
+
|
| 97 |
+
self.q_proj = nn.Linear(cfg.d_model, cfg.n_heads * self.head_dim, bias=False)
|
| 98 |
+
self.k_proj = nn.Linear(cfg.d_model, cfg.n_kv_heads * self.head_dim, bias=False)
|
| 99 |
+
self.v_proj = nn.Linear(cfg.d_model, cfg.n_kv_heads * self.head_dim, bias=False)
|
| 100 |
+
self.o_proj = nn.Linear(cfg.n_heads * self.head_dim, cfg.d_model, bias=False)
|
| 101 |
+
|
| 102 |
+
self.qk_norm = cfg.qk_norm
|
| 103 |
+
if cfg.qk_norm:
|
| 104 |
+
self.q_norm = RMSNorm(self.head_dim, cfg.rms_eps)
|
| 105 |
+
self.k_norm = RMSNorm(self.head_dim, cfg.rms_eps)
|
| 106 |
+
|
| 107 |
+
# Gated attention: one sigmoid gate per head, computed from the block input, multiplies the
|
| 108 |
+
# attention output. 2*sigmoid(0) = 1, and the projection is zero-initialized, so the model
|
| 109 |
+
# starts exactly as an ungated one. Adds sparsity, removes attention sinks, stabilizes
|
| 110 |
+
# training (Qwen, NeurIPS 2025). Cost: one d_model x n_heads matmul per layer.
|
| 111 |
+
self.attn_gate = cfg.attn_gate
|
| 112 |
+
if cfg.attn_gate:
|
| 113 |
+
self.attn_gate_proj = nn.Linear(cfg.d_model, cfg.n_heads, bias=False)
|
| 114 |
+
# Value residual: layers after the first mix the FIRST layer's values into their own,
|
| 115 |
+
# V = s * (a1*V_local + a2*V_1) / sqrt(a1^2 + a2^2), learned (s, a1, a2) starting at (1, 1, 0)
|
| 116 |
+
# so it is an identity at init. Counters the value-stream degradation of deep stacks.
|
| 117 |
+
self.value_residual = cfg.value_residual and layer_idx > 0
|
| 118 |
+
if self.value_residual:
|
| 119 |
+
self.vr_scale = nn.Parameter(torch.ones(()))
|
| 120 |
+
self.vr_alpha = nn.Parameter(torch.tensor([1.0, 0.0]))
|
| 121 |
+
|
| 122 |
+
def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor,
|
| 123 |
+
past=None, use_cache: bool = False, v1: torch.Tensor | None = None,
|
| 124 |
+
mask: torch.Tensor | None = None):
|
| 125 |
+
"""Returns (out, new_kv or None, v_local). v_local is this layer's own values (pre-mix),
|
| 126 |
+
which the model hands to later layers as v1 when value_residual is on. `mask` (B, 1, T, T)
|
| 127 |
+
bool, True = may attend, replaces plain causal attention: the document mask for packed
|
| 128 |
+
SFT batches (see MaxGPTUltra.doc_mask)."""
|
| 129 |
+
B, T, _ = x.shape
|
| 130 |
+
q = self.q_proj(x).view(B, T, self.n_heads, self.head_dim)
|
| 131 |
+
k = self.k_proj(x).view(B, T, self.n_kv_heads, self.head_dim)
|
| 132 |
+
v = self.v_proj(x).view(B, T, self.n_kv_heads, self.head_dim)
|
| 133 |
+
|
| 134 |
+
# QK-norm: normalize each head's Q and K (over head_dim) before RoPE. Keeps
|
| 135 |
+
# the attention logits well-scaled so we can train at a higher learning rate.
|
| 136 |
+
if self.qk_norm:
|
| 137 |
+
q = self.q_norm(q)
|
| 138 |
+
k = self.k_norm(k)
|
| 139 |
+
|
| 140 |
+
q = q.transpose(1, 2) # (B, n_heads, T, hd)
|
| 141 |
+
k = k.transpose(1, 2) # (B, n_kv_heads, T, hd)
|
| 142 |
+
v = v.transpose(1, 2)
|
| 143 |
+
v_local = v
|
| 144 |
+
if self.value_residual and v1 is not None:
|
| 145 |
+
a1, a2 = self.vr_alpha[0], self.vr_alpha[1]
|
| 146 |
+
v = self.vr_scale * (a1 * v + a2 * v1) * torch.rsqrt(a1 * a1 + a2 * a2)
|
| 147 |
+
|
| 148 |
+
# RoPE uses absolute positions; cos/sin are pre-sliced to this chunk's positions (offset
|
| 149 |
+
# past the cache during incremental decode), so new tokens rotate at the right angle.
|
| 150 |
+
q = apply_rope(q, cos, sin)
|
| 151 |
+
k = apply_rope(k, cos, sin)
|
| 152 |
+
|
| 153 |
+
if past is not None: # prepend cached keys/values (post-RoPE, pre-GQA-repeat)
|
| 154 |
+
pk, pv = past
|
| 155 |
+
k = torch.cat([pk, k], dim=2)
|
| 156 |
+
v = torch.cat([pv, v], dim=2)
|
| 157 |
+
new_kv = (k, v) if use_cache else None
|
| 158 |
+
|
| 159 |
+
kr = repeat_kv(k, self.n_rep)
|
| 160 |
+
vr = repeat_kv(v, self.n_rep)
|
| 161 |
+
if past is None and mask is not None:
|
| 162 |
+
out = F.scaled_dot_product_attention(q, kr, vr, attn_mask=mask) # causal AND same document
|
| 163 |
+
elif past is None:
|
| 164 |
+
out = F.scaled_dot_product_attention(q, kr, vr, is_causal=True) # prefill / training
|
| 165 |
+
elif q.size(2) == 1:
|
| 166 |
+
out = F.scaled_dot_product_attention(q, kr, vr) # 1 new token attends to all cached
|
| 167 |
+
else:
|
| 168 |
+
Tq, Tk = q.size(2), kr.size(2) # several new tokens: causal among them
|
| 169 |
+
mask = torch.ones(Tq, Tk, dtype=torch.bool, device=q.device).tril(diagonal=Tk - Tq)
|
| 170 |
+
out = F.scaled_dot_product_attention(q, kr, vr, attn_mask=mask)
|
| 171 |
+
if self.attn_gate:
|
| 172 |
+
gate = 2.0 * torch.sigmoid(self.attn_gate_proj(x)) # (B, T, n_heads)
|
| 173 |
+
out = out * gate.transpose(1, 2).unsqueeze(-1).to(out.dtype)
|
| 174 |
+
out = out.transpose(1, 2).contiguous().view(B, T, self.n_heads * self.head_dim)
|
| 175 |
+
out = self.o_proj(out)
|
| 176 |
+
return out, new_kv, v_local
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
# --------------------------------------------------------------------------- #
|
| 180 |
+
# SwiGLU feed-forward
|
| 181 |
+
# --------------------------------------------------------------------------- #
|
| 182 |
+
class SwiGLU(nn.Module):
|
| 183 |
+
"""FFN(x) = down( silu(gate(x)) * up(x) ). The gated activation outperforms a
|
| 184 |
+
plain GELU MLP at the same parameter budget; hidden width is ~8/3 * d_model so
|
| 185 |
+
the three projections roughly match a 4x GELU MLP's parameter count."""
|
| 186 |
+
|
| 187 |
+
def __init__(self, cfg: ModelConfig):
|
| 188 |
+
super().__init__()
|
| 189 |
+
self.gate_proj = nn.Linear(cfg.d_model, cfg.mlp_hidden, bias=False)
|
| 190 |
+
self.up_proj = nn.Linear(cfg.d_model, cfg.mlp_hidden, bias=False)
|
| 191 |
+
self.down_proj = nn.Linear(cfg.mlp_hidden, cfg.d_model, bias=False)
|
| 192 |
+
|
| 193 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 194 |
+
return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
# --------------------------------------------------------------------------- #
|
| 198 |
+
# Transformer block (pre-norm)
|
| 199 |
+
# --------------------------------------------------------------------------- #
|
| 200 |
+
class Block(nn.Module):
|
| 201 |
+
def __init__(self, cfg: ModelConfig, layer_idx: int = 0):
|
| 202 |
+
super().__init__()
|
| 203 |
+
self.attn_norm = RMSNorm(cfg.d_model, cfg.rms_eps)
|
| 204 |
+
self.attn = Attention(cfg, layer_idx)
|
| 205 |
+
self.mlp_norm = RMSNorm(cfg.d_model, cfg.rms_eps)
|
| 206 |
+
self.mlp = SwiGLU(cfg)
|
| 207 |
+
# "LayerNorm scaling": deeper blocks see a 1/sqrt(depth)-scaled normalized input, which
|
| 208 |
+
# keeps late layers from being drowned by the growing residual stream (IMU-1, 2026).
|
| 209 |
+
self.norm_scale = (1.0 / math.sqrt(layer_idx + 1)) if cfg.norm_scaling else 1.0
|
| 210 |
+
|
| 211 |
+
def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor,
|
| 212 |
+
past=None, use_cache: bool = False, v1: torch.Tensor | None = None,
|
| 213 |
+
mask: torch.Tensor | None = None):
|
| 214 |
+
"""Pre-norm residuals: normalize the input to each sublayer, add the result back.
|
| 215 |
+
Returns (x, kv or None, v_local)."""
|
| 216 |
+
h = self.attn_norm(x)
|
| 217 |
+
if self.norm_scale != 1.0:
|
| 218 |
+
h = h * self.norm_scale
|
| 219 |
+
a, kv, v_local = self.attn(h, cos, sin, past, use_cache, v1, mask)
|
| 220 |
+
x = x + a
|
| 221 |
+
h = self.mlp_norm(x)
|
| 222 |
+
if self.norm_scale != 1.0:
|
| 223 |
+
h = h * self.norm_scale
|
| 224 |
+
x = x + self.mlp(h)
|
| 225 |
+
return x, kv, v_local
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
# --------------------------------------------------------------------------- #
|
| 229 |
+
# Full model
|
| 230 |
+
# --------------------------------------------------------------------------- #
|
| 231 |
+
class MaxGPTUltra(nn.Module):
|
| 232 |
+
def __init__(self, cfg: ModelConfig):
|
| 233 |
+
super().__init__()
|
| 234 |
+
self.cfg = cfg
|
| 235 |
+
self.grad_checkpointing = False # trainer sets True to trade compute for memory (fits the 1B on 12GB)
|
| 236 |
+
# Document (block-diagonal) attention for packed batches: with doc_mask on, a token may only
|
| 237 |
+
# attend to earlier tokens of ITS OWN document, documents being the spans separated by
|
| 238 |
+
# doc_sep_id (<|endoftext|>, which stays with the document it ends). Without it, packed SFT
|
| 239 |
+
# conversations attend into each other (measured up to +7% GSM8K / +4% HumanEval for the
|
| 240 |
+
# fix, docs/research_2026-09-22.md 3.1). RoPE is relative, so no position reset is needed:
|
| 241 |
+
# a packed conversation gets exactly the logits it would get alone (scripts/test_sft.py [5]).
|
| 242 |
+
self.doc_mask = False
|
| 243 |
+
self.doc_sep_id: int | None = None
|
| 244 |
+
self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.d_model)
|
| 245 |
+
self.blocks = nn.ModuleList([Block(cfg, i) for i in range(cfg.n_layers)])
|
| 246 |
+
self.norm = RMSNorm(cfg.d_model, cfg.rms_eps)
|
| 247 |
+
self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
|
| 248 |
+
if cfg.tie_embeddings:
|
| 249 |
+
self.lm_head.weight = self.tok_emb.weight # weight tying
|
| 250 |
+
|
| 251 |
+
cos, sin = precompute_rope(cfg.head_dim, cfg.seq_len, cfg.rope_theta)
|
| 252 |
+
self.register_buffer("rope_cos", cos, persistent=False)
|
| 253 |
+
self.register_buffer("rope_sin", sin, persistent=False)
|
| 254 |
+
|
| 255 |
+
self.apply(self._init_weights)
|
| 256 |
+
# Deep-net residual init: scale the *output* projection of each sublayer by
|
| 257 |
+
# 1/sqrt(2 * n_layers) so the residual stream doesn't blow up with depth.
|
| 258 |
+
for name, p in self.named_parameters():
|
| 259 |
+
if name.endswith("o_proj.weight") or name.endswith("down_proj.weight"):
|
| 260 |
+
nn.init.normal_(p, mean=0.0, std=cfg.init_std / math.sqrt(2 * cfg.n_layers))
|
| 261 |
+
elif name.endswith("attn_gate_proj.weight"):
|
| 262 |
+
nn.init.zeros_(p) # gate = 2*sigmoid(0) = 1: identical to no gate at init
|
| 263 |
+
|
| 264 |
+
def _init_weights(self, module: nn.Module) -> None:
|
| 265 |
+
if isinstance(module, nn.Linear):
|
| 266 |
+
nn.init.normal_(module.weight, mean=0.0, std=self.cfg.init_std)
|
| 267 |
+
if module.bias is not None:
|
| 268 |
+
nn.init.zeros_(module.bias)
|
| 269 |
+
elif isinstance(module, nn.Embedding):
|
| 270 |
+
nn.init.normal_(module.weight, mean=0.0, std=self.cfg.init_std)
|
| 271 |
+
|
| 272 |
+
def document_mask(self, idx: torch.Tensor) -> torch.Tensor:
|
| 273 |
+
"""(B, 1, T, T) bool: causal AND same document, documents split at doc_sep_id (the separator
|
| 274 |
+
belongs to the document it ends, so the token after it starts a new one)."""
|
| 275 |
+
assert self.doc_sep_id is not None, "doc_mask needs doc_sep_id (the tokenizer's eos_id)"
|
| 276 |
+
sep = (idx == self.doc_sep_id).long()
|
| 277 |
+
seg = torch.cumsum(sep, dim=1) - sep # (B, T) document index per token
|
| 278 |
+
same = seg[:, :, None] == seg[:, None, :] # (B, T, T)
|
| 279 |
+
causal = torch.ones(idx.size(1), idx.size(1), dtype=torch.bool, device=idx.device).tril()
|
| 280 |
+
return (same & causal)[:, None, :, :]
|
| 281 |
+
|
| 282 |
+
def forward(self, idx: torch.Tensor, targets: torch.Tensor | None = None,
|
| 283 |
+
z_loss_weight: float = 0.0, past=None, use_cache: bool = False):
|
| 284 |
+
B, T = idx.shape
|
| 285 |
+
past_len = past[0][0].size(2) if past is not None else 0 # cached key length (incremental decode)
|
| 286 |
+
assert past_len + T <= self.cfg.seq_len, \
|
| 287 |
+
f"sequence length {past_len + T} exceeds seq_len {self.cfg.seq_len}"
|
| 288 |
+
|
| 289 |
+
x = self.tok_emb(idx)
|
| 290 |
+
cos = self.rope_cos[past_len:past_len + T].to(x.dtype) # positions offset past the cache
|
| 291 |
+
sin = self.rope_sin[past_len:past_len + T].to(x.dtype)
|
| 292 |
+
mask = self.document_mask(idx) if (self.doc_mask and past is None and not use_cache) else None
|
| 293 |
+
new_caches = [] if use_cache else None
|
| 294 |
+
v1 = None # layer 1's values (value_residual)
|
| 295 |
+
for i, block in enumerate(self.blocks):
|
| 296 |
+
if self.grad_checkpointing and self.training:
|
| 297 |
+
x, _, v_loc = grad_checkpoint(block, x, cos, sin, None, False, v1, mask, use_reentrant=False)
|
| 298 |
+
else:
|
| 299 |
+
x, kv, v_loc = block(x, cos, sin, (past[i] if past is not None else None), use_cache, v1, mask)
|
| 300 |
+
if use_cache:
|
| 301 |
+
new_caches.append(kv)
|
| 302 |
+
if i == 0 and self.cfg.value_residual:
|
| 303 |
+
v1 = v_loc
|
| 304 |
+
x = self.norm(x)
|
| 305 |
+
|
| 306 |
+
# incremental-decode path: just logits + the updated KV cache (generation needs no loss)
|
| 307 |
+
if use_cache:
|
| 308 |
+
return self.lm_head(x), new_caches
|
| 309 |
+
|
| 310 |
+
# --- chunked loss (training, opt-in via self.loss_chunk) ---------------------------
|
| 311 |
+
# Compute CE (+ z-loss) over slices of positions, each slice checkpointed so its
|
| 312 |
+
# [chunk, vocab] logits are recomputed in backward instead of retained. The full
|
| 313 |
+
# [B*T, vocab] logits tensor (the single biggest VRAM block, ~GBs at 49k vocab) never
|
| 314 |
+
# materializes, which frees room for a larger micro_batch. Numerically identical to the
|
| 315 |
+
# full path below (sum the per-token loss, divide by the token count). Returns no logits
|
| 316 |
+
# (every targets-given caller discards them); targets=None still returns full logits.
|
| 317 |
+
chunk = getattr(self, "loss_chunk", 0)
|
| 318 |
+
if targets is not None and chunk:
|
| 319 |
+
xf = x.reshape(-1, x.size(-1))
|
| 320 |
+
tf = targets.reshape(-1)
|
| 321 |
+
zw = z_loss_weight
|
| 322 |
+
|
| 323 |
+
def _chunk_loss(xc, tc):
|
| 324 |
+
lc = self.lm_head(xc).float()
|
| 325 |
+
ce = F.cross_entropy(lc, tc, ignore_index=-100, reduction="sum")
|
| 326 |
+
z = ((torch.logsumexp(lc, dim=-1).pow(2) * (tc != -100).float()).sum()
|
| 327 |
+
if zw > 0.0 else lc.new_zeros(()))
|
| 328 |
+
return ce, z
|
| 329 |
+
|
| 330 |
+
ce_sum, z_sum, n_tok = xf.new_zeros(()), xf.new_zeros(()), xf.new_zeros(())
|
| 331 |
+
for i in range(0, xf.size(0), chunk):
|
| 332 |
+
xc, tc = xf[i:i + chunk], tf[i:i + chunk]
|
| 333 |
+
ce, z = (grad_checkpoint(_chunk_loss, xc, tc, use_reentrant=False)
|
| 334 |
+
if self.training else _chunk_loss(xc, tc))
|
| 335 |
+
ce_sum = ce_sum + ce
|
| 336 |
+
z_sum = z_sum + z
|
| 337 |
+
n_tok = n_tok + (tc != -100).sum()
|
| 338 |
+
denom = n_tok.clamp(min=1)
|
| 339 |
+
loss = ce_sum / denom
|
| 340 |
+
if zw > 0.0:
|
| 341 |
+
loss = loss + zw * (z_sum / denom)
|
| 342 |
+
return None, loss
|
| 343 |
+
# ------------------------------------------------------------------------------------
|
| 344 |
+
|
| 345 |
+
logits = self.lm_head(x)
|
| 346 |
+
|
| 347 |
+
loss = None
|
| 348 |
+
if targets is not None:
|
| 349 |
+
logits_flat = logits.view(-1, logits.size(-1)).float() # fp32 for the softmax
|
| 350 |
+
targets_flat = targets.view(-1)
|
| 351 |
+
if (targets_flat != -100).any():
|
| 352 |
+
loss = F.cross_entropy(logits_flat, targets_flat, ignore_index=-100)
|
| 353 |
+
else:
|
| 354 |
+
loss = logits_flat.sum() * 0.0 # batch had no supervised tokens (SFT masking edge case)
|
| 355 |
+
if z_loss_weight > 0.0:
|
| 356 |
+
# z-loss penalizes large logsumexp, keeping logits from drifting huge
|
| 357 |
+
lse = torch.logsumexp(logits_flat, dim=-1)
|
| 358 |
+
keep = targets_flat != -100
|
| 359 |
+
z = (lse[keep].pow(2).mean() if keep.any() else lse.pow(2).mean())
|
| 360 |
+
loss = loss + z_loss_weight * z
|
| 361 |
+
return logits, loss
|
| 362 |
+
|
| 363 |
+
@torch.no_grad()
|
| 364 |
+
def num_params(self, non_embedding: bool = False) -> int:
|
| 365 |
+
n = sum(p.numel() for p in self.parameters()) # tied weights counted once
|
| 366 |
+
if non_embedding:
|
| 367 |
+
n -= self.tok_emb.weight.numel()
|
| 368 |
+
if self.lm_head.weight is not self.tok_emb.weight:
|
| 369 |
+
n -= self.lm_head.weight.numel()
|
| 370 |
+
return n
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
safetensors
|
| 3 |
+
tokenizers
|
| 4 |
+
pyyaml
|
run.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Chat with MaxGPT-Mini: python run.py "How do I make brownies?"
|
| 2 |
+
Needs torch, safetensors, tokenizers and pyyaml. Runs on CUDA, Apple MPS or CPU."""
|
| 3 |
+
import sys
|
| 4 |
+
import torch
|
| 5 |
+
from safetensors.torch import load_file
|
| 6 |
+
from model import ModelConfig, MaxGPTUltra, generate
|
| 7 |
+
from tokenizer.tokenizer import UltraTokenizer, IM_END
|
| 8 |
+
|
| 9 |
+
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
| 10 |
+
model = MaxGPTUltra(ModelConfig.from_yaml("config.yaml"))
|
| 11 |
+
model.load_state_dict(load_file("model.safetensors"))
|
| 12 |
+
model.to(device).eval()
|
| 13 |
+
tok = UltraTokenizer("tokenizer.json")
|
| 14 |
+
question = sys.argv[1] if len(sys.argv) > 1 else "How do I make brownies?"
|
| 15 |
+
ids = torch.tensor([tok.encode_chat([{"role": "user", "content": question}])], device=device)
|
| 16 |
+
with torch.no_grad():
|
| 17 |
+
out = generate(model, ids, max_new_tokens=200, temperature=0.8, top_k=50, eos_id=tok.specials[IM_END])
|
| 18 |
+
print(tok.decode(out[0, ids.shape[1]:].tolist(), skip_special=True).strip())
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer/__init__.py
ADDED
|
File without changes
|
tokenizer/tokenizer.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""MaxGPT-Ultra tokenizer.
|
| 2 |
+
|
| 3 |
+
A byte-level BPE tokenizer with:
|
| 4 |
+
- digit-splitting (every digit is its own token, which helps arithmetic),
|
| 5 |
+
- byte fallback (all 256 bytes are in the base vocab, so nothing is ever OOV),
|
| 6 |
+
- special tokens reserved up front (chat roles, tools, reasoning, plus spares),
|
| 7 |
+
so chat / tool-use / thinking work without ever resizing the vocabulary.
|
| 8 |
+
|
| 9 |
+
Train one with `train_tokenizer(...)`; load and use it with `UltraTokenizer(path)`.
|
| 10 |
+
The real run trains vocab=49152 on a sample of the corpus; the smoke test trains a
|
| 11 |
+
tiny one to validate the pipeline.
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
from typing import Iterable
|
| 17 |
+
|
| 18 |
+
from tokenizers import Tokenizer, models, pre_tokenizers, decoders, trainers
|
| 19 |
+
|
| 20 |
+
# --- special tokens, reserved up front (added first => low, stable ids) ---
|
| 21 |
+
END = "<|endoftext|>" # document separator, doubles as BOS and EOS
|
| 22 |
+
PAD = "<|pad|>"
|
| 23 |
+
IM_START = "<|im_start|>" # ChatML turn open (e.g. <|im_start|>user\n...)
|
| 24 |
+
IM_END = "<|im_end|>" # ChatML turn close
|
| 25 |
+
TOOL_CALL = "<|tool_call|>" # model is requesting a tool (search, etc.)
|
| 26 |
+
TOOL_RESPONSE = "<|tool_response|>" # tool output fed back in
|
| 27 |
+
THINK_START = "<think>" # reasoning scratchpad
|
| 28 |
+
THINK_END = "</think>"
|
| 29 |
+
|
| 30 |
+
SPECIAL_TOKENS = [
|
| 31 |
+
END, PAD, IM_START, IM_END, TOOL_CALL, TOOL_RESPONSE, THINK_START, THINK_END,
|
| 32 |
+
] + [f"<|reserved_{i}|>" for i in range(16)] # 16 spare slots for the future
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _byte_level_bpe() -> Tokenizer:
|
| 36 |
+
tok = Tokenizer(models.BPE(unk_token=None)) # byte-level => no UNK ever
|
| 37 |
+
tok.pre_tokenizer = pre_tokenizers.Sequence([
|
| 38 |
+
pre_tokenizers.Digits(individual_digits=True), # "1234" -> "1","2","3","4"
|
| 39 |
+
pre_tokenizers.ByteLevel(add_prefix_space=False, use_regex=True),
|
| 40 |
+
])
|
| 41 |
+
tok.decoder = decoders.ByteLevel()
|
| 42 |
+
return tok
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def train_tokenizer(text_iterator: Iterable[str], vocab_size: int = 49152,
|
| 46 |
+
out_path: str = "tokenizer/maxgpt-ultra.tokenizer.json") -> Tokenizer:
|
| 47 |
+
tok = _byte_level_bpe()
|
| 48 |
+
trainer = trainers.BpeTrainer(
|
| 49 |
+
vocab_size=vocab_size,
|
| 50 |
+
special_tokens=SPECIAL_TOKENS, # reserve ids 0..N
|
| 51 |
+
initial_alphabet=pre_tokenizers.ByteLevel.alphabet(), # all 256 bytes -> true byte fallback
|
| 52 |
+
show_progress=False,
|
| 53 |
+
)
|
| 54 |
+
tok.train_from_iterator(text_iterator, trainer=trainer)
|
| 55 |
+
tok.add_special_tokens(SPECIAL_TOKENS) # ensure they encode atomically
|
| 56 |
+
if os.path.dirname(out_path):
|
| 57 |
+
os.makedirs(os.path.dirname(out_path), exist_ok=True)
|
| 58 |
+
tok.save(out_path)
|
| 59 |
+
return tok
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class UltraTokenizer:
|
| 63 |
+
"""Loads a trained tokenizer and adds chat rendering + special-token ids."""
|
| 64 |
+
|
| 65 |
+
def __init__(self, path: str):
|
| 66 |
+
self.tok = Tokenizer.from_file(path)
|
| 67 |
+
self.specials = {t: self.tok.token_to_id(t) for t in SPECIAL_TOKENS}
|
| 68 |
+
self.eos_id = self.specials[END]
|
| 69 |
+
self.bos_id = self.specials[END] # we reuse <|endoftext|> for both
|
| 70 |
+
self.pad_id = self.specials[PAD]
|
| 71 |
+
|
| 72 |
+
@property
|
| 73 |
+
def vocab_size(self) -> int:
|
| 74 |
+
return self.tok.get_vocab_size()
|
| 75 |
+
|
| 76 |
+
def encode(self, text: str) -> list[int]:
|
| 77 |
+
return self.tok.encode(text).ids
|
| 78 |
+
|
| 79 |
+
def encode_batch(self, texts: list[str]) -> list[list[int]]:
|
| 80 |
+
"""Encode many docs at once: the Rust tokenizer spreads a batch over every CPU core
|
| 81 |
+
(TOKENIZERS_PARALLELISM), which is what turns a single-core data build into a
|
| 82 |
+
download-bound one on a big box. Same ids as encode(), doc by doc."""
|
| 83 |
+
return [e.ids for e in self.tok.encode_batch(texts)]
|
| 84 |
+
|
| 85 |
+
def decode(self, ids: list[int], skip_special: bool = False) -> str:
|
| 86 |
+
return self.tok.decode(ids, skip_special_tokens=skip_special)
|
| 87 |
+
|
| 88 |
+
def render_chat(self, messages: list[dict], add_generation_prompt: bool = True) -> str:
|
| 89 |
+
"""messages: [{'role': 'system'|'user'|'assistant', 'content': str}, ...] -> ChatML string."""
|
| 90 |
+
parts = [f"{IM_START}{m['role']}\n{m['content']}{IM_END}\n" for m in messages]
|
| 91 |
+
if add_generation_prompt:
|
| 92 |
+
parts.append(f"{IM_START}assistant\n")
|
| 93 |
+
return "".join(parts)
|
| 94 |
+
|
| 95 |
+
def encode_chat(self, messages: list[dict], add_generation_prompt: bool = True) -> list[int]:
|
| 96 |
+
return self.encode(self.render_chat(messages, add_generation_prompt))
|