L1 Beginner · Module 1: The LLM forward pass, for inference engineers
1.6Lab: a tiny GPT inference loop in NumPy
Put the whole module together in about 150 lines of NumPy. You build a complete GPT-style decoder, generate with and without a KV cache, and check that the cached loop produces the same tokens much faster.
By the end you will be able to
- ✓Implement a decoder-only transformer forward pass from scratch
- ✓Write a naive generation loop and a prefill-plus-decode loop with a KV cache
- ✓Verify that both loops produce identical tokens
- ✓Measure the speedup and the cache's memory, and explain both
This lab is the module in one file: labs/m01/1.6/tiny_gpt.py builds the model from 1.1–1.3,
runs the loop from 1.4, and adds the cache from 1.5. It needs only
NumPy and runs on any laptop.
python labs/m01/1.6/tiny_gpt.pyThe model
A 4-layer, 128-wide decoder with 4 heads and a byte-level vocabulary of 256: about 0.9 M parameters. The weights are random, so the output is gibberish. That is fine, because this lab is about the mechanics, and mechanics are easier to check when nothing is hidden inside a trained checkpoint.
The forward pass is the layer from 1.2, written out:
def forward(w, cfg, tokens, start_pos=0, cache=None): x = w["tok_emb"][tokens] + w["pos_emb"][start_pos:start_pos + len(tokens)]
for i, layer in enumerate(w["layers"]): h = rms_norm(x, layer["norm1"]) q, k, v = np.split(h @ layer["w_qkv"], 3, axis=-1) q, k, v = (split_heads(t, cfg.n_heads) for t in (q, k, v)) if cache is not None: # append new K/V, attend over all of it c = cache[i] c["k"] = k if c["k"] is None else np.concatenate([c["k"], k], axis=1) c["v"] = v if c["v"] is None else np.concatenate([c["v"], v], axis=1) k, v = c["k"], c["v"] x = x + merge_heads(attention(q, k, v, start_pos)) @ layer["w_o"] x = x + gelu(rms_norm(x, layer["norm2"]) @ layer["w_up"]) @ layer["w_down"]
return rms_norm(x, w["norm_f"]) @ w["tok_emb"].T # tied LM headTwo details are easy to get wrong:
- Positions. With a cache, the new token is at position
start_pos, not 0. Both the positional embedding and the causal mask need it. - The mask with a cache. Queries now cover positions
start_pos … start_pos + Tq − 1, while keys cover0 … Tk − 1. The mask compares absolute positions:
q_pos = q_offset + np.arange(Tq)[:, None]k_pos = np.arange(Tk)[None, :]scores = np.where(k_pos <= q_pos, scores, -np.inf)During decode Tq = 1 and the query is the last position, so the mask allows everything. During prefill it is the usual triangle.
Two loops
def generate_naive(w, cfg, prompt, n_new): tokens = list(prompt) for _ in range(n_new): logits = forward(w, cfg, np.array(tokens)) # the whole sequence, every step tokens.append(int(logits[-1].argmax())) return tokens[len(prompt):]
def generate_cached(w, cfg, prompt, n_new): cache = [{"k": None, "v": None} for _ in range(cfg.n_layers)] logits = forward(w, cfg, np.array(prompt), 0, cache) # prefill out = [int(logits[-1].argmax())] for _ in range(n_new - 1): # decode, one token at a time pos = len(prompt) + len(out) - 1 logits = forward(w, cfg, np.array([out[-1]]), pos, cache) out.append(int(logits[-1].argmax())) return outBoth use greedy decoding, so if the cache is correct they must agree token for token.
Results
tiny GPT: 4 layers, d_model 128, 4 heads, 0.89M paramsprompt: 27 tokens, generating 100 greedy tokens
naive (recompute everything): 7077.0 mskv-cache (prefill + decode) : 185.6 ms -> 38.1x fastersame tokens: TrueKV cache at the end: 882 KiB = 2 (K,V) x 4 layers x 126 positions x 128 dims x 4 bytesfirst 16 generated ids: [101, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47]same tokens: Trueis the important line. A cache that changes the output is a bug, not an optimization.- The speedup grows with length. The naive loop pushes about token-rows through the model in total; the cached loop pushes . The measured ratio is lower than the FLOP ratio because, at this tiny size, Python and NumPy call overhead per step is a big part of the cost. Real engines have the same problem, which is why they use CUDA Graphs (8.7).
- The repeated token
47(/) is what greedy decoding does with random weights: it falls into a loop. A trained model is less prone to this, but greedy repetition is real, and it is one reason for the sampling methods in Module 11.
Exercises
Sources
Check your understanding
0 / 4 answered1.Why must the naive and cached loops produce identical tokens under greedy decoding?
2.In the cached decode step, why is start_pos passed to forward?
3.Why is the measured speedup lower than the FLOP ratio at this model size?
4.What is the problem with growing the cache using np.concatenate?