Coding tutorial · Build it from scratch

Build a Modern LLM From Scratch

RMSNorm, RoPE, grouped-query attention, SwiGLU, a key-value (KV) cache and modern sampling, one tested module at a time. At the end our code reproduces the logits of Hugging Face’s Llama and runs real pretrained weights.

Language modelsPyTorchHugging Face

What you will build

blog-coding-tutorials/c04-llm

tinyllm, a Llama-style decoder with RMSNorm, RoPE, grouped-query attention, SwiGLU, a KV cache and modern sampling. It reproduces the logits of Hugging Face’s LlamaForCausalLM and runs the real SmolLM2-135M weights.

Time
About 2 hours of reading, plus about 35 minutes of CPU runs. Training takes about 12 minutes, and the head comparison about 21.
Hardware
Any laptop or CPU machine. No GPU needed. Numbers here come from an AMD EPYC 7R13 CPU with 8 threads, unless a block says otherwise. The GPU numbers come from one NVIDIA H100 80GB HBM3 (PyTorch 2.15.0, CUDA 13.2), and they are labelled.
You need
Python 3.10+, PyTorch 2.5 or newer (for enable_gqa), transformers 5 or newer, safetensors, pytest. The results here used PyTorch 2.15 and transformers 5.22.
Package
tinyllm
Final repo tree c04-llm/
c04-llm/
├── README.md                   # every command, results table
├── conftest.py
├── configs/                    # tiny, smollm2-135m, llama3-8b as JSON
├── results/                    # saved outputs of every run in this post
├── tinyllm/
│   ├── config.py               # ModelConfig and presets
│   ├── tokenizer.py            # byte tokenizer
│   ├── norm.py                 # RMSNorm
│   ├── rope.py                 # RotaryEmbedding, apply_rotary
│   ├── attention_naive.py      # reference attention, masks, reshapes
│   ├── attention_sdpa.py       # the fused kernel
│   ├── attention.py            # GroupedQueryAttention
│   ├── kv_cache.py             # KVCache
│   ├── mlp.py                  # SwiGLU
│   ├── moe.py                  # optional mixture of experts
│   ├── block.py                # DecoderBlock
│   ├── model.py                # TinyLLM
│   ├── loss.py                 # shifted cross-entropy
│   ├── init.py                 # init_weights
│   ├── params.py               # closed-form counts
│   ├── sampling.py             # temperature, top-k, top-p
│   ├── generation.py           # generate, cached and uncached
│   ├── checkpoint.py           # native save and load
│   ├── hf.py                   # LlamaForCausalLM conversion
│   └── utils.py                # device, seed, timer
├── scripts/
│   ├── walkthrough.py          # one experiment per step
│   ├── inspect_shapes.py       # every tensor in one block
│   ├── param_count.py
│   ├── compare_hf.py           # the trusted-implementation check
│   ├── train_sanity.py         # about 12 minutes on Tiny Shakespeare
│   ├── generate.py
│   ├── break_it.py             # every intentional failure
│   ├── moe_demo.py
│   └── compare_heads.py        # MHA vs GQA vs MQA
├── benchmarks/
│   ├── bench_attention.py
│   └── bench_generation.py
└── tests/
    ├── c04_helpers.py
    ├── test_components.py      # norm, RoPE, attention, SwiGLU, loss
    ├── test_model.py           # shapes, causality, parameter counts
    ├── test_cache.py           # full forward == cached forward
    ├── test_hf_parity.py       # logits match LlamaForCausalLM
    ├── test_matches_c3.py      # matches the C3 attention library
    ├── test_sampling.py
    ├── test_checkpoint.py      # round trip and resume
    ├── test_precision.py       # bf16
    ├── test_gpu.py             # GPU only, 5 tests, pass on an H100
    └── test_moe.py

The plan

What is inside a modern language model, tensor by tensor? And how do you prove that your version is correct, and not only plausible?

We answer both by building one. The model follows the Llama design, which is also the design of SmolLM2 and close to that of Qwen and many others. It differs from the 2017 transformer in four places. It uses RMSNorm instead of LayerNorm. It uses RoPE instead of added position vectors. It shares keys and values across query heads. It replaces the plain MLP with a gated one.

Why these changesWhat changed inside the transformer

This post does not repeat those arguments. It writes the code, runs it, and looks at the tensors. Each step adds one module and one check. At step 12 we hand our weights to Hugging Face and ask for the same logits. Then we run the other direction and load a real pretrained model into our own code.

The attention code comes from Build Attention From Scratch. We keep its GQA and RoPE design and its names, trimmed to what a decoder needs, and a test checks that the two agree. Unless a block says otherwise, the numbers below came from an AMD EPYC 7R13 CPU with 8 threads. The GPU blocks came from one NVIDIA H100 80GB HBM3 and are labelled. Commands run from the repo root.

$ git clone https://github.com/srini-anirudh/blog-coding-tutorials.git
$ cd blog-coding-tutorials
$ python -m venv .venv && .venv/bin/pip install -e ".[dev]"

Here is the whole journey in one figure. Press Next to walk it, or read on and come back to it.

Figure 1One token through one block of the tiny preset, for the input “The cat sat” (B = 1, T = 11). The camera follows the data. Shapes and RMS values come from scripts/inspect_shapes.py.
Step 01

Put every number in one configuration

Goal A dataclass that describes the whole architecture and rejects impossible shapes early.

Every module reads its sizes from one object. That lets us save the architecture next to the weights, translate it to Hugging Face later, and build Llama 3 8B on the meta device from one line.

@dataclass
class ModelConfig:
    """Hyperparameters of a Llama-style decoder-only transformer.

    The first seven fields are the contract other tutorials rely on (C5 trains this model).
    The rest have defaults that match Llama / SmolLM2 conventions.
    """

    vocab_size: int
    hidden_size: int
    num_layers: int
    num_heads: int
    num_kv_heads: int
    intermediate_size: int
    max_seq_len: int

    head_dim: int | None = None  # None means hidden_size // num_heads
    rope_theta: float = 10_000.0
    rms_norm_eps: float = 1e-5
    tie_word_embeddings: bool = True
    initializer_range: float = 0.02
    attn_backend: str = "sdpa"  # "naive" (reference) or "sdpa" (fused kernel)

    # Mixture of experts. num_experts == 0 means every block uses a dense SwiGLU.
    num_experts: int = 0
    num_experts_per_tok: int = 2
    expert_capacity_factor: float | None = None  # None means no token is ever dropped
    router_aux_loss_coef: float = 0.01

    def __post_init__(self) -> None:
        if self.head_dim is None:
            if self.hidden_size % self.num_heads != 0:
                raise ValueError(f"hidden_size={self.hidden_size} is not divisible by num_heads={self.num_heads}")
            self.head_dim = self.hidden_size // self.num_heads
        if self.num_heads % self.num_kv_heads != 0:
            raise ValueError(f"num_heads={self.num_heads} must be a multiple of num_kv_heads={self.num_kv_heads}")
        if self.head_dim % 2 != 0:
            raise ValueError("RoPE rotates pairs of channels, so head_dim must be even")
        if self.attn_backend not in ("naive", "sdpa"):
            raise ValueError(f"unknown attn_backend {self.attn_backend!r}")
        if self.num_experts and not 1 <= self.num_experts_per_tok <= self.num_experts:
            raise ValueError("num_experts_per_tok must be between 1 and num_experts")
Listing 1The first seven fields are the contract the next tutorial trains. The validation catches the two mistakes that otherwise surface as a confusing reshape error deep in attention.

Three of the checks encode real constraints. Head width must be an integer. Query heads must divide evenly among key and value heads. RoPE rotates pairs of channels, so head width must be even.

$ .venv/bin/python c04-llm/scripts/walkthrough.py --step config
ModelConfig(vocab_size=256, hidden_size=256, num_layers=6, num_heads=8, num_kv_heads=2, intermediate_size=704, max_seq_len=256, head_dim=32, rope_theta=10000.0, rms_norm_eps=1e-05, tie_word_embeddings=True, initializer_range=0.02, attn_backend='sdpa', num_experts=0, num_experts_per_tok=2, expert_capacity_factor=None, router_aux_loss_coef=0.01)
head_dim = 256 // 8 = 32
query heads per kv head = 8 // 2 = 4
num_kv_heads=3 -> ValueError: num_heads=8 must be a multiple of num_kv_heads=3
The symbols used in this post, with the tiny preset's values
SymbolFieldTinyMeaning
Vvocab_size256One token per byte.
Dhidden_size256Width of the residual stream.
Lnum_layers6Decoder blocks.
Hnum_heads8Query heads.
H_kvnum_kv_heads2Key and value heads.
dhead_dim32Width of one head, D // H.
Fintermediate_size704Width inside SwiGLU.

Checkpoint

  • num_kv_heads=3 raises a clear ValueError.
  • test_config_rejects_bad_heads and test_config_files_match_presets pass.
Step 02

Token embeddings and weight tying

Goal Turn ids into vectors, and use one matrix for both reading and scoring tokens.

An embedding is a lookup table: X = E[ids]. The table has V rows and D columns. The same id always returns the same row, at any position. Position enters later, inside attention.

We use a byte tokenizer, so V is exactly 256 and nothing needs downloading or training. The next tutorial replaces it with a trained byte-pair encoding (BPE) tokenizer.

Weight tying means the output layer reuses the embedding matrix. Tying is one assignment in the constructor. After it, both names point to the same Parameter, and gradients from both uses add up in one place.

    def __init__(self, config: ModelConfig) -> None:
        super().__init__()
        self.config = config
        self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
        self.rotary = RotaryEmbedding(config.head_dim, config.max_seq_len, config.rope_theta)
        self.layers = nn.ModuleList(DecoderBlock(config, i) for i in range(config.num_layers))
        self.norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
        self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
        if config.tie_word_embeddings:
            # One (V, D) matrix reads tokens in and scores tokens out.
            self.lm_head.weight = self.embed_tokens.weight
        init_weights(self, config)
