Skip to content

A straightforward method for training your LLM, from downloading data to generating text.

feat(models): RMSNorm, rotary embeddings, SwiGLU and a KV cache

FareedKhan-dev70bc89827c96
diff --git a/pyproject.toml b/pyproject.toml
index 2643daf..5aa6df4 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -20,6 +20,7 @@ dependencies = [
"tiktoken",
"zstandard",
"requests",
+ "jaxtyping",
]
[project.optional-dependencies]
diff --git a/src/models/modern/config.py b/src/models/modern/config.py
new file mode 100644
index 0000000..7c6e63c
--- /dev/null
+++ b/src/models/modern/config.py
@@ -0,0 +1,115 @@
+"""
+Settings for :class:`~src.models.modern.model.ModernTransformer`.
+
+The defaults describe a small Llama / Qwen style decoder. Every switch maps to one idea from
+the last few years of LLM research, and each one can be turned off to see what it buys:
+
+================== =====================================================================
+field what it does
+================== =====================================================================
+``n_kv_head`` grouped-query attention: several query heads share one key/value head
+``attention`` ``"gqa"`` (standard) or ``"mla"`` (DeepSeek's multi-head latent attention)
+``rope_theta`` base of the rotary position embedding frequencies
+``qk_norm`` RMSNorm on queries and keys before attention (OLMo 2, Qwen 3, Gemma 3)
+``attn_gate`` sigmoid gate on the attention output (Qwen3-Next, gated attention)
+``sliding_window`` each token only attends to the last N tokens (Mistral, Gemma 3)
+``tie_embeddings`` the output layer reuses the input embedding matrix
+``n_experts`` > 0 swaps the dense MLP for a Mixture of Experts (Mixtral, DeepSeek, Qwen 3)
+================== =====================================================================
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from dataclasses import asdict, dataclass, fields
+from typing import Any, Literal
+
+AttentionKind = Literal["gqa", "mla"]
+
+
+def round_up(value: int, multiple: int) -> int:
+ return ((value + multiple - 1) // multiple) * multiple
+
+
+@dataclass(frozen=True)
+class ModernConfig:
+ # size
+ vocab_size: int = 50304
+ context_length: int = 1024
+ n_embed: int = 768
+ n_head: int = 12
+ n_blocks: int = 12
+ ffn_hidden: int | None = None # SwiGLU width; None = 8/3 * n_embed rounded up to 64
+ # attention
+ attention: AttentionKind = "gqa"
+ n_kv_head: int | None = None # None = n_head (plain multi-head); 1 = multi-query
+ kv_latent_dim: int | None = None # MLA: size of the cached key/value latent; None = n_embed // 4
+ rope_dim: int | None = None # MLA: per-head dims that carry position; None = head_dim // 2
+ rope_theta: float = 10_000.0
+ qk_norm: bool = True
+ attn_gate: bool = False
+ sliding_window: int | None = None
+ # mixture of experts
+ n_experts: int = 0 # 0 = dense SwiGLU MLP
+ moe_top_k: int = 2
+ n_shared_experts: int = 0
+ moe_aux_loss_coef: float = 0.01
+ # misc
+ tie_embeddings: bool = True
+ norm_eps: float = 1e-6
+ init_std: float = 0.02
+ dropout: float = 0.0
+
+ def __post_init__(self) -> None:
+ def need(cond: bool, msg: str) -> None:
+ if not cond:
+ raise ValueError(f"ModernConfig: {msg}")
+
+ for name in ("vocab_size", "context_length", "n_embed", "n_head", "n_blocks"):
+ need(getattr(self, name) > 0, f"{name} must be positive")
+ need(self.n_embed % self.n_head == 0, "n_embed must be divisible by n_head")
+ need(self.head_dim % 2 == 0, "head_dim (n_embed / n_head) must be even for rotary embeddings")
+ need(self.attention in ("gqa", "mla"), "attention must be 'gqa' or 'mla'")
+ need(self.n_head % self.kv_heads == 0, "n_head must be divisible by n_kv_head")
+ need(self.mla_rope_dim % 2 == 0, "rope_dim must be even")
+ need(self.sliding_window is None or self.sliding_window > 0, "sliding_window must be positive")
+ need(self.n_experts >= 0, "n_experts must be >= 0")
+ if self.n_experts:
+ need(1 <= self.moe_top_k <= self.n_experts, "moe_top_k must be between 1 and n_experts")
+ need(0.0 <= self.dropout < 1.0, "dropout must be in [0, 1)")
+
+ # ------------------------------------------------------------------ derived sizes
+ @property
+ def head_dim(self) -> int:
+ return self.n_embed // self.n_head
+
+ @property
+ def kv_heads(self) -> int:
+ return self.n_kv_head or self.n_head
+
+ @property
+ def hidden_dim(self) -> int:
+ return self.ffn_hidden or round_up(int(8 * self.n_embed / 3), 64)
+
+ @property
+ def latent_dim(self) -> int:
+ return self.kv_latent_dim or max(16, self.n_embed // 4)
+
+ @property
+ def mla_rope_dim(self) -> int:
+ return self.rope_dim or max(2, self.head_dim // 2)
+
+ @property
+ def rope_table_dim(self) -> int:
+ """Width of the cos/sin tables: the full head for GQA, the decoupled part for MLA."""
+ return self.mla_rope_dim if self.attention == "mla" else self.head_dim
+
+ # ------------------------------------------------------------------ conversion
+ @classmethod
+ def from_mapping(cls, values: Mapping[str, Any]) -> ModernConfig:
+ """Build from any mapping (a JSON config, a checkpoint ``cfg``), ignoring unrelated keys."""
+ known = {f.name for f in fields(cls)}
+ return cls(**{k: v for k, v in values.items() if k in known})
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
diff --git a/src/models/modern/kv_cache.py b/src/models/modern/kv_cache.py
new file mode 100644
index 0000000..b5b6c22
--- /dev/null
+++ b/src/models/modern/kv_cache.py
@@ -0,0 +1,64 @@
+"""
+A key/value cache for fast generation.
+
+Without a cache, generating token ``t`` re-runs the whole prefix through every layer, so a
+reply of ``n`` tokens costs O(n^2) work. But the keys and values of old tokens never change
+(the attention is causal), so we can keep them. Each new token then only computes its own
+query, key and value and attends to the stored ones: generation becomes O(n).
+
+The cache is the main memory cost of serving an LLM, which is exactly why grouped-query
+attention and multi-head latent attention exist: they shrink what has to be stored per token.
+:meth:`KVCache.bytes_per_token` makes that cost visible.
+"""
+
+from __future__ import annotations
+
+import torch
+from jaxtyping import Float
+from torch import Tensor
+
+
+class KVCache:
+ """Preallocated keys and values for every layer. ``length`` counts the tokens stored."""
+
+ def __init__(
+ self,
+ n_layers: int,
+ batch_size: int,
+ max_len: int,
+ n_kv_heads: int,
+ k_dim: int,
+ v_dim: int,
+ *,
+ device: torch.device | str = "cpu",
+ dtype: torch.dtype = torch.float32,
+ ) -> None:
+ self.max_len = max_len
+ self.length = 0
+ shape = (n_layers, batch_size, n_kv_heads, max_len)
+ self.k = torch.zeros(*shape, k_dim, device=device, dtype=dtype)
+ self.v = torch.zeros(*shape, v_dim, device=device, dtype=dtype)
+
+ def update(
+ self, layer: int, k_new: Float[Tensor, "batch heads seq k_dim"], v_new: Float[Tensor, "batch heads seq v_dim"]
+ ) -> tuple[Float[Tensor, "batch heads total k_dim"], Float[Tensor, "batch heads total v_dim"]]:
+ """Store this step's keys/values for ``layer`` and return everything cached so far."""
+ end = self.length + k_new.size(2)
+ if end > self.max_len:
+ raise ValueError(f"KV cache is full ({self.max_len} tokens); reset it or use a longer one")
+ self.k[layer, :, :, self.length : end] = k_new
+ self.v[layer, :, :, self.length : end] = v_new
+ return self.k[layer, :, :, :end], self.v[layer, :, :, :end]
+
+ def advance(self, n_tokens: int) -> None:
+ """Called once per forward pass, after every layer has stored its new entries."""
+ self.length += n_tokens
+
+ def reset(self) -> None:
+ self.length = 0
+
+ def bytes_per_token(self) -> int:
+ """Memory one token costs across all layers (keys + values)."""
+ n_layers, batch, heads = self.k.shape[:3]
+ per_token = heads * (self.k.shape[-1] + self.v.shape[-1]) * self.k.element_size()
+ return n_layers * per_token
diff --git a/src/models/modern/mlp.py b/src/models/modern/mlp.py
new file mode 100644
index 0000000..172cfd6
--- /dev/null
+++ b/src/models/modern/mlp.py
@@ -0,0 +1,30 @@
+"""
+SwiGLU feed-forward block (Shazeer, 2020), used by Llama, Qwen, Mistral, DeepSeek and Gemma.
+
+The classic MLP is ``proj(relu(hidden(x)))``. A gated linear unit computes two projections
+and lets one gate the other:
+
+ SwiGLU(x) = down( silu(gate(x)) * up(x) )
+
+The gate decides, feature by feature, how much of ``up(x)`` passes through. It has three
+matrices instead of two, so the hidden width is ``8/3 * n_embed`` instead of ``4 * n_embed``
+to keep the parameter count the same. It consistently trains to a lower loss than ReLU or GELU.
+"""
+
+from __future__ import annotations
+
+import torch.nn as nn
+import torch.nn.functional as F
+from jaxtyping import Float
+from torch import Tensor
+
+
+class SwiGLU(nn.Module):
+ def __init__(self, n_embed: int, hidden: int) -> None:
+ super().__init__()
+ self.gate = nn.Linear(n_embed, hidden, bias=False)
+ self.up = nn.Linear(n_embed, hidden, bias=False)
+ self.down = nn.Linear(hidden, n_embed, bias=False)
+
+ def forward(self, x: Float[Tensor, "*batch embed"]) -> Float[Tensor, "*batch embed"]:
+ return self.down(F.silu(self.gate(x)) * self.up(x))
diff --git a/src/models/modern/norm.py b/src/models/modern/norm.py
new file mode 100644
index 0000000..0d774a4
--- /dev/null
+++ b/src/models/modern/norm.py
@@ -0,0 +1,30 @@
+"""
+RMSNorm (Zhang and Sennrich, 2019), the normalization used by Llama, Qwen, Gemma and DeepSeek.
+
+LayerNorm subtracts the mean and divides by the standard deviation. RMSNorm skips the mean:
+
+ RMSNorm(x) = x / sqrt(mean(x^2) + eps) * weight
+
+It is cheaper, has no bias, and works just as well in practice. The statistics are computed
+in float32 even when the model runs in bfloat16, because squaring small bf16 numbers loses
+precision quickly.
+"""
+
+from __future__ import annotations
+
+import torch
+import torch.nn as nn
+from jaxtyping import Float
+from torch import Tensor
+
+
+class RMSNorm(nn.Module):
+ def __init__(self, dim: int, eps: float = 1e-6) -> None:
+ super().__init__()
+ self.eps = eps
+ self.weight = nn.Parameter(torch.ones(dim))
+
+ def forward(self, x: Float[Tensor, "*batch dim"]) -> Float[Tensor, "*batch dim"]:
+ x32 = x.float()
+ normed = x32 * torch.rsqrt(x32.pow(2).mean(dim=-1, keepdim=True) + self.eps)
+ return normed.type_as(x) * self.weight
diff --git a/src/models/modern/rope.py b/src/models/modern/rope.py
new file mode 100644
index 0000000..f52f58c
--- /dev/null
+++ b/src/models/modern/rope.py
@@ -0,0 +1,46 @@
+"""
+Rotary position embeddings (RoPE, Su et al. 2021), used by nearly every modern LLM.
+
+The classic model *adds* a learned position vector to each token. RoPE instead *rotates* the
+query and key vectors by an angle that grows with the position. Split a head vector into
+pairs of numbers; pair ``i`` at position ``m`` is rotated by the angle ``m * theta_i`` with
+
+ theta_i = rope_theta ** (-2i / head_dim)
+
+so early pairs spin fast (they track nearby words) and late pairs spin slowly (they track
+long-range structure). The useful property: the dot product of a query at position ``m`` and
+a key at position ``n`` only depends on ``m - n``. Attention therefore sees *relative*
+positions, with no position parameters to learn.
+
+We use the "rotate half" layout (pair ``i`` is ``(x[i], x[i + d/2])``), as in most open code.
+"""
+
+from __future__ import annotations
+
+import torch
+from jaxtyping import Float
+from torch import Tensor
+
+
+def rope_frequencies(dim: int, theta: float = 10_000.0) -> Float[Tensor, " half"]:
+ """The rotation speed ``theta_i`` of each of the ``dim / 2`` pairs."""
+ return 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
+
+
+def rope_cache(
+ dim: int, max_len: int, theta: float = 10_000.0
+) -> tuple[Float[Tensor, "seq half"], Float[Tensor, "seq half"]]:
+ """Precompute ``cos`` and ``sin`` of every angle ``position * theta_i``."""
+ positions = torch.arange(max_len, dtype=torch.float32)
+ angles = torch.outer(positions, rope_frequencies(dim, theta))
+ return angles.cos(), angles.sin()
+
+
+def apply_rope(
+ x: Float[Tensor, "*batch seq dim"], cos: Float[Tensor, "seq half"], sin: Float[Tensor, "seq half"]
+) -> Float[Tensor, "*batch seq dim"]:
+ """Rotate every pair ``(x1, x2)`` of ``x`` by its angle: a 2D rotation per pair."""
+ half = x.shape[-1] // 2
+ x1, x2 = x[..., :half], x[..., half:]
+ cos, sin = cos.to(x.dtype), sin.to(x.dtype)
+ return torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1)