llm.guideChapter 7Build a Tiny LLM From Scratch

Build a Tiny LLM From Scratch

A 162K-parameter transformer in about 350 lines of NumPy, trained on Shakespeare.

Part 2: Foundations. 9 sections, about 10 minutes.

23402,0004,0006,000loss (nats per character)training step6-gram counting model: 1.63a uniform guess: ln 65 = 4.17validation 1.71
23403,0006,000loss (nats per character)training step6-gram counting model: 1.63uniform guess: 4.17validation 1.71
The training run behind this chapter: a transformer with 161,920 parameters learning Shakespeare for six minutes on one CPU core. The thin line is training loss; the dots are validation loss.

Reading about transformers only gets you so far. This chapter builds one: an autograd engine, a model, a training loop and a sampler, in about 350 lines of Python that use numpy and nothing else. Every number and figure in the chapter comes from running that code.

The model is small enough to train on a laptop CPU in minutes. The same structure at 10 million parameters is Andrej Karpathy’s nanoGPT, which trains in a few minutes on a free cloud GPU; section 7.9 covers what changes as you scale up.

7.1The plan

Five parts, each one a chapter you have already read.

PartWhat it doesWhere it was explained
DataText to character ids; random windows of 64 characters, with targets shifted by oneSections 2.2 and 3.3
AutogradComputes the gradient of the loss for every weightSections 3.4 and 3.10
ModelEmbeddings, three pre-norm transformer blocks, output layerChapter 5
Training loopBatch, forward, loss, backward, AdamW stepSections 3.5 to 3.7
SamplerGenerates one token at a time, with a KV cacheSections 2.7 and 2.8

The configuration: a vocabulary of 65 characters, a context of 64, a width of 64, 3 layers and 4 heads. Section 5.5 counted its weights: 161,920, of which 92% are in the three blocks.

Token embedding65 × 64 = 4,160Positions64 × 64 = 4,0963 blocksattention 16,448MLP 33,088per blockNorms896 in allOutput layer64 × 65 = 4,160161,920 weights in all; the three blocks hold 92% of themconfiguration: vocabulary 65, context 64, width 64, 3 layers, 4 heads
Figure 7.1 The plan as a picture, with the counts from section 5.5. Each part is one of the chapters you have read.

Common take“I built an LLM.”

Sharper take“I built the core loop of one, at a scale where I can read every number. That is its value: there is nothing in it I can’t inspect.”

7.2Autograd for arrays

Every operation records how to send gradients back.

Chapter 3’s lab built an autograd engine in which every node was a single number. That design is correct and far too slow for a real model. The fix is to make each node an array. The idea does not change: an operation produces its output and also stores a small function that, given the gradient of the loss with respect to the output, adds the right gradient to each input.

class T:
    """An array that remembers how it was made."""
    def __init__(self, d, parents=(), back=None):
        self.d = d
        self.g = None
        self.parents = parents
        self.back = back

    def backward(self):
        order, seen, stack = [], set(), [(self, False)]
        while stack:                                   # topological sort, without recursion
            v, done = stack.pop()
            if done:
                order.append(v); continue
            if id(v) in seen:
                continue
            seen.add(id(v)); stack.append((v, True))
            for p in v.parents:
                stack.append((p, False))
        self.g = np.ones_like(self.d)
        for v in reversed(order):                      # chain rule, output to inputs
            if v.back is not None and v.g is not None:
                v.back(v.g)

def _acc(t, g):
    t.g = g if t.g is None else t.g + g

Each operation is then a few lines. Here is a linear layer: the forward pass is one matrix product, and the backward pass is the three gradients from section 3.4.

def _mm(x, W):                                         # (..., in) @ (in, out) as one 2-D product, which is much faster
    return (x.reshape(-1, x.shape[-1]) @ W).reshape(x.shape[:-1] + (W.shape[1],))

def linear(x, W, b=None):                              # x @ W + b on the last axis
    out = T(_mm(x.d, W.d) + (b.d if b is not None else 0), (x, W) + ((b,) if b is not None else ()))
    def back(g):
        x2 = x.d.reshape(-1, x.d.shape[-1]); g2 = g.reshape(-1, g.shape[-1])
        _acc(W, x2.T @ g2)
        if b is not None:
            _acc(b, g2.sum(0))
        _acc(x, _mm(g, W.d.T))
    out.back = back
    return out

With arrays, the entire model is a graph of a few dozen nodes however many parameters it has. Before trusting it, I checked every parameter group against finite differences, the test from section 3.10: the largest relative error was 1.4 × 10⁻⁷.

Common take“Frameworks do the calculus with some special machinery.”

Sharper take“Each operation knows its own local derivative, and the engine applies the chain rule in reverse order. That’s all PyTorch does too, with faster arrays.”

7.3Attention in code