Listing 2The model constructor. The highlighted assignment is all of weight tying. Attribute names match Hugging Face, which pays off in step 12.
$ .venv/bin/python c04-llm/scripts/walkthrough.py --step embeddings
ids torch.Size([1, 11]): [84, 104, 101, 32, 99, 97, 116, 32, 115, 97, 116]
x   torch.Size([1, 11, 256])  rms=0.0201
the two 'a' bytes (positions 5 and 9) get the same vector: True
tied: lm_head.weight is embed_tokens.weight -> True
params tied 4,295,936  untied 4,361,472  difference 65,536 = V*D = 256*256
Shapes in step 2
TensorShapeMeaning
input_ids(B, T)Integers in 0 to V - 1.
embed_tokens.weight(V, D)One learned row per token.
x(B, T, D)The row for each token.

Checkpoint

  • Both uses of a byte give the same vector.
  • test_weight_tying_shares_storage passes.
Step 03

RMSNorm from scratch

Goal Rescale each token vector to unit root-mean-square, with no mean subtraction and no bias.

Derivation inThe geometry of normalization

RMSNorm is LayerNorm without the centring. It divides each token by its own RMS, then applies a learned gain per channel. It has D parameters and needs no running statistics.

class RMSNorm(nn.Module):
    """y = x / sqrt(mean(x^2) + eps) * weight, computed per token.

    Input and output: (..., hidden_size). Unlike LayerNorm there is no mean subtraction and no bias.
    """

    def __init__(self, hidden_size: int, eps: float = 1e-5) -> None:
        super().__init__()
        self.eps = eps
        self.weight = nn.Parameter(torch.ones(hidden_size))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        input_dtype = x.dtype
        # Square-and-mean in float32: in bf16 the sum of squares loses too many bits.
        x32 = x.float()
        rms_inv = torch.rsqrt(x32.pow(2).mean(dim=-1, keepdim=True) + self.eps)  # (..., 1)
        return self.weight * (x32 * rms_inv).to(input_dtype)
Listing 3The squares and their mean run in float32, even in a bf16 model. Otherwise the sum of squares loses too many bits.

Read forward from the inside out. x32.pow(2).mean(dim=-1, keepdim=True) gives one number per token, the mean square across its channels. keepdim=True leaves a dimension of size 1, so the result broadcasts over all D channels. torch.rsqrt returns one over the square root. Last, self.weight scales each channel by its learned gain.

$ .venv/bin/python c04-llm/scripts/walkthrough.py --step rmsnorm
input rms  102.7954 -> output rms 1.0000
input rms    1.0102 -> output rms 1.0000
input rms    0.0194 -> output rms 0.9869
input rms    0.0010 -> output rms 0.2921
input mean per token 2.936
  RMSNorm keeps the sign of the mean: 0.949
  LayerNorm removes it:               -0.000
max |ours - torch.nn.RMSNorm| = 0.0e+00

The first lines hold a surprise. An input with RMS 0.0194 comes out at 0.9869, and one with RMS 0.001 comes out at 0.2921. The reason is epsilon. The output RMS is r / sqrt(r² + eps), so with eps = 1e-5 the norm stops rescaling once r falls near sqrt(eps), which is 0.0032. Drag the slider to see it.

Input RMS
Output RMS
Shortfall from 1
Figure 2One 32-channel token vector before and after RMSNorm. The input panel rescales itself so you can see its shape at any size. The output axis is fixed. The animation steps through the four inputs measured above. The sliders take over at any time, and 0.02 is the real embedding scale from step 2. The readouts use the formula r / sqrt(r² + eps) on the rounded input, and the notes give the measured values. The 0.001 in the printed line is rounded: inverting the formula on the output 0.2921 gives an input RMS of about 0.00097.

Checkpoint

  • Output RMS is 1 for any input much larger than sqrt(eps).
  • test_rmsnorm_output_has_unit_rms passes.
Step 04

Rotary position embeddings

Goal Make the query-key score depend on the distance between two tokens, and not on where they sit.

Derivation inHow models know where they are

RoPE adds nothing to the token vector. It rotates each pair of channels by an angle proportional to position. Each pair rotates at its own speed. Queries and keys are rotated. Values are not. This is the same module as in Build Attention From Scratch.

