A straightforward method for training your LLM, from downloading data to generating text.
feat(models): a modern decoder next to the classic Transformer
FareedKhan-dev0cca1300ea1b
diff --git a/src/models/modern/__init__.py b/src/models/modern/__init__.pynew file mode 100644index 0000000..632c2a0--- /dev/null+++ b/src/models/modern/__init__.py@@ -0,0 +1,27 @@+"""The modern (2024-2026 style) decoder. See ``model.py`` for what changed and why."""++from src.models.modern.attention import GroupedQueryAttention, MultiHeadLatentAttention, attention_mask+from src.models.modern.block import ModernBlock+from src.models.modern.config import ModernConfig+from src.models.modern.kv_cache import KVCache+from src.models.modern.mlp import SwiGLU+from src.models.modern.model import ModernTransformer+from src.models.modern.moe import MoE+from src.models.modern.norm import RMSNorm+from src.models.modern.rope import apply_rope, rope_cache, rope_frequencies++__all__ = [+ "GroupedQueryAttention",+ "KVCache",+ "MoE",+ "ModernBlock",+ "ModernConfig",+ "ModernTransformer",+ "MultiHeadLatentAttention",+ "RMSNorm",+ "SwiGLU",+ "apply_rope",+ "attention_mask",+ "rope_cache",+ "rope_frequencies",+]diff --git a/src/models/modern/block.py b/src/models/modern/block.pynew file mode 100644index 0000000..74fce7a--- /dev/null+++ b/src/models/modern/block.py@@ -0,0 +1,48 @@+"""+One block of the modern model: the same pre-norm residual shape as the classic block,++ x = x + attention(norm(x))+ x = x + mlp(norm(x))++with RMSNorm instead of LayerNorm, rotary attention (GQA or MLA) instead of the classic+heads, and a SwiGLU or Mixture-of-Experts layer instead of the ReLU MLP.+"""++from __future__ import annotations++import torch.nn as nn+from jaxtyping import Float+from torch import Tensor++from src.models.modern.attention import GroupedQueryAttention, MultiHeadLatentAttention+from src.models.modern.config import ModernConfig+from src.models.modern.kv_cache import KVCache+from src.models.modern.mlp import SwiGLU+from src.models.modern.moe import MoE+from src.models.modern.norm import RMSNorm+++class ModernBlock(nn.Module):+ def __init__(self, cfg: ModernConfig, layer_idx: int) -> None:+ super().__init__()+ self.attn_norm = RMSNorm(cfg.n_embed, cfg.norm_eps)+ self.attn: nn.Module = (+ MultiHeadLatentAttention(cfg, layer_idx) if cfg.attention == "mla" else GroupedQueryAttention(cfg, layer_idx)+ )+ self.mlp_norm = RMSNorm(cfg.n_embed, cfg.norm_eps)+ self.mlp: nn.Module = (+ MoE(cfg.n_embed, cfg.hidden_dim, cfg.n_experts, cfg.moe_top_k, cfg.n_shared_experts)+ if cfg.n_experts > 0+ else SwiGLU(cfg.n_embed, cfg.hidden_dim)+ )++ def forward(+ self,+ x: Float[Tensor, "batch seq embed"],+ cos: Float[Tensor, "seq half"],+ sin: Float[Tensor, "seq half"],+ cache: KVCache | None = None,+ ) -> Float[Tensor, "batch seq embed"]:+ x = x + self.attn(self.attn_norm(x), cos, sin, cache)+ x = x + self.mlp(self.mlp_norm(x))+ return xdiff --git a/src/models/modern/model.py b/src/models/modern/model.pynew file mode 100644index 0000000..250cefb--- /dev/null+++ b/src/models/modern/model.py@@ -0,0 +1,193 @@+"""+The modern decoder: the same job as the classic ``Transformer``, built the way 2024-2026+open models (Llama 3/4, Qwen 3, Gemma 3, DeepSeek-V3, OLMo 2) are built.++ token ids -> embedding -> N x ModernBlock -> RMSNorm -> lm_head (tied to the embedding)++What changed compared with the classic model, and why:++- No learned position table: positions come from rotary embeddings inside attention, so+ there are no position parameters and attention sees relative distances.+- RMSNorm instead of LayerNorm, SwiGLU instead of ReLU, no biases in linear layers.+- Grouped-query attention or multi-head latent attention, with a KV cache for generation.+- Optional Mixture of Experts, sliding-window attention and gated attention.+- The output layer shares its weight with the input embedding ("tied embeddings"), which+ saves ``vocab_size * n_embed`` parameters, a large fraction of a small model.+- Small, depth-scaled initialization: residual output projections start at+ ``init_std / sqrt(2 * n_blocks)`` so the residual stream does not grow with depth (GPT-2).++It has the same interface as the classic model (``forward``, ``forward_hidden``, ``lm_head``,+``context_length``, ``generate``), so every post-training stage works with it unchanged.+"""++from __future__ import annotations++import math++import torch+import torch.nn as nn+import torch.nn.functional as F+import torch.utils.checkpoint as checkpoint+from jaxtyping import Float, Int+from torch import Tensor++from src.inference.sampling import sample_next_token+from src.models.modern.block import ModernBlock+from src.models.modern.config import ModernConfig+from src.models.modern.kv_cache import KVCache+from src.models.modern.moe import MoE+from src.models.modern.norm import RMSNorm+from src.models.modern.rope import rope_cache+++class ModernTransformer(nn.Module):+ def __init__(self, config: ModernConfig) -> None:+ super().__init__()+ self.config = config+ self.context_length = config.context_length+ self.gradient_checkpointing = False+ self.token_embed = nn.Embedding(config.vocab_size, config.n_embed)+ self.drop = nn.Dropout(config.dropout)+ self.blocks = nn.ModuleList([ModernBlock(config, i) for i in range(config.n_blocks)])+ self.final_norm = RMSNorm(config.n_embed, config.norm_eps)+ self.lm_head = nn.Linear(config.n_embed, config.vocab_size, bias=False)+ if config.tie_embeddings:+ self.lm_head.weight = self.token_embed.weight++ cos, sin = rope_cache(config.rope_table_dim, config.context_length, config.rope_theta)+ self.register_buffer("rope_cos", cos, persistent=False) # rebuilt on load, never saved+ self.register_buffer("rope_sin", sin, persistent=False)+ self.aux_loss: Tensor | None = None++ self.apply(self._init_weights)+ residual_std = config.init_std / math.sqrt(2 * config.n_blocks)+ for name, param in self.named_parameters():+ if name.endswith(("o_proj.weight", "down.weight")):+ nn.init.normal_(param, mean=0.0, std=residual_std)++ def _init_weights(self, module: nn.Module) -> None:+ if isinstance(module, nn.Linear):+ nn.init.normal_(module.weight, mean=0.0, std=self.config.init_std)+ if module.bias is not None:+ nn.init.zeros_(module.bias)+ elif isinstance(module, nn.Embedding):+ nn.init.normal_(module.weight, mean=0.0, std=self.config.init_std)++ # ------------------------------------------------------------------ forward+ def forward_hidden(+ self, idx: Int[Tensor, "batch seq"], cache: KVCache | None = None+ ) -> Float[Tensor, "batch seq embed"]:+ """Hidden states after the final norm (what ``lm_head`` reads; reward/value heads reuse it)."""+ T = idx.size(1)+ start = cache.length if cache is not None else 0+ if start + T > self.context_length:+ raise ValueError(f"sequence of {start + T} tokens exceeds context_length {self.context_length}")+ cos, sin = self.rope_cos[start : start + T], self.rope_sin[start : start + T]+ x = self.drop(self.token_embed(idx))+ for block in self.blocks:+ if self.gradient_checkpointing and self.training and cache is None:+ x = checkpoint.checkpoint(block, x, cos, sin, use_reentrant=False)+ else:+ x = block(x, cos, sin, cache)+ if cache is not None:+ cache.advance(T)+ self.aux_loss = self._moe_aux_loss()+ return self.final_norm(x)++ def forward(+ self, idx: Int[Tensor, "batch seq"], targets: Int[Tensor, "batch seq"] | None = None+ ) -> tuple[Float[Tensor, "batch seq vocab"], Float[Tensor, ""] | None]:+ logits = self.lm_head(self.forward_hidden(idx))+ loss = None+ if targets is not None:+ loss = F.cross_entropy(logits.reshape(-1, logits.size(-1)), targets.reshape(-1).long())+ if self.aux_loss is not None:+ loss = loss + self.config.moe_aux_loss_coef * self.aux_loss+ return logits, loss++ def _moe_aux_loss(self) -> Tensor | None:+ losses = [b.mlp.aux_loss for b in self.blocks if isinstance(b.mlp, MoE) and b.mlp.aux_loss is not None]+ return torch.stack(losses).mean() if losses else None++ # ------------------------------------------------------------------ generation+ def new_cache(self, batch_size: int) -> KVCache:+ """An empty KV cache sized for this model (it stores the latent for MLA)."""+ cfg = self.config+ ref = self.token_embed.weight+ if cfg.attention == "mla":+ heads, k_dim, v_dim = 1, cfg.latent_dim, cfg.mla_rope_dim+ else:+ heads, k_dim, v_dim = cfg.kv_heads, cfg.head_dim, cfg.head_dim+ return KVCache(cfg.n_blocks, batch_size, cfg.context_length, heads, k_dim, v_dim,+ device=ref.device, dtype=ref.dtype)++ @torch.no_grad()+ def generate(+ self,+ idx: Int[Tensor, "batch seq"],+ max_new_tokens: int,+ temperature: float = 1.0,+ top_k: int | None = None,+ top_p: float | None = None,+ min_p: float | None = None,+ use_cache: bool = True,+ context_window: int | None = None,+ ) -> Int[Tensor, "batch total"]:+ """+ Sample ``max_new_tokens`` tokens after ``idx``.++ With the cache, the prompt is processed once ("prefill") and every later step feeds only+ the newest token ("decode"). When the window fills up, the most recent half is+ re-encoded into a fresh cache, so generation can run longer than ``context_length``.+ """+ window = min(context_window or self.context_length, self.context_length)+ if not use_cache:+ for _ in range(max_new_tokens):+ logits = self(idx[:, -window:])[0][:, -1, :]+ idx = torch.cat([idx, sample_next_token(logits, temperature, top_k, top_p, min_p)], dim=1)+ return idx++ cache = self.new_cache(idx.size(0))+ hidden = self.forward_hidden(idx[:, -window:], cache) # prefill+ for _ in range(max_new_tokens):+ logits = self.lm_head(hidden[:, -1, :])+ next_token = sample_next_token(logits, temperature, top_k, top_p, min_p)+ idx = torch.cat([idx, next_token], dim=1)+ if cache.length >= window: # out of room: keep the latest half and continue+ cache.reset()+ hidden = self.forward_hidden(idx[:, -(window // 2) :], cache)+ else:+ hidden = self.forward_hidden(next_token, cache) # decode one token+ return idx++ # ------------------------------------------------------------------ accounting+ def num_params(self, exclude_embeddings: bool = False) -> int:+ """Parameter count (tied weights counted once)."""+ n = sum(p.numel() for p in self.parameters())+ return n - self.token_embed.weight.numel() if exclude_embeddings else n++ def active_params(self) -> int:+ """Parameters used per token: with MoE only ``moe_top_k`` of the routed experts run."""+ n = self.num_params()+ for block in self.blocks:+ if isinstance(block.mlp, MoE):+ per_expert = sum(p.numel() for p in block.mlp.experts[0].parameters())+ n -= per_expert * (block.mlp.n_experts - block.mlp.top_k)+ return n++ def flops_per_token(self, seq_len: int | None = None) -> float:+ """+ Training FLOPs per token (forward + backward), following PaLM appendix B:++ - ``6`` FLOPs per weight that multiplies the token (2 forward, 4 backward). The input+ embedding is a lookup and costs nothing; the output layer is a real matmul.+ - the attention scores and the weighted sum of values, which grow with ``seq_len``.+ """+ cfg = self.config+ T = seq_len or cfg.context_length+ body = self.active_params() - self.token_embed.weight.numel()+ if not cfg.tie_embeddings:+ body -= self.lm_head.weight.numel()+ qk_dim = cfg.head_dim + (cfg.mla_rope_dim if cfg.attention == "mla" else 0)+ attention = 6 * cfg.n_blocks * cfg.n_head * T * (qk_dim + cfg.head_dim)+ return 6 * body + 6 * cfg.n_embed * cfg.vocab_size + attentiondiff --git a/tests/test_modern_model.py b/tests/test_modern_model.pynew file mode 100644index 0000000..012fc68--- /dev/null+++ b/tests/test_modern_model.py@@ -0,0 +1,247 @@+"""+Tests for the modern decoder (src/models/modern).++Most tests check a property that must hold rather than a hard-coded number: causality,+cached decoding matching a full forward pass, rotary embeddings depending only on relative+position, grouped-query attention matching multi-head attention with copied heads, and so on.+"""++from __future__ import annotations++import math+from dataclasses import replace++import pytest+import torch+import torch.nn.functional as F++from src.models.modern import (+ GroupedQueryAttention,+ ModernConfig,+ ModernTransformer,+ MoE,+ RMSNorm,+ apply_rope,+ rope_cache,+)++BASE = ModernConfig(vocab_size=97, context_length=32, n_embed=32, n_head=4, n_blocks=2, n_kv_head=2)++VARIANTS = {+ "gqa": BASE,+ "mha": replace(BASE, n_kv_head=None),+ "mqa": replace(BASE, n_kv_head=1),+ "mla": replace(BASE, attention="mla", kv_latent_dim=12, rope_dim=4),+ "window": replace(BASE, sliding_window=5),+ "moe": replace(BASE, n_experts=4, moe_top_k=2, n_shared_experts=1),+ "gated_no_qknorm": replace(BASE, attn_gate=True, qk_norm=False, tie_embeddings=False),+}+++def _model(cfg: ModernConfig, seed: int = 0) -> ModernTransformer:+ torch.manual_seed(seed)+ return ModernTransformer(cfg).eval()++[email protected]("name", list(VARIANTS))+def test_forward_shapes_and_loss(name: str) -> None:+ cfg = VARIANTS[name]+ model = _model(cfg)+ idx = torch.randint(0, cfg.vocab_size, (3, 16))+ targets = torch.randint(0, cfg.vocab_size, (3, 16))+ logits, loss = model(idx, targets)+ assert logits.shape == (3, 16, cfg.vocab_size)+ assert loss is not None and loss.ndim == 0+ # a freshly initialized model should be close to a uniform guess: loss ~ ln(vocab)+ assert abs(loss.item() - math.log(cfg.vocab_size)) < 0.5++[email protected]("name", list(VARIANTS))+def test_causality(name: str) -> None:+ """Changing a token must not change the predictions for earlier positions."""+ cfg = VARIANTS[name]+ model = _model(cfg)+ idx = torch.randint(0, cfg.vocab_size, (2, 20))+ changed = idx.clone()+ changed[:, 12] = (changed[:, 12] + 1) % cfg.vocab_size+ with torch.no_grad():+ a, _ = model(idx)+ b, _ = model(changed)+ assert torch.allclose(a[:, :12], b[:, :12], atol=1e-5)+ assert not torch.allclose(a[:, 12:], b[:, 12:], atol=1e-5)++[email protected]("name", list(VARIANTS))+def test_kv_cache_matches_full_forward(name: str) -> None:+ """Prefill 7 tokens, then decode one token at a time: logits must equal a full pass."""+ cfg = VARIANTS[name]+ model = _model(cfg)+ idx = torch.randint(0, cfg.vocab_size, (2, 18))+ with torch.no_grad():+ full, _ = model(idx)+ cache = model.new_cache(batch_size=2)+ steps = [model.lm_head(model.forward_hidden(idx[:, :7], cache))]+ for t in range(7, 18):+ steps.append(model.lm_head(model.forward_hidden(idx[:, t : t + 1], cache)))+ assert cache.length == 18+ assert torch.allclose(torch.cat(steps, dim=1), full, atol=1e-4)+++def test_sliding_window_limits_what_a_token_sees() -> None:+ """With one block and window w, position t only depends on tokens t-w+1 .. t."""+ cfg = replace(BASE, n_blocks=1, sliding_window=4)+ model = _model(cfg)+ idx = torch.randint(0, cfg.vocab_size, (1, 16))+ changed = idx.clone()+ changed[:, 5] = (changed[:, 5] + 1) % cfg.vocab_size # outside the window of position 9..15+ with torch.no_grad():+ a, _ = model(idx)+ b, _ = model(changed)+ assert torch.allclose(a[:, 9:], b[:, 9:], atol=1e-5)+ assert not torch.allclose(a[:, 5:9], b[:, 5:9], atol=1e-5)+++def test_rope_scores_depend_only_on_relative_position() -> None:+ torch.manual_seed(0)+ cos, sin = rope_cache(dim=16, max_len=64)+ q, k = torch.randn(16), torch.randn(16)++ def score(m: int, n: int) -> float:+ qm = apply_rope(q[None], cos[m : m + 1], sin[m : m + 1])[0]+ kn = apply_rope(k[None], cos[n : n + 1], sin[n : n + 1])[0]+ return float(qm @ kn)++ assert math.isclose(score(10, 3), score(40, 33), rel_tol=1e-4, abs_tol=1e-4)+ assert math.isclose(score(5, 5), float(q @ k), rel_tol=1e-4, abs_tol=1e-4) # same position: no change+++def test_rope_is_a_rotation_of_each_pair() -> None:+ """Pair (x[i], x[i + d/2]) at position m is rotated by the angle m * theta_i."""+ torch.manual_seed(0)+ dim, m = 8, 7+ cos, sin = rope_cache(dim=dim, max_len=16)+ x = torch.randn(dim)+ out = apply_rope(x[None], cos[m : m + 1], sin[m : m + 1])[0]+ half = dim // 2+ for i in range(half):+ angle = m * 10_000.0 ** (-2 * i / dim)+ rot = torch.tensor([[math.cos(angle), -math.sin(angle)], [math.sin(angle), math.cos(angle)]])+ expected = rot @ torch.stack([x[i], x[i + half]])+ assert torch.allclose(torch.stack([out[i], out[i + half]]), expected, atol=1e-5)+ assert torch.allclose(out.norm(), x.norm(), atol=1e-5) # rotations keep the length+++def test_rmsnorm_matches_torch() -> None:+ x = torch.randn(4, 10, 32)+ ours, ref = RMSNorm(32, eps=1e-6), torch.nn.RMSNorm(32, eps=1e-6)+ with torch.no_grad():+ ours.weight.uniform_(0.5, 1.5)+ ref.weight.copy_(ours.weight)+ assert torch.allclose(ours(x), ref(x), atol=1e-5)+++def test_gqa_equals_mha_with_shared_heads() -> None:+ """GQA with 2 KV heads == MHA whose 4 KV heads are copies (heads 0,1 share KV 0; 2,3 share KV 1)."""+ gqa_cfg = replace(BASE, n_kv_head=2, qk_norm=False)+ mha_cfg = replace(BASE, n_kv_head=4, qk_norm=False)+ torch.manual_seed(0)+ gqa, mha = GroupedQueryAttention(gqa_cfg, 0), GroupedQueryAttention(mha_cfg, 0)+ D = BASE.head_dim+ with torch.no_grad():+ mha.q_proj.weight.copy_(gqa.q_proj.weight)+ mha.o_proj.weight.copy_(gqa.o_proj.weight)+ for proj in ("k_proj", "v_proj"):+ w = getattr(gqa, proj).weight.view(2, D, -1) # (kv_heads, D, C)+ getattr(mha, proj).weight.copy_(w.repeat_interleave(2, dim=0).reshape(4 * D, -1))+ x = torch.randn(2, 9, BASE.n_embed)+ cos, sin = rope_cache(D, 9)+ assert torch.allclose(gqa(x, cos, sin), mha(x, cos, sin), atol=1e-5)+++def test_mla_caches_much_less_than_mha() -> None:+ mha = _model(replace(BASE, n_kv_head=None)).new_cache(1)+ mla = _model(VARIANTS["mla"]).new_cache(1)+ assert mla.k.shape[-1] == 12 and mla.v.shape[-1] == 4 # latent + shared rotary key+ assert mla.bytes_per_token() * 3 < mha.bytes_per_token()+++def test_moe_routes_tokens_and_balancing_loss_trains_the_router() -> None:+ torch.manual_seed(0)+ moe = MoE(n_embed=16, hidden=32, n_experts=4, top_k=2)+ x = torch.randn(2, 10, 16)+ y = moe(x)+ assert y.shape == x.shape+ assert moe.tokens_per_expert is not None and moe.tokens_per_expert.sum().item() == 2 * 10 * 2+ assert moe.aux_loss is not None and moe.aux_loss.item() >= 0.99 # == 1 only for perfect balance+ moe.aux_loss.backward()+ assert moe.router.weight.grad is not None and moe.router.weight.grad.abs().sum() > 0+++def test_moe_loss_includes_aux_and_active_params_are_smaller() -> None:+ model = _model(VARIANTS["moe"])+ idx = torch.randint(0, BASE.vocab_size, (2, 8))+ logits, loss = model(idx, idx)+ plain = F.cross_entropy(logits.reshape(-1, BASE.vocab_size), idx.reshape(-1))+ assert model.aux_loss is not None+ assert torch.allclose(loss, plain + BASE.moe_aux_loss_coef * model.aux_loss)+ assert model.active_params() < model.num_params()+++def test_tied_embeddings_share_one_matrix() -> None:+ tied, untied = _model(BASE), _model(replace(BASE, tie_embeddings=False))+ assert tied.lm_head.weight is tied.token_embed.weight+ assert untied.num_params() - tied.num_params() == BASE.vocab_size * BASE.n_embed++[email protected]("name", ["gqa", "moe"])+def test_gradient_checkpointing_gives_the_same_gradients(name: str) -> None:+ cfg = VARIANTS[name]+ idx = torch.randint(0, cfg.vocab_size, (2, 12))+ grads = []+ for ckpt in (False, True):+ model = _model(cfg).train()+ model.gradient_checkpointing = ckpt+ _, loss = model(idx, idx)+ loss.backward()+ grads.append(torch.cat([p.grad.flatten() for p in model.parameters() if p.grad is not None]))+ assert torch.allclose(grads[0], grads[1], atol=1e-5)++[email protected]("name", ["gqa", "mla", "window"])+def test_cached_and_uncached_generation_agree(name: str) -> None:+ model = _model(VARIANTS[name])+ prompt = torch.randint(0, BASE.vocab_size, (2, 5))+ a = model.generate(prompt, 20, top_k=1, use_cache=True)+ b = model.generate(prompt, 20, top_k=1, use_cache=False)+ assert torch.equal(a, b)+++def test_generation_can_run_past_the_context_window() -> None:+ model = _model(BASE)+ out = model.generate(torch.zeros(1, 4, dtype=torch.long), max_new_tokens=3 * BASE.context_length)+ assert out.shape == (1, 4 + 3 * BASE.context_length)+++def test_config_validation() -> None:+ with pytest.raises(ValueError, match="divisible"):+ ModernConfig(n_embed=30, n_head=4)+ with pytest.raises(ValueError, match="n_kv_head"):+ ModernConfig(n_embed=32, n_head=4, n_kv_head=3)+ assert ModernConfig.from_mapping({"n_embed": 64, "n_head": 4, "lr": 1e-3}).n_embed == 64+++def test_post_training_wrappers_accept_the_modern_model() -> None:+ from src.post_training.reward_model import RewardModel+ from src.post_training.rollout import compute_logprobs, generate_with_logprobs+ from src.post_training.value_head import TransformerWithValueHead++ model = _model(BASE)+ actor = TransformerWithValueHead(model)+ idx = torch.randint(0, BASE.vocab_size, (2, 8))+ logits, values = actor(idx)+ assert logits.shape == (2, 8, BASE.vocab_size) and values.shape == (2, 8)+ reward = RewardModel(_model(BASE))(idx, seq_lengths=torch.tensor([8, 5]))+ assert reward.shape == (2,)+ rb = generate_with_logprobs(model, idx[:, :4], max_new_tokens=6)+ lp, mask = compute_logprobs(model, rb.sequences, rb.response_mask, requires_grad=False)+ assert torch.allclose(rb.gen_logprobs[rb.response_mask[:, 4:]], lp[mask], atol=1e-4)