Score, mask, softmax, blend, and four lines to send gradients back.

The attention formula from section 5.1 is six lines of forward pass. The queries, keys and values arrive already split into heads, with shape (batch, heads, tokens, head size).

def attention(q, k, v):
    """Causal scaled dot-product attention. q, k, v: (B, heads, T, d_head)."""
    n, dh = q.d.shape[2], q.d.shape[3]
    scale = 1 / math.sqrt(dh)
    s = (q.d @ k.d.transpose(0, 1, 3, 2)) * scale      # every token scores every token
    s = s + np.triu(np.full((n, n), -1e9, dtype=s.dtype), 1)   # causal mask: no peeking at the future
    s = s - s.max(-1, keepdims=True)
    p = np.exp(s); p /= p.sum(-1, keepdims=True)       # softmax: scores -> weights
    out = T(p @ v.d, (q, k, v))                        # blend the values
    out.att = p
    def back(g):
        _acc(v, p.transpose(0, 1, 3, 2) @ g)
        gp = g @ v.d.transpose(0, 1, 3, 2)
        gs = p * (gp - (gp * p).sum(-1, keepdims=True))   # back through the softmax
        _acc(q, (gs @ k.d) * scale)
        _acc(k, (gs.transpose(0, 1, 3, 2) @ q.d) * scale)
    out.back = back
    return out

The forward half reads top to bottom as the formula does: score every token against every token, add a large negative number above the diagonal so no token sees the future, apply softmax, and blend the values. The backward half applies the chain rule to those same steps in reverse. The one line worth staring at is the softmax’s: a weight’s gradient depends on all the other weights in its row, because they are forced to sum to 1.

x(B, 64, 64)q, k, v(B, 4, 64, 16)scores(B, 4, 64, 64)mask, softmaxsame shape× v(B, 4, 64, 16)merge heads(B, 64, 64)the causal mask for 10 tokens:each row sees itself and earlier tokensB = batch, 4 heads of size 16,64 tokens of context
Figure 7.2 The shapes the six lines of code move through, and the mask that keeps each token from reading the future.

Common take“The causal mask is a special attention mode.”

Sharper take“It’s one line: add minus infinity to the scores above the diagonal. Remove it and the same code is a bidirectional encoder.”

7.4The model

Embeddings, three pre-norm blocks, a final norm and an output layer.

def forward(P, cfg, idx, keep_att=None):
    """idx: (B, T) token ids -> logits (B, T, V). A pre-norm decoder-only transformer."""
    h = cfg['heads']
    x = add(emb(P['tok'], idx), emb(P['pos'], np.arange(idx.shape[1])))
    for l in range(cfg['layers']):
        a = layernorm(x, P[f'{l}.ln1g'], P[f'{l}.ln1b'])
        att = attention(split_heads(linear(a, P[f'{l}.Wq']), h), split_heads(linear(a, P[f'{l}.Wk']), h),
                        split_heads(linear(a, P[f'{l}.Wv']), h))
        if keep_att is not None:
            keep_att.append(att.att)
        x = add(x, linear(merge_heads(att), P[f'{l}.Wo'], P[f'{l}.bo']))        # x + Attention(Norm(x))
        m = layernorm(x, P[f'{l}.ln2g'], P[f'{l}.ln2b'])
        x = add(x, linear(gelu(linear(m, P[f'{l}.W1'], P[f'{l}.b1'])), P[f'{l}.W2'], P[f'{l}.b2']))   # x + MLP(Norm(x))
    return linear(layernorm(x, P['lnfg'], P['lnfb']), P['head'])

Read it against the pipeline at the top of Chapter 5. Token and position embeddings are looked up and added. Each layer normalizes, runs attention, and adds the result back; then normalizes, runs the MLP, and adds that back. The two commented lines are the pre-norm pattern from section 3.9. A final normalization and one last matrix turn each position’s vector into 65 scores.

The output has one row of scores for every position in the batch, and the loss is the cross-entropy of section 3.3 averaged over all of them. One forward pass on a batch of 16 windows of 64 characters is therefore 1,024 next-character predictions, each a training example.

Common take“The model is trained to predict the last token of each window.”

Sharper take“It’s trained on every position at once. The causal mask makes each position a separate prediction, so one window of 64 characters is 64 training examples.”

7.5The training loop

Sample a batch, run it forward, measure, send gradients back, step.

"""Train the tiny transformer on a text file:  python3 train_tiny.py shakespeare.txt"""
import math, sys
import numpy as np
import mt

text = open(sys.argv[1] if len(sys.argv) > 1 else 'shakespeare.txt').read()
chars = sorted(set(text)); stoi = {c: i for i, c in enumerate(chars)}
data = np.array([stoi[c] for c in text])
split = int(0.9 * len(data)); train, val = data[:split], data[split:]