class RotaryEmbedding(nn.Module):
    """Precomputes cos/sin tables for positions 0 .. max_seq_len - 1.

    inv_freq: (d/2,)   one rotation speed per pair of channels
    cos, sin: (max_seq_len, d)
    """

    def __init__(self, head_dim: int, max_seq_len: int, theta: float = 10_000.0) -> None:
        super().__init__()
        inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, dtype=torch.float32) / head_dim))
        positions = torch.arange(max_seq_len, dtype=torch.float32)
        # Angles in float32: position * speed gets large, and bf16 would round it badly.
        freqs = torch.outer(positions, inv_freq)  # (S, d/2)
        emb = torch.cat((freqs, freqs), dim=-1)  # (S, d): channel i and channel i + d/2 share an angle
        # Not persistent: a pure function of the config, so it does not belong in a checkpoint.
        self.register_buffer("inv_freq", inv_freq, persistent=False)
        self.register_buffer("cos_cached", emb.cos(), persistent=False)
        self.register_buffer("sin_cached", emb.sin(), persistent=False)

    def forward(self, position_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
        """position_ids: (B, T) absolute positions -> cos, sin: (B, T, d), float32."""
        return self.cos_cached[position_ids], self.sin_cached[position_ids]


def rotate_half(x: torch.Tensor) -> torch.Tensor:
    """(x1, x2) -> (-x2, x1) on the two halves of the last dim: a 90 degree turn of every pair.

    Channel i is paired with channel i + d/2. This pairing is a convention. It must match
    the checkpoint, or trained weights read positions wrongly (see "Break it" in the post).
    """
    x1, x2 = x.chunk(2, dim=-1)
    return torch.cat((-x2, x1), dim=-1)


def rotate(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
    """Rotate x (B, H, T, d) by its positions. cos, sin: (B, T, d), broadcast over heads."""
    cos, sin = cos[:, None].to(x.dtype), sin[:, None].to(x.dtype)
    return x * cos + rotate_half(x) * sin


def apply_rotary(
    q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
    """Rotate q (B, H, T, d) and k (B, H_kv, T, d) with the same tables."""
    return rotate(q, cos, sin), rotate(k, cos, sin)
Listing 4The table is a pure function of the config, so it stays out of the checkpoint. rotate_half fixes which channels form a pair.

Walk through the constructor first. inv_freq holds one speed per channel pair, from 1.0 down to 0.000178 in the tiny preset. torch.outer multiplies every position by every speed, so freqs holds one angle per position and per pair. torch.cat((freqs, freqs), dim=-1) gives channel i and channel i + d/2 the same angle, because they form a pair.

Then rotate applies the usual 2D rotation. For a pair (a, b), x * cos + rotate_half(x) * sin gives (a cos - b sin, b cos + a sin). Rotation keeps the length of the vector, which the output below confirms.

$ .venv/bin/python c04-llm/scripts/walkthrough.py --step rope
inv_freq torch.Size([16]), first three [1.0, 0.5623413324356079, 0.3162277638912201], last 0.000178
cos table torch.Size([256, 32])
wavelength of fastest pair 6.3 tokens, slowest 35,333 tokens
norm before 5.6920, after rotating to position 100 5.6920
score(q at   5, k at   2), offset 3: -5.1072
score(q at 103, k at 100), offset 3: -5.1072
score(q at 205, k at 202), offset 3: -5.1072
score(q at   5, k at   3), offset 2: -4.7229

Read the last four lines. The first three have offset 3 and identical scores, even after the pair moves by 98 positions and then by 200. The fourth has offset 2 and a different score. That is the whole property, measured.

Figure 3Two of the 16 channel pairs in one head, drawn as clocks. Query and key both turn as positions grow, and the angle between them stays fixed while the offset stays fixed. The arrows are illustrative. The scores in the notes are the measured ones above.
Shapes in step 4
TensorShapeMeaning
inv_freq(d/2,)One rotation speed per channel pair.
cos_cached, sin_cached(max_seq_len, d)Tables indexed by absolute position.
cos, sin(B, T, d)The rows for these T positions.

Checkpoint

  • Rotation keeps the vector norm.
  • test_rope_dot_product_depends_only_on_offset passes.
Step 05

Grouped-query attention, naive first

Goal A readable reference, a fast version on PyTorch’s scaled dot-product attention (SDPA), and a test that they agree, with a cache slot ready for step 14.

Derivation inHow attention moves information

Grouped-query attention keeps all H query heads and reduces keys and values to H_kv heads. Several query heads read each key and value head. It sits between multi-head attention (MHA), where every query head has its own keys and values, and multi-query attention (MQA), where all query heads share one. The reshape helpers below are trimmed copies from the attention tutorial.

def split_heads(x: torch.Tensor, num_heads: int) -> torch.Tensor:
    """(B, T, H*d) -> (B, H, T, d). Heads are a reshape of one wide projection, not separate weights."""
    b, t, _ = x.shape
    return x.view(b, t, num_heads, -1).transpose(1, 2)


def merge_heads(x: torch.Tensor) -> torch.Tensor:
    """(B, H, T, d) -> (B, T, H*d). After transpose the memory is out of order, so copy first."""
    b, h, t, d = x.shape
    return x.transpose(1, 2).contiguous().view(b, t, h * d)


def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
    """(B, H_kv, T, d) -> (B, H_kv * n_rep, T, d), so each query head finds its shared k/v head.

    Query head h reads kv head h // n_rep. That is the GQA grouping.
    """
    if n_rep == 1:
        return x
    b, h_kv, t, d = x.shape
    return x[:, :, None].expand(b, h_kv, n_rep, t, d).reshape(b, h_kv * n_rep, t, d)


def causal_mask(nq: int, nk: int | None = None, device: torch.device | str | None = None) -> torch.Tensor:
    """Boolean (nq, nk) mask, True where attention is allowed, aligned to the bottom-right corner.

    The queries are the last nq of nk positions, so query i sits at absolute position
    i + (nk - nq) and may see keys up to that position. With nq == nk this is the usual
    lower triangle. With a cache (nq < nk) the diagonal shifts right.
    """
    nk = nq if nk is None else nk
    q_pos = torch.arange(nq, device=device)[:, None] + (nk - nq)
    k_pos = torch.arange(nk, device=device)[None, :]
    return k_pos <= q_pos


def naive_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, n_rep: int) -> torch.Tensor:
    """Causal grouped-query attention.

    q: (B, H, T_q, d)    k, v: (B, H_kv, T_kv, d)    returns (B, H, T_q, d)
    """
    k, v = repeat_kv(k, n_rep), repeat_kv(v, n_rep)
    scores = q @ k.transpose(-2, -1) / math.sqrt(q.shape[-1])  # (B, H, T_q, T_kv)
    mask = causal_mask(q.shape[2], k.shape[2], q.device)
    scores = scores.masked_fill(~mask, float("-inf"))
    # Softmax in float32 so a bf16 run produces the same probabilities as a float32 run.
    probs = torch.softmax(scores.float(), dim=-1).to(q.dtype)
    return probs @ v
Listing 5The reference implementation. causal_mask takes two lengths because a cache makes queries shorter than keys. The diagonal then shifts right.

Follow one call of naive_attention. repeat_kv inserts a dimension and expands it, which turns (B, H_kv, T, d) into (B, H, T, d). Query head h now lines up with KV head h // n_rep. q @ k.transpose(-2, -1) gives one score per query and per key, and dividing by the square root of d keeps those scores from growing with head width.

masked_fill sets every forbidden pair to minus infinity, so softmax gives it weight 0. Each row of probs then sums to 1, and probs @ v is a weighted average of the values, one per query.

Next we hand the same maths to PyTorch’s fused kernel. There is one trap, and the code comments mark it. is_causal=True builds a triangle aligned to the top-left corner. That is correct only when queries and keys have the same length.

def sdpa_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, n_rep: int) -> torch.Tensor:
    """Causal grouped-query attention via F.scaled_dot_product_attention.

    q: (B, H, T_q, d)    k, v: (B, H_kv, T_kv, d)    returns (B, H, T_q, d)
    """
    q_len, kv_len = q.shape[2], k.shape[2]
    if q_len == kv_len:
        # No cache: the plain lower triangle. is_causal lets the kernel skip masked tiles.
        mask, is_causal = None, True
    elif q_len == 1:
        # One new token attends to everything before it: no mask at all.
        mask, is_causal = None, False
    else:
        # Chunked prefill on top of a cache. is_causal=True would align the triangle to the
        # top-left corner, which is wrong here, so pass the shifted mask explicitly.
        mask, is_causal = causal_mask(q_len, kv_len, q.device), False
    # enable_gqa broadcasts the H_kv heads to H inside the kernel, with no repeat_kv copy.
    return F.scaled_dot_product_attention(
        q, k, v, attn_mask=mask, is_causal=is_causal, enable_gqa=n_rep > 1
    )
Listing 6The three mask cases of real decoding. enable_gqa broadcasts the shared heads inside the kernel, so no copy is made.

The module itself is mostly projections. RoPE tables come in from the model, so they are computed once per call and shared across layers.

class GroupedQueryAttention(nn.Module):
    """hidden_states (B, T, D) -> (B, T, D).

    Inside: q (B, H, T, d)   k, v (B, H_kv, T, d)   cache (B, H_kv, T_past + T, d)
    """

    def __init__(self, config: ModelConfig, layer_idx: int) -> None:
        super().__init__()
        self.layer_idx = layer_idx
        self.num_heads = config.num_heads
        self.num_kv_heads = config.num_kv_heads
        self.head_dim = config.head_dim
        self.n_rep = config.num_kv_groups
        self.backend = config.attn_backend
        d, hd = config.hidden_size, config.head_dim
        # No biases, as in Llama. K and V are smaller than Q: that is the whole point of GQA.
        self.q_proj = nn.Linear(d, self.num_heads * hd, bias=False)
        self.k_proj = nn.Linear(d, self.num_kv_heads * hd, bias=False)
        self.v_proj = nn.Linear(d, self.num_kv_heads * hd, bias=False)
        self.o_proj = nn.Linear(self.num_heads * hd, d, bias=False)

    def forward(
        self,
        hidden_states: torch.Tensor,
        cos: torch.Tensor,
        sin: torch.Tensor,
        kv_cache: KVCache | None = None,
    ) -> torch.Tensor:
        """cos, sin: (B, T, d), the RoPE tables for these T positions (computed once per model call)."""
        q = split_heads(self.q_proj(hidden_states), self.num_heads)  # (B, H, T, d)
        k = split_heads(self.k_proj(hidden_states), self.num_kv_heads)  # (B, H_kv, T, d)
        v = split_heads(self.v_proj(hidden_states), self.num_kv_heads)  # (B, H_kv, T, d)

        q, k = apply_rotary(q, k, cos, sin)  # keys are cached already rotated
        if kv_cache is not None:
            k, v = kv_cache.update(k, v, self.layer_idx)  # (B, H_kv, T_past + T, d)

        out = BACKENDS[self.backend](q, k, v, self.n_rep)  # (B, H, T, d)
        return self.o_proj(merge_heads(out))
Listing 7Keys are cached after rotation, so a cached key never needs to be rotated again.
$ .venv/bin/python c04-llm/scripts/walkthrough.py --step attention
q_proj torch.Size([256, 256])  k_proj torch.Size([64, 256])  v_proj torch.Size([64, 256])
q torch.Size([1, 8, 11, 32])
k torch.Size([1, 2, 11, 32])
v torch.Size([1, 2, 11, 32])
repeat_kv(k, 4) torch.Size([1, 8, 11, 32])
causal_mask(4).int()      [[1, 0, 0, 0], [1, 1, 0, 0], [1, 1, 1, 0], [1, 1, 1, 1]]
causal_mask(2, 5).int()   [[1, 1, 1, 1, 0], [1, 1, 1, 1, 1]]
output torch.Size([1, 8, 11, 32]), max |naive - sdpa| = 7.45e-08

Figure 4How 8 query heads share key and value heads as H_kv drops from 8 to 1. Query head h reads KV head h // n_rep. Cache sizes are for the tiny preset in float32.
Shapes in step 5, tiny preset, B = 1, T = 11
TensorShapeExample
q(B, H, T, d)(1, 8, 11, 32)
k, v(B, H_kv, T, d)(1, 2, 11, 32)
repeat_kv(k, 4)(B, H, T, d)(1, 8, 11, 32)
scores(B, H, T, T)(1, 8, 11, 11)
attention output(B, H, T, d)(1, 8, 11, 32)
after o_proj(B, T, D)(1, 11, 256)

How much does the fused kernel save inside the full model? We time forward plus backward, per training step.

$ .venv/bin/python c04-llm/benchmarks/bench_attention.py --device cpu
device=cpu batch=8  (tiny preset, forward + backward per step)
   seq   naive ms    sdpa ms  speed-up
   128      141.7      116.7     1.21x
   256      276.0      232.1     1.19x
   512     1361.5      441.1     3.09x
  1024     4644.9     1097.9     4.23x

Which kernel did SDPA use here? On this PyTorch build, the CPU path dispatches to aten::_scaled_dot_product_flash_attention_for_cpu, a flash-style CPU kernel that runs in float32. So the CPU numbers above already use a fused kernel.

A probe of the PyTorch backends is saved in results/sdpa_cpu_backend_probe.txt. The CUDA FlashAttention kernel is a different one. It needs a GPU. As far as we could tell, it runs only in bf16 and half precision.

We ran the GPU commands on one NVIDIA H100 80GB HBM3, with PyTorch 2.15.0 and CUDA 13.2. The five GPU tests pass. Four of them force the FlashAttention backend, so PyTorch raises an error instead of falling back. Three compare it with the naive path for MHA, GQA and MQA, and one checks a single cached decode step against a full forward pass. The fifth is a float32 test of chunked prefill on a cache, with the shifted mask.

$ .venv/bin/python -m pytest c04-llm -m gpu
5 passed, 76 deselected in 1.81s
$ .venv/bin/python c04-llm/benchmarks/bench_attention.py --device cuda --dtype bf16
device=cuda (NVIDIA H100 80GB HBM3) dtype=bf16 batch=8  (tiny preset, forward + backward per step)
   seq   naive ms    sdpa ms  speed-up  naive MiB   sdpa MiB
   128       25.1       20.3     1.23x        163        117
   256       26.1       20.0     1.30x        342        184
   512       27.3       20.1     1.36x       1001        323
  1024       27.1       20.0     1.36x       3460        594

On the GPU the clear result is memory, not time. At 1024 tokens the naive path peaks at 3,460 MiB and SDPA at 594 MiB, almost 6 times less. The naive path stores a (T, T) score matrix per head. Its peak grows about 3.5 times from 512 to 1024 tokens, and the SDPA peak about 1.8 times. We did not record which SDPA backend this benchmark used, so we do not name a kernel.

The naive path also takes its softmax in float32, with torch.softmax(scores.float(), dim=-1). So the bf16 naive run holds a float32 score matrix. That is why its 1024-token peak (3,460 MiB) is higher than the float32 naive run (3,242 MiB). It also means the bf16 time comparison includes that upcast.

The times say little. SDPA takes 20.0 to 20.3 ms at every length, and the naive path 25.1 to 27.3 ms. That is a speed-up of about 1.2x to 1.4x, in single runs. The flat shape is consistent with a step limited by kernel launches, because a model this small cannot keep an H100 busy. We did not prove that. The speed-up tells you little about large models.

In float32 the same run gives about 1.2x to 1.6x, again in single runs. The naive times there are 21.9, 23.9, 23.0 and 27.8 ms, which are not monotone, so read that range as noise and not as a trend. The 1024-token peak is 3,242 MiB for naive and 1,045 MiB for SDPA. The run is saved in results/bench_attention_gpu_float32.txt.

A first run on a heavily loaded host gave SDPA speed-ups from 0.88x to 1.51x. We discarded it and re-ran. Treat all GPU timings here as single runs on a shared machine. This benchmark leaves PyTorch’s default backend choice in place (see the note in Step 14). A 20 ms forward and backward step over 6 layers cannot include a cost of about 10 ms per attention call, so that slow call does not seem to affect it.

Checkpoint

  • Naive and SDPA differ by about 1e-7.
  • test_naive_and_sdpa_agree and test_same_output_as_attnzoo pass. The second one checks tinyllm against the C3 library, including its cache protocol.
Step 06

SwiGLU, the gated feed-forward

Goal Implement down(silu(x W_gate) * (x W_up)) and understand why F is not 4D.

Background inWhy neural networks need nonlinearity

Attention mixes across positions. The MLP, a multilayer perceptron, works inside each position. SwiGLU makes two wide copies of the token. One copy, after silu, becomes a gate that scales the other copy channel by channel. A third matrix projects back down.

class SwiGLU(nn.Module):
    """(B, T, D) -> (B, T, F) twice -> gate -> (B, T, D).

    Three matrices instead of the classic two. To keep the parameter count of a 4*D MLP,
    Llama-style models pick F close to (2/3) * 4 * D, rounded to a hardware-friendly multiple.
    """

    def __init__(self, hidden_size: int, intermediate_size: int) -> None:
        super().__init__()
        self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
        self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
        self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        # The gate decides, per channel and per token, how much of the "up" value passes.
        return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
Listing 8Three matrices, no biases. The gate multiplication is the only nonlinearity in the block other than the attention softmax.
$ .venv/bin/python c04-llm/scripts/walkthrough.py --step swiglu
x torch.Size([1, 11, 256]) -> gate torch.Size([1, 11, 704]), up torch.Size([1, 11, 704]) -> product torch.Size([1, 11, 704]) -> out torch.Size([1, 11, 256])
gate range [-0.278, 1.769]; silu never goes below -0.278
SwiGLU params: 3*D*F = 540,672
classic MLP with F = 4D: 2*D*4D = 524,288
F that matches it, 8D/3 = 682.7, rounded up to a multiple of 64 = 704
Shapes in step 6, tiny preset, B = 1, T = 11
TensorShapeExample
x(B, T, D)(1, 11, 256)
gate_proj(x)(B, T, F)(1, 11, 704)
up_proj(x)(B, T, F)(1, 11, 704)
silu(gate) * up(B, T, F)(1, 11, 704)
down_proj(product)(B, T, D)(1, 11, 256)

A classic MLP with F = 4D has 8D² weights. SwiGLU with width F has 3DF. They match at F = 8D/3. That is the origin of the odd-looking numbers in real configs. SmolLM2-135M uses exactly 8D/3: 1536 for D = 576. Llama 3 8B uses more, 14,336 for D = 4096, which is a ratio of 3.5.

Checkpoint

  • Output shape equals input shape. Gate values never fall below -0.278.
  • test_swiglu_shapes_and_formula passes.
Step 07

The decoder block

Goal Assemble two pre-norm residual branches into a block whose output shape equals its input shape.

Each branch normalises its own input, computes, and adds the result to the stream. The stream itself is never normalised inside a block. That gives gradients a clean path from the loss to the first layer.

class DecoderBlock(nn.Module):
    def __init__(self, config: ModelConfig, layer_idx: int) -> None:
        super().__init__()
        self.input_layernorm = RMSNorm(config.hidden_size, config.rms_norm_eps)
        self.self_attn = GroupedQueryAttention(config, layer_idx)
        self.post_attention_layernorm = RMSNorm(config.hidden_size, config.rms_norm_eps)
        if config.num_experts:
            self.mlp: nn.Module = MoE(
                config.hidden_size, config.intermediate_size, config.num_experts,
                config.num_experts_per_tok, config.expert_capacity_factor,
            )
        else:
            self.mlp = SwiGLU(config.hidden_size, config.intermediate_size)

    def forward(
        self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, kv_cache: KVCache | None = None
    ) -> tuple[torch.Tensor, torch.Tensor | None]:
        """x: (B, T, D) -> (B, T, D), plus the MoE auxiliary loss (None for a dense block)."""
        # Pre-norm: the residual stream x itself is never normalised, only the branch inputs.
        x = x + self.self_attn(self.input_layernorm(x), cos, sin, kv_cache)
        h = self.mlp(self.post_attention_layernorm(x))
        aux = None
        if isinstance(h, tuple):
            h, aux = h
        return x + h, aux
Listing 9Two lines do the architecture. The rest is the optional MoE branch from step 16.
$ .venv/bin/python c04-llm/scripts/walkthrough.py --step block
input              torch.Size([1, 11, 256]) rms=1.015
attention branch   torch.Size([1, 11, 256]) rms=0.016
mlp branch         torch.Size([1, 11, 256]) rms=0.008
output             torch.Size([1, 11, 256]) rms=1.015
block(x) matches by hand: True; aux loss for a dense block: None

A fresh block is close to the identity function. With a unit-scale input, the attention branch has RMS 0.016 and the MLP branch has RMS 0.008. Training gradually grows these branches.

Shapes in step 7, tiny preset, B = 1, T = 11
TensorShapeExample
x, input(B, T, D)(1, 11, 256)
cos, sin(B, T, d)(1, 11, 32)
attention branch(B, T, D)(1, 11, 256)
mlp branch(B, T, D)(1, 11, 256)
x, output(B, T, D)(1, 11, 256)

Checkpoint

  • block(x) matches the hand-computed sum exactly.
  • test_gradients_reach_every_parameter passes.
Step 08

The decoder stack and LM head

Goal Repeat L blocks, add a final norm, and score every token in the vocabulary at every position.

The stack is a loop. Two details matter. Positions must start after the cached tokens, which is the job of past. And the final norm is needed because the stream has never been normalised.

    def forward(
        self,
        input_ids: torch.Tensor,
        labels: torch.Tensor | None = None,
        past_key_values: KVCache | None = None,
        use_cache: bool = False,
    ) -> CausalLMOutput:
        """input_ids: (B, T) token ids. With a cache, only the new tokens are passed in."""
        b, t = input_ids.shape
        if use_cache and past_key_values is None:
            past_key_values = KVCache()
        past = past_key_values.get_seq_length() if past_key_values is not None else 0
        if past + t > self.config.max_seq_len:
            raise ValueError(f"sequence length {past + t} exceeds max_seq_len={self.config.max_seq_len}")

        x = self.embed_tokens(input_ids)  # (B, T, D)
        # New tokens sit after the cached ones, so their positions start at `past`.
        position_ids = torch.arange(past, past + t, device=input_ids.device).expand(b, t)
        cos, sin = self.rotary(position_ids)  # (B, T, head_dim) each, shared by all layers

        aux_total = None
        for layer in self.layers:
            x, aux = layer(x, cos, sin, past_key_values)
            if aux is not None:
                aux_total = aux if aux_total is None else aux_total + aux

        logits = self.lm_head(self.norm(x))  # (B, T, V)

        loss = None
        if labels is not None:
            loss = causal_lm_loss(logits, labels)
            if aux_total is not None:
                loss = loss + self.config.router_aux_loss_coef * aux_total
        return CausalLMOutput(logits=logits, loss=loss, past_key_values=past_key_values, aux_loss=aux_total)
Listing 10The forward pass, and the public contract: it returns an object with .logits, .loss and .past_key_values.

Read it top to bottom. past is the number of tokens already in the cache, and it is 0 without one. position_ids counts from past, so a new token gets its real position. The RoPE tables are looked up once and passed to every layer. Each layer returns the new stream and an optional auxiliary loss, which is None for a dense block. After the loop, self.norm and self.lm_head turn the stream into one score per vocabulary entry.

$ .venv/bin/python c04-llm/scripts/walkthrough.py --step stack
logits torch.Size([1, 11, 256])  rms=0.346
next-token probabilities torch.Size([256]), sum=1.0000, largest=0.0242 (uniform would be 0.0039)
changing tokens 8.. leaves logits 0..7 unchanged: True

The last output line is a causality check on the whole model. Changing tokens at position 8 and later leaves logits 0 to 7 bitwise unchanged.

Shapes through the whole model
TensorShapeTiny, B = 1, T = 11
input_ids(B, T)(1, 11)
x, every block(B, T, D)(1, 11, 256)
cos, sin(B, T, d)(1, 11, 32)
cache, per layer(B, H_kv, T, d), twice(1, 2, 11, 32)
logits(B, T, V)(1, 11, 256)

Checkpoint

  • Largest next-token probability is near uniform on random weights: 0.024 against 0.0039 for exactly uniform.
  • test_causality_future_tokens_do_not_change_past_logits passes.
Step 09

The shifted cross-entropy loss

Goal Score each position against the token after it, and let callers mask positions out.

The model predicts the next token, so targets are the inputs moved left by one. The last position has no target. The first token is never predicted.

def causal_lm_loss(logits: torch.Tensor, labels: torch.Tensor, ignore_index: int = IGNORE_INDEX) -> torch.Tensor:
    """Mean cross-entropy over the positions that have a real next token.

    logits: (B, T, V)   labels: (B, T), usually the input ids themselves.
    The shift happens here, as in Hugging Face: logits[:, :-1] are scored against labels[:, 1:].
    Positions whose label is ignore_index (padding, prompt tokens) do not count.
    """
    shift_logits = logits[:, :-1, :].float()  # (B, T-1, V); float32 so log-softmax is exact enough
    shift_labels = labels[:, 1:]  # (B, T-1)
    return F.cross_entropy(
        shift_logits.reshape(-1, shift_logits.shape[-1]),
        shift_labels.reshape(-1),
        ignore_index=ignore_index,
    )
Listing 11Hugging Face shifts inside the model too, so labels = input_ids is correct for both. The value -100 is the convention for “do not score”.
$ .venv/bin/python c04-llm/scripts/walkthrough.py --step loss
input  ['T', 'h', 'e', ' ', 'c', 'a']
target ['h', 'e', ' ', 'c', 'a', 't']
by hand: mean -log p(next) = 5.6640
causal_lm_loss             = 5.6640
ln V                       = 5.5452
with labels[:4] = -100, only 3 positions count: 5.6883
Shapes in step 9
TensorShapeMeaning
logits(B, T, V)One score per token, per position.
labels(B, T)Usually the input ids.
shift_logits(B, T-1, V)Drops the last position.
shift_labels(B, T-1)Drops the first token.
flattened(B*(T-1), V) and (B*(T-1),)The form cross_entropy expects.
lossscalarMean over positions not marked -100.

Checkpoint

  • The hand computation and causal_lm_loss agree to four decimals.
  • test_loss_is_shifted and test_loss_ignores_masked_labels pass.
Step 10

Initialisation

Goal Start near the uniform loss, and keep the residual stream stable at any depth.

Derivation inWhy transformers do not explode

Two rules cover it. Every weight starts small, with standard deviation 0.02. The two projections that write onto the residual stream are scaled down further by the square root of 2L, because each block adds two random contributions and their variance accumulates.

def init_weights(model: nn.Module, config: ModelConfig) -> None:
    """GPT-2 / Llama-style init.

    Every Linear and Embedding weight ~ N(0, std) with std = initializer_range (0.02).
    o_proj and down_proj use std / sqrt(2 * num_layers): each block adds two branches to the
    residual stream, so 2L random contributions accumulate. Scaling each by 1/sqrt(2L) keeps
    the variance of the final residual stream about the same at any depth.
    RMSNorm gains start at 1, so every norm begins as a pure rescale.
    """
    std = config.initializer_range
    residual_std = std / math.sqrt(2 * config.num_layers)
    for name, module in model.named_modules():
        if isinstance(module, nn.Linear):
            is_residual = name.split(".")[-1] in RESIDUAL_PROJECTIONS
            nn.init.normal_(module.weight, mean=0.0, std=residual_std if is_residual else 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=std)
        elif isinstance(module, RMSNorm):
            nn.init.ones_(module.weight)
Listing 12Scaling o_proj and down_proj by depth follows GPT-2. Norm gains start at 1.

A correct model should start near ln V, the loss of a uniform guess. That number is your first sanity check on any new model, and it costs one forward pass. Here we also test what happens without the depth scaling, in a 48-layer model.

$ .venv/bin/python c04-llm/scripts/break_it.py --case init
[init] initial loss on random tokens (V = 256, ln V = 5.545)
  std=0.02  loss    5.611
  std=0.2   loss   10.418
  std=1.0   loss   46.022
[init] residual-stream RMS at the last layer of a 48-layer model, std 0.02, embeddings RMS 0.02
  std/sqrt(2L) on residual projections: layer 1 0.020, layer 12 0.026, layer 48 0.059
  same std everywhere            : layer 1 0.040, layer 12 0.333, layer 48 0.690

The first block shows the sanity check at work. With a standard deviation of 0.02, the loss starts at 5.611, close to ln 256. At 0.2 it starts at 10.418, and at 1.0 it starts at 46.022. A bad init is visible before the first training step.

Checkpoint

  • Initial loss on the tiny model is near ln 256 = 5.545.
  • test_initial_loss_is_near_uniform passes.
Step 11

Derive the parameter count, then verify it

Goal Write the size of every component as a formula, and check it against real modules and published model sizes.

If you can write the parameter count by hand, you understand the architecture. Every term comes from a matrix we already built.

def count_parameters(c: ModelConfig) -> dict[str, int]:
    """Closed-form parameter count, split by component.

    With D = hidden_size, F = intermediate_size, V = vocab_size, L = num_layers,
    H = num_heads, H_kv = num_kv_heads, d = head_dim:
      embeddings  V*D
      attention   L * (D*H*d  [q]  + 2*D*H_kv*d  [k, v]  + H*d*D  [o])
      mlp         L * 3*D*F, or L * (E * 3*D*F + D*E) with E experts and a router
      norms       L * 2*D + D  (two per block, one final)
      lm_head     V*D if untied, 0 if tied to the embeddings
    """
    d_model, d = c.hidden_size, c.head_dim
    attention = c.num_layers * (d_model * c.num_heads * d + 2 * d_model * c.num_kv_heads * d + c.num_heads * d * d_model)
    ffn = 3 * d_model * c.intermediate_size
    if c.num_experts:
        mlp = c.num_layers * (c.num_experts * ffn + d_model * c.num_experts)
    else:
        mlp = c.num_layers * ffn
    counts = {
        "embeddings": c.vocab_size * d_model,
        "attention": attention,
        "mlp": mlp,
        "norms": c.num_layers * 2 * d_model + d_model,
        "lm_head": 0 if c.tie_word_embeddings else c.vocab_size * d_model,
    }
    counts["total"] = sum(counts.values())
    return counts
Listing 13The closed form. RMSNorm has one gain per channel, and attention has four projections.

The check builds each model on PyTorch’s meta device, which records shapes and allocates no memory. So Llama 3 8B fits on a laptop for counting.

$ .venv/bin/python c04-llm/scripts/param_count.py
component               tiny    smollm2-135m       llama3-8b
embeddings            65,536          28.31M         525.34M
attention              0.98M          26.54M          1.342B
mlp                    3.24M          79.63M          5.637B
norms                  3,328          35,136           0.27M
lm_head                    0               0         525.34M
total                  4.30M         134.52M          8.030B

verify: formula == sum(p.numel()) of the built module
  tiny           formula=     4,295,936  module=     4,295,936  equal=True
  smollm2-135m   formula=   134,515,008  module=   134,515,008  equal=True
  llama3-8b      formula= 8,030,261,248  module= 8,030,261,248  equal=True

KV cache per sequence of 4096 tokens, bf16 (2 bytes per value)
  MHA (32 kv heads)    cache= 2.00 GiB  attention params=2.147B
  GQA (8 kv heads)     cache= 0.50 GiB  attention params=1.342B
  MQA (1 kv head)      cache= 0.06 GiB  attention params=1.107B

Formula and module agree on all three. The totals also agree with outside sources. SmolLM2-135M has 134,515,008 parameters when loaded from the Hub in step 12. Llama 3 8B’s published size is 8.03B, and our formula gives 8,030,261,248. Try the formula yourself. A preset button fills in a real model, and a bad combination raises the same error as ModelConfig.

Total parameters
Head width d
KV cache, 4096 tokens, bf16
Figure 5Parameter calculator, using the same formula as count_parameters. With the Llama 3 8B preset, move H_kv between 1 and 32 and watch the cache move by a factor of 32 while the total grows by about 13%, from 7.80B parameters at 1 head to 8.84B at 32.

Checkpoint

  • All three totals print equal=True.
  • test_parameter_count_formula_matches_model and test_parameter_count_of_real_models pass.
Step 12

Prove it against the trusted implementation

Goal Give our weights to Hugging Face’s LlamaForCausalLM and get the same logits. Then load real pretrained weights into our model.

So far each module passed its own small test. That cannot catch a wrong design choice that we made consistently, such as the RoPE pairing. A second, independent implementation can. Because we named our attributes after Hugging Face’s, the conversion is a config translation and a key prefix.

def to_hf_state_dict(model: TinyLLM) -> dict[str, torch.Tensor]:
    """Rename keys: 'layers.0.self_attn.q_proj.weight' -> 'model.layers.0.self_attn.q_proj.weight'."""
    out = {}
    for name, tensor in model.state_dict().items():
        out[name if name.startswith("lm_head.") else f"model.{name}"] = tensor
    return out


def to_hf(model: TinyLLM):
    """Build a LlamaForCausalLM carrying exactly the same weights."""
    from transformers import LlamaForCausalLM

    hf = LlamaForCausalLM(to_hf_config(model.config))
    missing, unexpected = hf.load_state_dict(to_hf_state_dict(model), strict=False)
    allowed = {"lm_head.weight"} if model.config.tie_word_embeddings else set()
    if set(missing) - allowed or unexpected:
        raise RuntimeError(f"HF conversion mismatch: missing={missing}, unexpected={unexpected}")
    return hf.to(next(model.parameters()).dtype).eval()
Listing 14The weight conversion. It fails loudly on any unexpected or missing key, so a silently random layer cannot slip through.
@pytest.mark.parametrize("overrides", [{}, {"tie_word_embeddings": False}, {"num_kv_heads": 1}, {"rope_theta": 500_000.0}])
def test_logits_and_loss_match_llama(overrides):
    model = small_model(**overrides)
    hf = to_hf(model)
    ids = random_ids(2, 33)
    ours = model(ids, labels=ids)
    with torch.no_grad():
        theirs = hf(ids, labels=ids)
    torch.testing.assert_close(ours.logits, theirs.logits, atol=1e-5, rtol=1e-5)
    torch.testing.assert_close(ours.loss, theirs.loss, atol=1e-5, rtol=1e-5)
Listing 15The strongest test in the folder. It runs for tied and untied heads, for MQA, and for a different RoPE theta.
$ .venv/bin/python c04-llm/scripts/compare_hf.py --pretrained HuggingFaceTB/SmolLM2-135M
random tiny model (4.3M params), float32, CPU
  max |logit diff|    0.000e+00
  loss ours / HF      5.581258 / 5.581259
  naive backend diff  7.153e-07
  64 greedy tokens identical: True

HuggingFaceTB/SmolLM2-135M loaded into TinyLLM: 134,515,008 params
  max |logit diff|    0.000e+00  (logit scale ~24.9)
  next-token top-5:   ' the' 0.262, ' Paris' 0.094, ' located' 0.073, ' called' 0.044, ' a' 0.039
  greedy, ours:       'The capital of France is the capital of the country.\n\nThe capital of France is the capital of the country.\n\nThe capital of'
  identical to HF:    True

The logit difference is exactly zero, in both directions. A real pretrained model runs through code we wrote today, and greedy decoding matches generate() token for token. The model itself is a small one, which shows in its answer.

Checkpoint

  • Random tiny model and SmolLM2-135M both match within tolerance.
  • test_logits_and_loss_match_llama passes. test_smollm2_135m_logits_match passes with -m network.
Step 13

Generation: greedy, temperature, top-k, top-p

Goal Turn one row of logits into one token, with each filter as a small pure function.

Derivation inChoosing the next token

Generation is a loop around one decision. Each filter takes logits and returns logits, so they compose, and each can be tested alone.

def apply_top_k(logits: torch.Tensor, k: int) -> torch.Tensor:
    """Keep the k largest logits per row, set the rest to -inf. logits: (B, V)."""
    k = min(k, logits.shape[-1])
    kth = torch.topk(logits, k, dim=-1).values[..., -1:]  # (B, 1): the k-th largest value
    return logits.masked_fill(logits < kth, float("-inf"))


def apply_top_p(logits: torch.Tensor, p: float) -> torch.Tensor:
    """Nucleus filter: keep the smallest set of tokens whose probability sums to at least p.

    logits: (B, V). The most likely token is always kept, so the set is never empty.
    """
    sorted_logits, sorted_idx = torch.sort(logits, dim=-1, descending=True)
    probs = torch.softmax(sorted_logits, dim=-1)
    # Probability mass strictly before each token. A token is dropped once that mass already reaches p.
    mass_before = torch.cumsum(probs, dim=-1) - probs
    sorted_logits = sorted_logits.masked_fill(mass_before >= p, float("-inf"))
    return torch.full_like(logits, float("-inf")).scatter(-1, sorted_idx, sorted_logits)


def sample_next_token(
    logits: torch.Tensor,
    temperature: float = 1.0,
    top_k: int | None = None,
    top_p: float | None = None,
    generator: torch.Generator | None = None,
) -> torch.Tensor:
    """logits: (B, V) for the last position -> next token ids (B, 1).

    temperature == 0 means greedy decoding. Otherwise the filters run in the order Hugging Face
    uses: temperature, then top-k, then top-p, then a draw from the renormalised distribution.
    """
    if temperature == 0.0:
        return logits.argmax(dim=-1, keepdim=True)
    logits = apply_temperature(logits.float(), temperature)
    if top_k is not None:
        logits = apply_top_k(logits, top_k)
    if top_p is not None:
        logits = apply_top_p(logits, top_p)
    probs = torch.softmax(logits, dim=-1)
    return torch.multinomial(probs, num_samples=1, generator=generator)
Listing 16Filters set logits to minus infinity, so softmax gives them probability 0. The - probs term in top-p keeps the token that crosses the threshold.

Take the filters in order. apply_top_k finds the k-th largest value in each row and blanks everything below it. apply_top_p sorts the row, computes the probability mass before each token, and blanks a token once that mass already reaches p. The final scatter puts the survivors back in their original positions. sample_next_token then draws one id per row from what remains. A temperature of 0 skips the draw and takes the largest logit, which is greedy decoding.

Run them on the model we train in step 15. Below is the real next-byte distribution after the prompt ROMEO:\nI will . Move the sliders to see what each filter does to it. The filters run in the same order as the code.

Tokens kept
Top probability
Entropy
Figure 6All 256 real logits from the trained tiny model after the prompt above, saved in results/sampling_logits.json. The 14 most likely bytes are drawn. The readouts use all 256.
$ .venv/bin/python c04-llm/scripts/walkthrough.py --step sampling
prompt 'ROMEO:\nI will '; top bytes for the next token
  'b' 0.2321, 'n' 0.1078, 's' 0.0766, 'p' 0.0601, 't' 0.0598, 'f' 0.0492, 'c' 0.0482, 'm' 0.0474, 'd' 0.0474, 'a' 0.0470, 'r' 0.0447, 'g' 0.0344
  mass outside these 12: 0.1452
top_k=40  keeps 40 tokens
top_k=5   keeps 5 tokens
top_p=0.95 keeps 18 tokens
top_p=0.5  keeps 5 tokens
temperature 0.5: top prob 0.565, entropy 1.71 nats
temperature 1.0: top prob 0.232, entropy 2.73 nats
temperature 2.0: top prob 0.106, entropy 3.27 nats
Shapes in step 13
TensorShapeMeaning
logits[:, -1, :](B, V)Scores for the next token only.
after each filter(B, V)Same shape, with blanked entries at minus infinity.
probs(B, V)Each row sums to 1.
next_token(B, 1)One id per row.
ids(B, T + 1)The sequence after torch.cat.

Here is what each setting does to the text, same model and seed.

$ .venv/bin/python c04-llm/scripts/generate.py --compare --max-new-tokens 120
[greedy]
ROMEO:
The sea that we will be so so sorrow.

GLOUCESTER:
The gods be so seen to see the sea that will
I see the sea that will 

[temperature 0.5]
ROMEO:
And therefore weep but to thy son I should die.

JULIET:
I do beseech your grace to thee and my meaning.

Nurse:
God kee

[temperature 1.0]
ROMEO:
And wilt thou what befalled makes his speech
And seld him cuw'd up: by him:
Nothing there: it is, I say my six else
You 

[temperature 1.5]
ROMEO:
Joy! alGo
UsIA:
I would I think your loss
And gwarel, heaven 'twas spoken to me,
And draw not, we should an you the plea

[temperature 1.0, top_k 5]
ROMEO:
And wilt thou go, while he will not be seldom.

RICHARD:
I do beg in a son of those that were in,
When said we are, my l

[temperature 1.0, top_p 0.5]
ROMEO:
And with the strong that he hath spoke to see
The counterfeit of the people's face, that we have
To see the wind of my b

Checkpoint

  • Same seed gives the same output, through both generation paths.
  • test_top_p_keeps_smallest_nucleus and test_top_k_keeps_k_largest pass.
Step 14

Cached generation: same tokens, far less work

Goal Keep past keys and values, prove the output does not change, and measure the saving.

Theory inThe mechanics of LLM inference

Start naive. To get one new token, run the whole sequence again and keep the last row of logits. This is correct and very wasteful, because past tokens do not change. Their keys and values do not change either. So we store them and pass only the new token.

class KVCache:
    """Dynamic cache. Each entry is (B, H_kv, T, d) and grows by torch.cat along T.

    Keys are stored after RoPE, so a cached key never needs to be rotated again.
    Storing H_kv heads (not H) is where GQA saves memory.
    """

    def __init__(self) -> None:
        self.keys: list[torch.Tensor] = []
        self.values: list[torch.Tensor] = []

    def get_seq_length(self, layer_idx: int = 0) -> int:
        return self.keys[layer_idx].shape[2] if layer_idx < len(self.keys) else 0

    def update(self, k: torch.Tensor, v: torch.Tensor, layer_idx: int = 0) -> tuple[torch.Tensor, torch.Tensor]:
        """Append k, v (B, H_kv, T_new, d); return (B, H_kv, T_past + T_new, d)."""
        if layer_idx == len(self.keys):  # first call for this layer: prefill
            self.keys.append(k)
            self.values.append(v)
        else:  # decode: append along time
            self.keys[layer_idx] = torch.cat((self.keys[layer_idx], k), dim=2)
            self.values[layer_idx] = torch.cat((self.values[layer_idx], v), dim=2)
        return self.keys[layer_idx], self.values[layer_idx]
Listing 17The cache, with the same interface as the C3 library and Hugging Face’s DynamicCache. It grows by concatenation, which copies on every step and is simple enough for us to read.
    ids = input_ids
    cache = None
    finished = torch.zeros(ids.shape[0], dtype=torch.bool, device=ids.device)
    for _ in range(max_new_tokens):
        if not use_cache:
            logits = model(ids).logits  # (B, T_so_far, V), all recomputed
        elif cache is None:
            out = model(ids, use_cache=True)  # prefill: the whole prompt, fills the cache
            logits, cache = out.logits, out.past_key_values
        else:
            logits = model(ids[:, -1:], past_key_values=cache).logits  # decode: (B, 1, V)

        next_token = sample_next_token(logits[:, -1, :], temperature, top_k, top_p, generator)  # (B, 1)
        if eos_token_id is not None:
            # Rows that already ended keep emitting EOS, so the batch stays rectangular.
            next_token = torch.where(finished[:, None], torch.full_like(next_token, eos_token_id), next_token)
            finished |= next_token[:, 0] == eos_token_id
        ids = torch.cat((ids, next_token), dim=1)
        if eos_token_id is not None and bool(finished.all()):
            break
    model.train(was_training)
    return ids
Listing 18Both paths in one loop. Prefill runs the prompt. Decode feeds one token and reuses the cache.

The decode branch is the whole optimisation. ids[:, -1:] passes one token. TinyLLM.forward reads past from the cache, so that token gets its true position. Inside attention, kv_cache.update appends its key and value, and sdpa_attention takes the q_len == 1 branch, because one new token may see everything before it and needs no mask.

Figure 7Blue tokens go through the model at this step. Gray tokens are not recomputed. The violet strip is the key tensor of one layer, and it grows by one cell per token. The counters show the total tokens processed by each path.
Shapes in one decode step of step 14, one layer
TensorShapeMeaning
ids[:, -1:](B, 1)The one new token.
q(B, H, 1, d)One query per head.
k, v from this token(B, H_kv, 1, d)The new cache entries.
k, v after update(B, H_kv, T_past + 1, d)Everything so far, as stored.
attention output(B, H, 1, d)One row per head.
logits(B, 1, V)Scores for the next token.

Now measure. The benchmark times each decode step separately.

$ .venv/bin/python c04-llm/benchmarks/bench_generation.py --device cpu
preset=tiny params=4,295,936 device=cpu batch=1 prompt=16 new=496
  cache=off  total    8.78s      56.5 tok/s
  cache=on   total    1.81s     274.1 tok/s

  per-step latency (ms) at sequence length T
       T   no cache      cache
      17       5.97       4.43
      48       8.55       4.31
      80       8.55       4.36
     144      13.63       4.25
     272      17.01       3.12
     511      25.99       3.43

  speed-up from the cache: 4.9x
Figure 8Measured decode latency per step, tiny preset with random weights, on an AMD EPYC 7R13 CPU with 8 threads. Each point is the median of 5 neighbouring steps. Hover for values. The table above holds the same numbers.
$ .venv/bin/python c04-llm/benchmarks/bench_generation.py --device cpu \
    --preset smollm2-135m --new-tokens 128
preset=smollm2-135m params=134,515,008 device=cpu batch=1 prompt=16 new=128
  cache=off  total   16.20s       7.9 tok/s
  cache=on   total    7.30s      17.5 tok/s

  per-step latency (ms) at sequence length T
       T   no cache      cache
      17      65.27      56.90
      48      90.31      58.13
      80     124.16      58.09
     143     169.42      56.90

  speed-up from the cache: 2.2x
$ .venv/bin/python c04-llm/benchmarks/bench_generation.py --device cuda --dtype bf16
preset=tiny params=4,295,936 device=cuda (NVIDIA H100 80GB HBM3) dtype=bf16 cudnn_sdp=off batch=1 prompt=16 new=496
  cache=off  total    2.81s     176.3 tok/s
  cache=on   total    2.51s     197.4 tok/s

  per-step latency (ms) at sequence length T
       T   no cache      cache
      17       5.39       5.00
      48       5.82       5.06
      80       5.46       5.11
     144       5.55       5.11
     272       5.57       4.95
     511       5.49       4.93

  speed-up from the cache: 1.1x

Checkpoint

  • Cached logits match full-forward logits within 1e-5.
  • test_token_by_token_with_cache_equals_full_forward, test_chunked_prefill_equals_full_forward and test_cached_generation_matches_uncached_greedy pass.
Step 15

A quick training run, then save and load

Goal Show that the architecture learns, with loss going down and samples improving, and that a checkpoint round-trips exactly.

Theory inHow LLMs are pretrained

This is a sanity check and not a training recipe. It has no packing, no mixed precision and no resume. Those belong to the next tutorial. We train the tiny preset on Tiny Shakespeare, about 1.1 MB of text, one byte per token.

$ .venv/bin/python c04-llm/scripts/train_sanity.py --device cpu
device=cpu  params=4,295,936  train bytes=1,003,854  val bytes=111,540
step     0  val 5.578  (uniform guess = ln 256 = 5.545)
sample before training: 'ROMEO::�y*37A����hh\x1c\x1c^� �\x1bk�%�ċ�����   \x1aNNj׳���\x1e\x1e[\x0eBB��vv�\x1cggg<\x01'
step   200  train 1.603  val 1.767   132.9s  12,327 tok/s
step   400  train 1.411  val 1.610   263.6s  12,432 tok/s
step   600  train 1.227  val 1.532   401.8s  12,234 tok/s
step   800  train 1.152  val 1.496   532.9s  12,299 tok/s
step  1000  train 1.131  val 1.500   670.3s  12,222 tok/s

sample after training:
ROMEO:
Is is God fright with holy and more lose
And thy claim--

BALTHBruptial: thy face and swallow her heart and heaven
To be whiping as one another seen;
I will be

saved checkpoint to runs/tiny-shakespeare/
Figure 9Measured loss from the run above, on an AMD EPYC 7R13 CPU with 8 threads. Step 0 is the untrained model, at the uniform-guess level. Hover for values.

A native checkpoint is a folder with config.json and model.safetensors. Tied weights are stored once, because safetensors refuses shared tensors and the duplicate would waste space.

def save_checkpoint(model: TinyLLM, path: str | Path) -> Path:
    """Write config.json and model.safetensors into the folder `path`."""
    path = Path(path)
    path.mkdir(parents=True, exist_ok=True)
    model.config.save(path / "config.json")
    state = {k: v.detach().contiguous().cpu() for k, v in model.state_dict().items()}
    if model.config.tie_word_embeddings:
        # Same storage as embed_tokens.weight. safetensors refuses shared tensors, and the
        # duplicate would only waste V*D values on disk, so drop it and re-tie on load.
        del state["lm_head.weight"]
    save_file(state, path / "model.safetensors")
    return path


def load_checkpoint(path: str | Path, device: str | torch.device = "cpu") -> TinyLLM:
    """Rebuild the model from config.json and load the weights. Fails loudly on any mismatch."""
    path = Path(path)
    config = ModelConfig.load(path / "config.json")
    model = TinyLLM(config)
    state = load_file(path / "model.safetensors")
    missing, unexpected = model.load_state_dict(state, strict=False)
    allowed_missing = {"lm_head.weight"} if config.tie_word_embeddings else set()
    if set(missing) - allowed_missing or unexpected:
        raise RuntimeError(f"checkpoint mismatch: missing={missing}, unexpected={unexpected}")
    return model.to(device)
Listing 19Saving and loading. load_checkpoint allows exactly one missing key, the tied head, and rejects everything else. For Hugging Face format, tinyllm.hf.save_hf writes a folder that AutoModelForCausalLM.from_pretrained opens.

Check the size on disk against the parameter count. The tiny model has 4,295,936 parameters at 4 bytes each, which is 17,183,744 bytes. The file holds 5,640 bytes more, for the safetensors header. A second copy of the tied head would have added V × D × 4 = 262,144 bytes.

$ du -b c04-llm/runs/tiny-shakespeare/*
422	c04-llm/runs/tiny-shakespeare/config.json
17189384	c04-llm/runs/tiny-shakespeare/model.safetensors

Checkpoint

  • Loss starts near 5.5 and falls below 2 within a few hundred steps.
  • test_round_trip_reproduces_logits, test_tied_weights_are_stored_once_and_retied, test_training_resumes_identically and test_save_hf_loads_with_automodel pass.
Step 16

An optional mixture-of-experts block

Goal Replace SwiGLU with a router and several expert MLPs, and see why routing needs its own loss.

Skip this step if you only want Llama. MoE keeps the parameter count of a large model and the compute of a small one. Each token runs through only k of E experts. Mixtral and DeepSeek use this idea, with more engineering around it.

    def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
        b, t, d = x.shape
        flat = x.reshape(-1, d)  # (N, D) with N = B*T
        n = flat.shape[0]

        logits = self.router(flat)  # (N, E): one score per expert per token
        probs = torch.softmax(logits.float(), dim=-1)  # (N, E)
        top_p, top_idx = probs.topk(self.top_k, dim=-1)  # (N, k), (N, k)
        top_p = (top_p / top_p.sum(dim=-1, keepdim=True)).to(x.dtype)  # renormalise over the chosen k

        capacity = n * self.top_k  # every assignment fits
        if self.capacity_factor is not None:
            # Each expert gets an equal share of the k*N assignments, times the slack factor.
            capacity = math.ceil(self.capacity_factor * n * self.top_k / self.num_experts)

        out = torch.zeros_like(flat)
        counts = torch.zeros(self.num_experts, dtype=torch.long, device=x.device)
        dropped = 0
        for e, expert in enumerate(self.experts):
            token_ids, slot_ids = torch.nonzero(top_idx == e, as_tuple=True)  # assignments to expert e
            if token_ids.numel() > capacity:
                # Over capacity: earlier tokens win, the rest skip this expert (the residual still carries them).
                dropped += token_ids.numel() - capacity
                token_ids, slot_ids = token_ids[:capacity], slot_ids[:capacity]
            counts[e] = token_ids.numel()
            if token_ids.numel() == 0:
                continue
            y = expert(flat[token_ids]) * top_p[token_ids, slot_ids, None]  # (n_e, D)
            out.index_add_(0, token_ids, y)

        self.last_tokens_per_expert, self.last_dropped = counts, dropped
        return out.view(b, t, d), load_balancing_loss(probs, top_idx, self.num_experts)


def load_balancing_loss(probs: torch.Tensor, top_idx: torch.Tensor, num_experts: int) -> torch.Tensor:
    """Switch-Transformer auxiliary loss: E * sum_e f_e * P_e.

    f_e: fraction of the N*k assignments that went to expert e (not differentiable).
    P_e: mean router probability for expert e (differentiable, so the gradient flows here).
    It equals 1.0 for perfectly uniform routing and grows as routing collapses onto few experts.
    """
    one_hot = torch.zeros_like(probs).scatter_(1, top_idx, 1.0)  # (N, E)
    f = one_hot.mean(dim=0) / top_idx.shape[1]  # (E,), sums to 1
    p = probs.mean(dim=0)  # (E,), sums to 1
    return num_experts * (f * p).sum()
Listing 20A Python loop over experts, written for reading. Production kernels batch this, and compute the same thing. test_moe_matches_dense_reference checks it against a brute-force version that runs every expert on every token.

Three ideas carry this listing. Routing logits come first: self.router is one linear layer that gives each token a score per expert, and topk keeps the best k. Each token’s kept scores are divided by their sum, so its weights add to 1.

Expert capacity comes next. With capacity_factor set, each expert accepts at most ceil(factor * N * k / E) assignments. Earlier tokens win, and later ones skip that expert, so only the residual stream carries them through it. The default of None never drops anything, and the demo below uses that default.

The auxiliary loss comes last. load_balancing_loss multiplies each expert’s share of the assignments by its mean router probability. The share is not differentiable, but the probability is, so the gradient lowers the probability of busy experts.

Figure 10Routing six tokens through four experts with top-2. Router probabilities here are illustrative. The measured routing is in the output below.

Does the load-balancing loss matter in practice? We train a small MoE model twice on the same batches, once with the loss switched off.

$ .venv/bin/python c04-llm/scripts/moe_demo.py --steps 300
device=cpu; a perfectly balanced router gives every expert 0.125 of the load
model: 1,706,624 params, 526,976 active per token (8 experts, top-2)

router_aux_loss_coef = 0.0
  step    1  lm loss 5.522  aux 1.041/layer  layer-0 shares [0.18 0.20 0.09 0.07 0.06 0.10 0.24 0.07]  busiest expert 0.24  (0s)
  step  100  lm loss 2.485  aux 1.837/layer  layer-0 shares [0.00 0.02 0.16 0.03 0.22 0.20 0.27 0.10]  busiest expert 0.46  (7s)
  step  200  lm loss 2.240  aux 1.733/layer  layer-0 shares [0.00 0.04 0.19 0.05 0.14 0.19 0.24 0.15]  busiest expert 0.48  (14s)
  step  300  lm loss 2.010  aux 1.835/layer  layer-0 shares [0.01 0.07 0.15 0.07 0.12 0.19 0.27 0.11]  busiest expert 0.49  (20s)

router_aux_loss_coef = 0.01
  step    1  lm loss 5.522  aux 1.041/layer  layer-0 shares [0.18 0.20 0.09 0.07 0.06 0.10 0.24 0.07]  busiest expert 0.24  (0s)
  step  100  lm loss 2.426  aux 1.091/layer  layer-0 shares [0.19 0.04 0.15 0.07 0.16 0.18 0.17 0.04]  busiest expert 0.19  (6s)
  step  200  lm loss 2.112  aux 1.010/layer  layer-0 shares [0.11 0.08 0.13 0.13 0.11 0.14 0.15 0.16]  busiest expert 0.16  (13s)
  step  300  lm loss 1.912  aux 1.017/layer  layer-0 shares [0.11 0.09 0.11 0.12 0.11 0.17 0.16 0.12]  busiest expert 0.18  (19s)
Shapes in step 16, with N = B × T
TensorShapeMeaning
flat(N, D)All tokens in the batch, pooled.
logits, probs(N, E)One score per expert per token.
top_p, top_idx(N, k)The chosen experts and their weights.
token_ids(n_e,)Tokens sent to expert e.
out(N, D)Weighted sum, one row per token.

Checkpoint

  • Active parameters per token are 526,976 of 1,706,624 in the demo model, about a third.
  • The tests in test_moe.py pass, including capacity overflow and the uniform-routing value of 1.0.

Design choices compared

The first table compares attention choices on one small task. Rows differ only in KV heads. Same data, batches, steps and seed. Read it left to right: parameters and cache fall, and the question is how much loss they cost.

MHA, GQA and MQA in the tiny preset, 400 steps on Tiny Shakespeare, AMD EPYC 7R13, 8 threads
ConfigKV headsAttention paramsCache per token, float32Validation loss
MHA81,572,86412,288 B1.618
GQA41,179,6486,144 B1.621
GQA (tinyllm default)2983,0403,072 B1.619
MQA1884,7361,536 B1.622
$ .venv/bin/python c04-llm/scripts/compare_heads.py --steps 400 --device cpu
device=cpu steps=400  tiny preset, 8 query heads, seed 0
config         kv heads  attn params  total params  cache/token  val loss    time
MHA                   8    1,572,864     4,885,760     12,288 B     1.618    362s
GQA                   4    1,179,648     4,492,544      6,144 B     1.621    327s
GQA                   2      983,040     4,295,936      3,072 B     1.619    287s
MQA                   1      884,736     4,197,632      1,536 B     1.622    274s

From MHA to MQA, attention parameters fall by 44% and the cache falls by a factor of 8. Validation loss stays between 1.618 and 1.622. This gap is too small to read as a ranking, and it does not show that heads are free. It comes from one seed, 400 steps and a tiny model on 1 MB of text. The GQA paper tests this at real model sizes. What this table does show is the cost side, which holds at any scale.

The second table places our model next to the designs it descends from. The columns are the aspects we built in the steps above.

From the 2017 transformer to tinyllm
Aspect2017 TransformerGPT-2tinyllm (Llama style)What the change buys
NormLayerNorm, postLayerNorm, preRMSNorm, preClean residual path. No mean or bias to compute.
PositionFixed sinusoid, addedLearned, addedRoPE, on q and kScore depends on offset. No position table in the weights.
AttentionMHAMHAGQA + SDPASmaller KV cache. Fused kernel.
Feed-forwardReLU, F = 4DGELU, F = 4DSwiGLU, F about 8D/3Gating, at about the same parameter count.
BiasesYesYesNoneFewer parameters, and the same norm gain does the job.
Weight tyingYesYesOptionalSaves V × D where the vocabulary is large.
DecodingEncoder-decoderDecoder onlyDecoder only, KV cacheEach new token computes only its own keys and values. Attention still reads every cached key.

Run everything

The final folder, and every command that produced a number in this post. Outputs of these runs are saved in c04-llm/results/.

c04-llm/ final tree
c04-llm/
├── README.md                   # every command, results table
├── conftest.py
├── configs/                    # tiny, smollm2-135m, llama3-8b as JSON
├── results/                    # saved outputs of every run in this post
├── tinyllm/
│   ├── config.py               # ModelConfig and presets
│   ├── tokenizer.py            # byte tokenizer
│   ├── norm.py                 # RMSNorm
│   ├── rope.py                 # RotaryEmbedding, apply_rotary
│   ├── attention_naive.py      # reference attention, masks, reshapes
│   ├── attention_sdpa.py       # the fused kernel
│   ├── attention.py            # GroupedQueryAttention
│   ├── kv_cache.py             # KVCache
│   ├── mlp.py                  # SwiGLU
│   ├── moe.py                  # optional mixture of experts
│   ├── block.py                # DecoderBlock
│   ├── model.py                # TinyLLM
│   ├── loss.py                 # shifted cross-entropy
│   ├── init.py                 # init_weights
│   ├── params.py               # closed-form counts
│   ├── sampling.py             # temperature, top-k, top-p
│   ├── generation.py           # generate, cached and uncached
│   ├── checkpoint.py           # native save and load
│   ├── hf.py                   # LlamaForCausalLM conversion
│   └── utils.py                # device, seed, timer
├── scripts/
│   ├── walkthrough.py          # one experiment per step
│   ├── inspect_shapes.py       # every tensor in one block
│   ├── param_count.py
│   ├── compare_hf.py           # the trusted-implementation check
│   ├── train_sanity.py         # about 12 minutes on Tiny Shakespeare
│   ├── generate.py
│   ├── break_it.py             # every intentional failure
│   ├── moe_demo.py
│   └── compare_heads.py        # MHA vs GQA vs MQA
├── benchmarks/
│   ├── bench_attention.py
│   └── bench_generation.py
└── tests/
    ├── c04_helpers.py
    ├── test_components.py      # norm, RoPE, attention, SwiGLU, loss
    ├── test_model.py           # shapes, causality, parameter counts
    ├── test_cache.py           # full forward == cached forward
    ├── test_hf_parity.py       # logits match LlamaForCausalLM
    ├── test_matches_c3.py      # matches the C3 attention library
    ├── test_sampling.py
    ├── test_checkpoint.py      # round trip and resume
    ├── test_precision.py       # bf16
    ├── test_gpu.py             # GPU only, 5 tests, pass on an H100
    └── test_moe.py
$ .venv/bin/python -m pytest c04-llm -m "not slow and not gpu and not network"
$ .venv/bin/python -m pytest c04-llm -m "network or slow"
$ .venv/bin/python c04-llm/scripts/walkthrough.py --step all
$ .venv/bin/python c04-llm/scripts/inspect_shapes.py
$ .venv/bin/python c04-llm/scripts/param_count.py
$ .venv/bin/python c04-llm/scripts/compare_hf.py --pretrained HuggingFaceTB/SmolLM2-135M
$ .venv/bin/python c04-llm/scripts/train_sanity.py --device cpu
$ .venv/bin/python c04-llm/scripts/generate.py --compare
$ .venv/bin/python c04-llm/scripts/break_it.py --case all --pretrained HuggingFaceTB/SmolLM2-135M --device cpu
$ .venv/bin/python c04-llm/scripts/moe_demo.py --steps 300
$ .venv/bin/python c04-llm/scripts/compare_heads.py --steps 400 --device cpu
$ .venv/bin/python c04-llm/benchmarks/bench_generation.py --device cpu
$ .venv/bin/python c04-llm/benchmarks/bench_generation.py --device cpu --preset smollm2-135m --new-tokens 128
$ .venv/bin/python c04-llm/benchmarks/bench_attention.py --device cpu
# On a machine with a GPU
$ .venv/bin/python -m pytest c04-llm -m gpu
$ .venv/bin/python c04-llm/benchmarks/bench_attention.py --device cuda --dtype bf16
$ .venv/bin/python c04-llm/benchmarks/bench_attention.py --device cuda --dtype float32
$ .venv/bin/python c04-llm/benchmarks/bench_generation.py --device cuda --dtype bf16
$ .venv/bin/python c04-llm/benchmarks/bench_generation.py --device cuda --dtype bf16 --preset smollm2-135m --new-tokens 496
$ .venv/bin/python c04-llm/benchmarks/bench_generation.py --device cuda --dtype bf16 --allow-cudnn-sdp
$ .venv/bin/python c04-llm/benchmarks/bench_generation.py --device cuda --dtype bf16 --preset smollm2-135m --new-tokens 496 --allow-cudnn-sdp

On an AMD EPYC 7R13 CPU, the first pytest command gives 75 passed and 6 deselected, in about 18 seconds. The network test, which downloads SmolLM2-135M, passes. The 5 GPU tests in tests/test_gpu.py skip on a machine without a GPU. They pass on an NVIDIA H100 80GB HBM3: 5 passed. The SmolLM2 GPU run uses 496 new tokens, while the CPU run above uses 128. c04-llm/README.md lists every command with its saved result.

Key insights and nuances

Exercises

  1. Batched generation with left paddingMedium Add an attention_mask argument. Make position ids skip padding, and combine the padding mask with the causal mask. Prove that a padded batch gives the same tokens as running each prompt alone.
    Hint

    Compute positions with attention_mask.cumsum(-1) - 1. attnzoo.masks.padding_mask shows the 4D mask shape.

  2. A preallocated cacheMedium Replace torch.cat with C3’s StaticKVCache design. Run bench_generation.py again and report what changes as T grows, on every device you have.
  3. Add qk-norm and compare lossesMedium Apply RMSNorm to q and k per head, before RoPE, as OLMo 2 and Qwen3 do. Run compare_heads.py on it. Report whether the difference is larger than the noise between two seeds.
  4. Match MixtralHard Make MoE reproduce the logits of MixtralForCausalLM on a small config. Map the state dict keys and find which detail of routing or RoPE differs from ours, if any.
  5. Write a divergence finderHard Write a diagnose.py that takes a model and a trusted reference. It should hook each block, find the first layer where their outputs differ, and name the sub-module. Test it on each case in break_it.py.

Continue reading

References

Grouped by topic. Every entry links to its primary source.

Architecture

Sampling

Mixture of experts

Code