cfg = {'vocab': len(chars), 'd': 64, 'layers': 3, 'heads': 4, 'block': 64}
steps, batch_size, peak_lr = (int(sys.argv[2]) if len(sys.argv) > 2 else 6000), 16, 2e-3
P = mt.init(cfg); opt = mt.AdamW(P)
rng = np.random.default_rng(0)


def get_batch(src, B):
    at = rng.integers(0, len(src) - cfg['block'] - 1, B)
    X = np.stack([src[i:i + cfg['block']] for i in at])            # inputs
    Y = np.stack([src[i + 1:i + cfg['block'] + 1] for i in at])    # the same text, shifted by one
    return X, Y


for step in range(1, steps + 1):
    lr = peak_lr * min(1, step / 100) * (0.1 + 0.45 * (1 + math.cos(math.pi * step / steps)))   # warmup, then cosine decay
    X, Y = get_batch(train, batch_size)
    loss, _ = mt.loss_fn(P, cfg, X, Y)       # forward pass and cross-entropy
    loss.backward()                          # a gradient for every parameter
    opt.step(lr)                             # clip, AdamW update, reset the gradients
    if step % 500 == 0 or step == 1:
        Xv, Yv = get_batch(val, 64)
        print(step, 'train %.3f' % float(loss.d), 'val %.3f' % float(mt.loss_fn(P, cfg, Xv, Yv)[0].d))

prompt = np.array([[stoi[c] for c in 'ROMEO:\n']])
out, _ = mt.generate(mt.weights(P), cfg, prompt, 56, rng, temp=0.8)
print(''.join(chars[i] for i in out[0]))

The loop is the one from section 3.1 with the refinements from the rest of Chapter 3: AdamW (section 3.5), a short warmup followed by cosine decay (section 3.6), and gradient clipping at 1.0, which lives inside opt.step. Six thousand steps took 365 seconds on one CPU core.

The complete engine and model (mt.py)
"""mt.py: a tensor autograd engine in numpy and a small GPT built on it.
The scalar engine from Chapter 3, grown up: every operation records how to send gradients back."""
import math
import numpy as np

DT = np.float32


class T:
    """An array that remembers how it was made."""
    def __init__(self, d, parents=(), back=None):
        self.d = d
        self.g = None
        self.parents = parents
        self.back = back

    def backward(self):
        order, seen, stack = [], set(), [(self, False)]
        while stack:                                   # topological sort, without recursion
            v, done = stack.pop()
            if done:
                order.append(v); continue
            if id(v) in seen:
                continue
            seen.add(id(v)); stack.append((v, True))
            for p in v.parents:
                stack.append((p, False))
        self.g = np.ones_like(self.d)
        for v in reversed(order):                      # chain rule, output to inputs
            if v.back is not None and v.g is not None:
                v.back(v.g)


def _acc(t, g):
    t.g = g if t.g is None else t.g + g


def _unbroadcast(g, shape):
    while g.ndim > len(shape):
        g = g.sum(0)
    for i, s in enumerate(shape):
        if s == 1 and g.shape[i] != 1:
            g = g.sum(i, keepdims=True)
    return g


def emb(W, idx):                                       # table lookup
    out = T(W.d[idx], (W,))
    def back(g):
        gw = np.zeros_like(W.d); np.add.at(gw, idx, g); _acc(W, gw)
    out.back = back
    return out


def add(a, b):
    out = T(a.d + b.d, (a, b))
    def back(g):
        _acc(a, _unbroadcast(g, a.d.shape)); _acc(b, _unbroadcast(g, b.d.shape))
    out.back = back
    return out


def _mm(x, W):                                         # (..., in) @ (in, out) as one 2-D product, which is much faster
    return (x.reshape(-1, x.shape[-1]) @ W).reshape(x.shape[:-1] + (W.shape[1],))


def linear(x, W, b=None):                              # x @ W + b on the last axis
    out = T(_mm(x.d, W.d) + (b.d if b is not None else 0), (x, W) + ((b,) if b is not None else ()))
    def back(g):
        x2 = x.d.reshape(-1, x.d.shape[-1]); g2 = g.reshape(-1, g.shape[-1])
        _acc(W, x2.T @ g2)
        if b is not None:
            _acc(b, g2.sum(0))
        _acc(x, _mm(g, W.d.T))
    out.back = back
    return out


def layernorm(x, gain, bias, eps=1e-5):
    mu = x.d.mean(-1, keepdims=True); xc = x.d - mu
    inv = 1 / np.sqrt((xc ** 2).mean(-1, keepdims=True) + eps); xh = xc * inv
    out = T(xh * gain.d + bias.d, (x, gain, bias))
    def back(g):
        _acc(gain, (g * xh).reshape(-1, xh.shape[-1]).sum(0)); _acc(bias, g.reshape(-1, g.shape[-1]).sum(0))
        gx = g * gain.d
        _acc(x, inv * (gx - gx.mean(-1, keepdims=True) - xh * (gx * xh).mean(-1, keepdims=True)))
    out.back = back
    return out


_C = math.sqrt(2 / math.pi)


def gelu(x):
    x2 = x.d * x.d
    t = np.tanh(_C * (x.d + 0.044715 * x2 * x.d))
    out = T(0.5 * x.d * (1 + t), (x,))
    def back(g):
        _acc(x, g * (0.5 * (1 + t) + 0.5 * x.d * (1 - t * t) * _C * (1 + 0.134145 * x2)))
    out.back = back
    return out


def split_heads(x, h):                                 # (B, T, d) -> (B, h, T, d/h)
    B, n, d = x.d.shape
    out = T(x.d.reshape(B, n, h, d // h).transpose(0, 2, 1, 3), (x,))
    def back(g):
        _acc(x, g.transpose(0, 2, 1, 3).reshape(B, n, d))
    out.back = back
    return out


def merge_heads(x):                                    # (B, h, T, d/h) -> (B, T, d)
    B, h, n, dh = x.d.shape
    out = T(x.d.transpose(0, 2, 1, 3).reshape(B, n, h * dh), (x,))
    def back(g):
        _acc(x, g.reshape(B, n, h, dh).transpose(0, 2, 1, 3))
    out.back = back
    return out


def attention(q, k, v):
    """Causal scaled dot-product attention. q, k, v: (B, heads, T, d_head)."""
    n, dh = q.d.shape[2], q.d.shape[3]
    scale = 1 / math.sqrt(dh)
    s = (q.d @ k.d.transpose(0, 1, 3, 2)) * scale      # every token scores every token
    s = s + np.triu(np.full((n, n), -1e9, dtype=s.dtype), 1)   # causal mask: no peeking at the future
    s = s - s.max(-1, keepdims=True)
    p = np.exp(s); p /= p.sum(-1, keepdims=True)       # softmax: scores -> weights
    out = T(p @ v.d, (q, k, v))                        # blend the values
    out.att = p
    def back(g):
        _acc(v, p.transpose(0, 1, 3, 2) @ g)
        gp = g @ v.d.transpose(0, 1, 3, 2)
        gs = p * (gp - (gp * p).sum(-1, keepdims=True))   # back through the softmax
        _acc(q, (gs @ k.d) * scale)
        _acc(k, (gs.transpose(0, 1, 3, 2) @ q.d) * scale)
    out.back = back
    return out


def cross_entropy(logits, targets, weights=None):     # logits (N, V); optional per-row weights
    z = logits.d - logits.d.max(-1, keepdims=True)
    p = np.exp(z); p /= p.sum(-1, keepdims=True)
    N = len(targets); w = np.ones(N, dtype=p.dtype) if weights is None else weights.astype(p.dtype)
    out = T(np.array(-(w * np.log(p[np.arange(N), targets] + 1e-12)).sum() / N, dtype=p.dtype), (logits,))
    def back(g):
        d = p.copy(); d[np.arange(N), targets] -= 1
        _acc(logits, d * (w[:, None] * (g / N)))
    out.back = back
    return out


def kl_to(logits, base_logp):                          # mean KL(model || base), base_logp fixed
    z = logits.d - logits.d.max(-1, keepdims=True)
    logp = z - np.log(np.exp(z).sum(-1, keepdims=True)); p = np.exp(logp)
    diff = logp - base_logp
    kl = (p * diff).sum(-1, keepdims=True)
    N = logits.d.shape[0]
    out = T(np.array(kl.mean(), dtype=p.dtype), (logits,))
    def back(g):
        _acc(logits, p * (diff - kl) * (g / N))
    out.back = back
    return out


def reshape(x, shape):
    old = x.d.shape
    out = T(x.d.reshape(shape), (x,))
    def back(g):
        _acc(x, g.reshape(old))
    out.back = back
    return out


# ------------------------------------------------------------------ the model
def init(cfg, seed=0):
    r = np.random.default_rng(seed)
    V, d, L, block = cfg['vocab'], cfg['d'], cfg['layers'], cfg['block']
    res = 0.02 / math.sqrt(2 * L)                      # residual projections start small (Chapter 3, section 3.8)
    P = {'tok': r.normal(0, .02, (V, d)), 'pos': r.normal(0, .02, (block, d))}
    for l in range(L):
        P.update({f'{l}.ln1g': np.ones(d), f'{l}.ln1b': np.zeros(d),
                  f'{l}.Wq': r.normal(0, .02, (d, d)), f'{l}.Wk': r.normal(0, .02, (d, d)), f'{l}.Wv': r.normal(0, .02, (d, d)),
                  f'{l}.Wo': r.normal(0, res, (d, d)), f'{l}.bo': np.zeros(d),
                  f'{l}.ln2g': np.ones(d), f'{l}.ln2b': np.zeros(d),
                  f'{l}.W1': r.normal(0, .02, (d, 4 * d)), f'{l}.b1': np.zeros(4 * d),
                  f'{l}.W2': r.normal(0, res, (4 * d, d)), f'{l}.b2': np.zeros(d)})
    P.update({'lnfg': np.ones(d), 'lnfb': np.zeros(d), 'head': r.normal(0, .02, (d, V))})
    return {k: T(v.astype(DT)) for k, v in P.items()}


def forward(P, cfg, idx, keep_att=None):
    """idx: (B, T) token ids -> logits (B, T, V). A pre-norm decoder-only transformer."""
    h = cfg['heads']
    x = add(emb(P['tok'], idx), emb(P['pos'], np.arange(idx.shape[1])))
    for l in range(cfg['layers']):
        a = layernorm(x, P[f'{l}.ln1g'], P[f'{l}.ln1b'])
        att = attention(split_heads(linear(a, P[f'{l}.Wq']), h), split_heads(linear(a, P[f'{l}.Wk']), h),
                        split_heads(linear(a, P[f'{l}.Wv']), h))
        if keep_att is not None:
            keep_att.append(att.att)
        x = add(x, linear(merge_heads(att), P[f'{l}.Wo'], P[f'{l}.bo']))        # x + Attention(Norm(x))
        m = layernorm(x, P[f'{l}.ln2g'], P[f'{l}.ln2b'])
        x = add(x, linear(gelu(linear(m, P[f'{l}.W1'], P[f'{l}.b1'])), P[f'{l}.W2'], P[f'{l}.b2']))   # x + MLP(Norm(x))
    return linear(layernorm(x, P['lnfg'], P['lnfb']), P['head'])


def loss_fn(P, cfg, X, Y, weights=None):
    logits = forward(P, cfg, X)
    return cross_entropy(reshape(logits, (-1, cfg['vocab'])), Y.reshape(-1), weights), logits


class AdamW:
    def __init__(self, P, wd=0.1, b1=0.9, b2=0.95):
        self.P, self.wd, self.b1, self.b2, self.t = P, wd, b1, b2, 0
        self.m = {k: np.zeros_like(p.d) for k, p in P.items()}
        self.v = {k: np.zeros_like(p.d) for k, p in P.items()}

    def step(self, lr, clip=1.0):
        norm = math.sqrt(sum(float((p.g.astype(np.float64) ** 2).sum()) for p in self.P.values()))
        scale = min(1.0, clip / (norm + 1e-12))
        self.t += 1
        for k, p in self.P.items():
            g = p.g * scale
            self.m[k] = self.b1 * self.m[k] + (1 - self.b1) * g
            self.v[k] = self.b2 * self.v[k] + (1 - self.b2) * g * g
            if p.d.ndim >= 2:
                p.d *= 1 - lr * self.wd                # decoupled weight decay, matrices only
            p.d -= lr * (self.m[k] / (1 - self.b1 ** self.t)) / (np.sqrt(self.v[k] / (1 - self.b2 ** self.t)) + 1e-8)
            p.g = None
        return norm


# ------------------------------------------------------------------ inference without autograd
def _ln(x, g, b):
    xc = x - x.mean(-1, keepdims=True)
    return xc / np.sqrt((xc ** 2).mean(-1, keepdims=True) + 1e-5) * g + b


def _gelu(x):
    return 0.5 * x * (1 + np.tanh(_C * (x + 0.044715 * x * x * x)))


def weights(P):
    return {k: p.d for k, p in P.items()}


def np_forward(W, cfg, idx):
    """Plain forward pass on arrays: (B, T) -> logits (B, T, V)."""
    B, n = idx.shape; h = cfg['heads']; d = cfg['d']; dh = d // h
    x = W['tok'][idx] + W['pos'][:n]
    mask = np.triu(np.full((n, n), -1e9, dtype=x.dtype), 1)
    for l in range(cfg['layers']):
        a = _ln(x, W[f'{l}.ln1g'], W[f'{l}.ln1b'])
        q = _mm(a, W[f'{l}.Wq']).reshape(B, n, h, dh).transpose(0, 2, 1, 3)
        k = _mm(a, W[f'{l}.Wk']).reshape(B, n, h, dh).transpose(0, 2, 1, 3)
        v = _mm(a, W[f'{l}.Wv']).reshape(B, n, h, dh).transpose(0, 2, 1, 3)
        s = q @ k.transpose(0, 1, 3, 2) / math.sqrt(dh) + mask
        s = s - s.max(-1, keepdims=True); p = np.exp(s); p /= p.sum(-1, keepdims=True)
        x = x + _mm((p @ v).transpose(0, 2, 1, 3).reshape(B, n, d), W[f'{l}.Wo']) + W[f'{l}.bo']
        m = _ln(x, W[f'{l}.ln2g'], W[f'{l}.ln2b'])
        x = x + _mm(_gelu(_mm(m, W[f'{l}.W1']) + W[f'{l}.b1']), W[f'{l}.W2']) + W[f'{l}.b2']
    return _mm(_ln(x, W['lnfg'], W['lnfb']), W['head'])


def step_cached(W, cfg, toks, pos, cache):
    """One new token per sequence, reusing cached keys and values. toks: (B,) -> logits (B, V)."""
    B = len(toks); h = cfg['heads']; d = cfg['d']; dh = d // h
    x = W['tok'][toks] + W['pos'][pos]
    for l in range(cfg['layers']):
        a = _ln(x, W[f'{l}.ln1g'], W[f'{l}.ln1b'])
        q = _mm(a, W[f'{l}.Wq']).reshape(B, h, 1, dh)
        k = _mm(a, W[f'{l}.Wk']).reshape(B, h, 1, dh)
        v = _mm(a, W[f'{l}.Wv']).reshape(B, h, 1, dh)
        if cache[l] is None:
            cache[l] = [k, v]
        else:
            cache[l] = [np.concatenate([cache[l][0], k], 2), np.concatenate([cache[l][1], v], 2)]
        s = q @ cache[l][0].transpose(0, 1, 3, 2) / math.sqrt(dh)        # the new token against everything cached
        s = s - s.max(-1, keepdims=True); p = np.exp(s); p /= p.sum(-1, keepdims=True)
        x = x + (p @ cache[l][1]).reshape(B, d) @ W[f'{l}.Wo'] + W[f'{l}.bo']
        m = _ln(x, W[f'{l}.ln2g'], W[f'{l}.ln2b'])
        x = x + _mm(_gelu(_mm(m, W[f'{l}.W1']) + W[f'{l}.b1']), W[f'{l}.W2']) + W[f'{l}.b2']
    return _mm(_ln(x, W['lnfg'], W['lnfb']), W['head'])


def generate(W, cfg, prompt, n_new, rng, temp=1.0, greedy=False):
    """prompt: (B, T0) ids. Returns (B, T0 + n_new) ids and the log-probability of each sampled token."""
    B, n0 = prompt.shape
    cache = [None] * cfg['layers']
    for t in range(n0):
        logits = step_cached(W, cfg, prompt[:, t], t, cache)
    out, lps = [prompt], []
    for t in range(n_new):
        z = logits / temp
        z = z - z.max(-1, keepdims=True); p = np.exp(z); p /= p.sum(-1, keepdims=True)
        if greedy:
            nxt = p.argmax(-1)
        else:                                          # inverse-CDF sampling for the whole batch at once
            c = np.cumsum(p.astype(np.float64), -1); c /= c[:, -1:]
            nxt = (c > rng.random((B, 1))).argmax(-1)
        lps.append(np.log(p[np.arange(B), nxt] + 1e-12))
        out.append(nxt[:, None])
        if t < n_new - 1:
            logits = step_cached(W, cfg, nxt, n0 + t, cache)
    return np.concatenate(out, 1), np.stack(lps, 1)

Common take“Training a transformer needs a GPU cluster.”

Sharper take“Training a useful one does. The algorithm is twenty lines and runs on a laptop; what the cluster buys is scale.”

7.6Reading the run

What each part of the curve is telling you.

The figure at the top of the chapter is this run. Read it left to right.

  • Step 1: 4.17. That is ln 65, the loss of a uniform guess over 65 characters. Starting there confirms the initialization is sound (section 3.8).
  • Steps 1 to 500: a fast drop to 2.32. The model is learning which characters are common and which follow which. A bigram count model scores 2.49, so this is roughly bigram-level knowledge.
  • Steps 500 to 6,000: a long, slow descent. Words, then common phrases, then the layout of a play. Validation ends at 1.71.
  • The gap. Training loss ends at 1.53, below validation by 0.18. The model has started to fit its training windows better than new text: the early stage of overfitting from section 3.7.

How good is 1.71? Here is every model so far on this text and this split:

Counting

6-gram with backoffChapter 41.63

Recurrent

Vanilla RNN31K parameters1.87
LSTM93K parameters1.87

Transformer

This chapter, characters162K parameters1.71
This chapter, BPE tokens219K parameters, section 6.91.65
nanoGPT, characters10.7M parameters, on a GPU (reported)1.47
Figure 7.3 Validation loss in nats per character; lower is better. The last row is the figure reported in the nanoGPT repository for its 10M-parameter character model, not a run from this guide.

The transformer is clearly ahead of the recurrent models from Chapter 4 and still just behind the 6-gram counting model. That is the honest result at this size. The path past the counting model is scale: the same architecture with sixty times the parameters, a GPU and a longer context reaches about 1.47.

Common take“The loss went down, so training worked.”

Sharper take“I check four things: the first value against ln of the vocabulary size, the shape of the drop, the gap between training and validation, and a baseline on the same data to say whether the final number is good.”

7.7Sampling

One model, three temperatures.

Generation is the loop from section 2.1: run the model, turn the last position’s scores into probabilities, draw one character, append it, repeat. Temperature divides the scores before the softmax (section 2.8). The same trained weights at three settings:

Temperature 0.5

ROMEO:
The sun will be have that the sent of that the did will tears,
That the hath and the now at one the was that mine take
To entreat things did my be son our from his and
A sleep the …

Temperature 1.0

ROMEO:
Thinks at down. Cation 'Tis in door.

MALIZABETH:
Sun sholad upon my lie: toget breen roy, here, 'is?
'Do, and he say are.

Somere's,
To flatter child high your of Roma.
Have him …

Temperature 1.5

ROMEO:
Thoirth willw's caulna?

KING RICHARD II

but sen'sluck,'
'Betth a, slain tonat!
O, or woay'd.' gRatzel's a mercummI:
'With true.
'Twasped,
Unom ahild hobedy: yet fair ' through that …
Figure 7.4 Real samples, each continuing “ROMEO:”. At 0.5 the model stays with its most common words and repeats itself. At 1.0 it is more varied and invents a speaker. At 1.5 the spelling falls apart.

None of this is Shakespeare, and none of it is copied either. With 161,920 parameters the model cannot memorize a megabyte of text; what it has kept is the statistics of spelling, common words and the shape of a script.

Common take“Higher temperature makes the model more creative.”

Sharper take“Higher temperature gives low-probability characters more of a chance. Whether that reads as creative or broken depends on how good the probabilities were to begin with.”

7.8The KV cache

The same output, twelve times faster.

The simple way to generate recomputes the whole sequence for every new token. But a token’s keys and values never change once computed, because of the causal mask. The KV cache stores them, so each step computes one new token and attends over what is stored (section 2.7).

def step_cached(W, cfg, toks, pos, cache):
    """One new token per sequence, reusing cached keys and values. toks: (B,) -> logits (B, V)."""
    B = len(toks); h = cfg['heads']; d = cfg['d']; dh = d // h
    x = W['tok'][toks] + W['pos'][pos]
    for l in range(cfg['layers']):
        a = _ln(x, W[f'{l}.ln1g'], W[f'{l}.ln1b'])
        q = _mm(a, W[f'{l}.Wq']).reshape(B, h, 1, dh)
        k = _mm(a, W[f'{l}.Wk']).reshape(B, h, 1, dh)
        v = _mm(a, W[f'{l}.Wv']).reshape(B, h, 1, dh)
        if cache[l] is None:
            cache[l] = [k, v]
        else:
            cache[l] = [np.concatenate([cache[l][0], k], 2), np.concatenate([cache[l][1], v], 2)]
        s = q @ cache[l][0].transpose(0, 1, 3, 2) / math.sqrt(dh)        # the new token against everything cached
        s = s - s.max(-1, keepdims=True); p = np.exp(s); p /= p.sum(-1, keepdims=True)
        x = x + (p @ cache[l][1]).reshape(B, d) @ W[f'{l}.Wo'] + W[f'{l}.bo']
        m = _ln(x, W[f'{l}.ln2g'], W[f'{l}.ln2b'])
        x = x + _mm(_gelu(_mm(m, W[f'{l}.W1']) + W[f'{l}.b1']), W[f'{l}.W2']) + W[f'{l}.b2']
    return _mm(_ln(x, W['lnfg'], W['lnfb']), W['head'])

To make the timing visible I measured it on a larger untrained model of the same design, 4 layers and a width of 128, generating 256 tokens:

04812064128192256milliseconds per tokenposition of the token being generatedno cache: 11.7 msKV cache: 0.58 ms
04812064128192256milliseconds per tokenposition of the token being generatedno cache: 11.7 msKV cache: 0.58 ms
  • recompute everything
  • with a KV cache
Figure 7.5 Real timing. Without a cache the cost of each token grows with its position, from 1.0 ms to 11.7 ms. With a cache it stays near 0.6 ms. In total: 1.48 seconds against 0.12.

The cache is not free. It held 1.05 MB at the end, which is exactly 2 × 4 layers × 256 tokens × 128 dimensions × 4 bytes, the formula from section 2.7 at small scale. And it must reproduce the uncached result: in a double-precision check the two differed by 2 × 10⁻¹⁶.

Common take“The KV cache is an optimization you can add later.”

Sharper take“Without it, generating n tokens costs on the order of n² token computations. Every serving stack has it, and its memory is what limits how many conversations fit on a GPU.”

7.9What the toy lacks

An honest bridge to production models.

This chapter’s modelA production LLM
Tokenizer65 charactersSubwords, 100,000 or more (Chapter 6)
Parameters161,920Billions to hundreds of billions
Context64 tokensHundreds of thousands of tokens
Training data1 MB of playsTrillions of tokens (Chapter 8)
PositionLearned, absoluteRotary (section 5.4)
After pretrainingNothing: it continues textFine-tuning and reinforcement learning to make an assistant (Chapter 9)
Inferencenumpy on one coreBatched, quantized, on GPUs

What is the same matters more: the block, the loss, the training loop and the sampling loop. A frontier model is this program with more layers, more data, a better tokenizer, and a great deal of engineering to make it train and serve at that size.

Two next steps, in order. Train nanoGPT’s character-level Shakespeare configuration, 6 layers, a width of 384 and a context of 256, on a free cloud GPU and watch validation loss pass the 6-gram. Then read nanochat, which carries the same ideas through a tokenizer, pretraining, chat fine-tuning and a web interface, and can be trained end to end for about a hundred dollars of GPU time.

Parameterstoy 161,9208 billionabout 49,000 timesTraining tokenstoy 1.1M15 trillionabout 14 million timesContext, tokenstoy 64128,000about 2,000 times
Figure 7.6 The gap on logarithmic scales, toy (orange) against a production model shaped like Llama 3 8B (blue), with published training tokens and context. The program is the same; every number is thousands to millions of times larger.

Common take“It’s a toy, so it doesn’t tell you much about real models.”

Sharper take“It tells you which parts are essential, since everything in it is. What it leaves out is scale and post-training, and those are the next three chapters.”

Key takeaways

  • A working transformer is an autograd engine, a model, a training loop and a sampler: about 350 lines with numpy.
  • Autograd on arrays is the scalar engine with bigger nodes: each operation stores how to pass gradients to its inputs. Check it against finite differences before trusting it.
  • The causal mask is one line, and it turns every position in a window into a separate training example.
  • The first loss should be ln of the vocabulary size: 4.17 for 65 characters.
  • After six minutes on one CPU core the model reached 1.71: ahead of the RNN and LSTM at 1.87, just behind the 6-gram at 1.63. Scale is what closes that gap.
  • Temperature reshapes the same probabilities: low repeats the common, high lets the unlikely through.
  • A KV cache made generating 256 tokens about twelve times faster, for 1 MB of memory, with identical output.
  • The toy and a frontier model share the block, the loss and both loops. They differ in scale, tokenizer and post-training.

Check your understanding

  1. Your first logged loss is 6.2 on a 65-character vocabulary. What should it have been, what does 6.2 tell you, and what would you inspect?

    Answer outline

    It should be near ln 65 = 4.17, the loss of a uniform guess. A higher value means the untrained model is confidently wrong: its initial scores are far from equal. Inspect the scale of the output layer’s initial weights and the spread of the first batch’s scores, then check that targets are the inputs shifted by exactly one and that ids map to the right characters. Section 3.8 showed the same symptom from an output layer initialized 100 times too large.

  2. You train the same model much longer. Training loss falls to 1.2 while validation loss bottoms out at 1.7 and starts to climb. What is happening, what are three responses, and which would you try first?

    Answer outline

    Overfitting: the model is memorizing its one megabyte of training text. Responses: keep the checkpoint with the best validation loss (early stopping), add regularization such as dropout or more weight decay, or get more data; shrinking the model also works but lowers the ceiling. Try early stopping first, since it costs nothing, then dropout of 0.1 to 0.2. More data is the real fix when it is available.

  3. You add a KV cache. Generation is faster, but at temperature 0 the text differs from the uncached version. List the likely bugs and how you would find the one responsible.

    Answer outline

    Likely causes: the new token is given the wrong position index; the new token’s own key and value are not added to the cache before it attends, so it cannot see itself; the cache from one layer is used in another; or the sequence has grown past the trained context length. Find it by comparing the cached scores with a full forward pass after each token and stopping at the first difference, then comparing layer by layer at that token.

Further reading

  • Andrej Karpathy, “Let’s build GPT: from scratch, in code, spelled out” (video) and the nanoGPT repository: the same model in PyTorch, and the configuration to scale it to 10M parameters.
  • Sebastian Raschka, Build a Large Language Model (From Scratch), chapters 3 to 5: attention, the GPT model and pretraining, built up in PyTorch.
  • Andrej Karpathy, nanochat: the whole pipeline from tokenizer to chat interface in one readable repository. The stretch goal after this chapter.

↑↓ to move↵ to openesc to close