Imports
run firstThe lab file's imports. Run this cell first (or press Run all).
Hands-on lab 03 of 10 · GPT + generation
Run a decoder-only transformer (GPT-2 layout) end to end: token ids in, next-token logits out. Then generate text with greedy decoding and top-k sampling, first by recomputing the whole sequence at every step, then with a KV cache. The cached version must produce the same logits and tokens. The model is untrained (random weights); correctness is what we check.
B batch, N tokens in this call, V vocab, d width, h heads, d_k = d / h. The code keeps nanoGPT's variable names (as build-llm does): T = N, T_past = N_past.
Forward pass
idx [B, N] (int64) x = tok_emb[idx] + pos_emb[pos] [B, N, d] pos = start, start+1, ..., start+N-1 (start = number of cached tokens) for each block (pre-norm, lab 02): x = x + Attn(LN1(x)) x = x + MLP(LN2(x)) logits = LN_f(x) @ tok_emb^T [B, N, V] (the output head shares its weight with the token embedding: "tied")
Causal attention with a KV cache
q, k, v = split(x W_qkv^T + b) each [B, h, N, d_k] k_all = cat(k_past, k), v_all = cat(v_past, v) [B, h, N_past + N, d_k] scores = q k_all^T / sqrt(d_k) [B, h, N, N_past + N] mask: new token i sits at absolute position N_past + i and may see keys j <= N_past + i → causal_mask(N, N_past + N) from lab 01 y = softmax(scores) v_all → merge heads → W_o [B, N, d] return y and the new cache (k_all, v_all)
Why the cache is exact: in a causal model the keys and values of token j depend only on tokens 0..j. Appending a token never changes them, so they can be computed once and reused. Each decode step then costs O(N) instead of re-running all N tokens through the model.
Decoding
greedy: next = argmax(logits[:, -1])
top-k: keep the k largest logits, divide by the temperature, softmax,
sample one index from those k (temperature < 1 sharpens,
> 1 flattens; k = 1 is greedy).
Preview (covered in the next tutorial, Build an LLM)
Editor keys: Tab / Shift+Tab indent and dedent by 4 spaces, Enter keeps the indentation, Shift+Enter runs the cell and moves to the next one.
Cells on this page:
The lab file's imports. Run this cell first (or press Run all).
class GPTConfigcausal_mask(n_q, n_k, device=None)Given (you wrote it in lab 01): [n_q, n_k] bool, True = may attend. The n_q queries are the last n_q of the n_k positions.
attend(q, k, v, mask)Given: lab 01's scaled_dot_product_attention (torch's fused kernel). q [B, h, T_q, d_k], k and v [B, h, T_k, d_k], mask [T_q, T_k] bool → [B, h, T_q, d_k].
class CausalSelfAttention(nn.Module)forward(x, past_kv=None)Args:
x: [B, T, d] the NEW tokens only past_kv: None, or a tuple (k_past, v_past), each [B, h, T_past, d_k]
Returns:
y: [B, T, d] present: (k_all, v_all), each [B, h, T_past + T, d_k]
class Block(nn.Module)forward(x, past_kv=None)Pre-norm block. Returns (x [B, T, d], present) where present comes from attn.
class GPT(nn.Module)forward(idx, past_kvs=None)Args:
idx: [B, T] token ids (only the NEW tokens when a cache is given)
past_kvs: None, or a list with one (k, v) tuple per block
Returns:
logits: [B, T, vocab_size]
presents: list with one (k_all, v_all) tuple per blockgreedy_next(logits)logits [B, V] → next token ids [B] (int64): the most likely token.
sample_top_k(logits, k, temperature=1.0, generator=None)Top-k sampling. logits [B, V] → sampled token ids [B] (int64).
temperature and softmax over those k,torch.multinomial(..., generator=generator),generate(model, idx, max_new_tokens, use_cache=True, top_k=None, temperature=1.0, generator=None)Append max_new_tokens tokens to idx [B, T0]; returns [B, T0 + max_new_tokens].
top_k=None means greedy decoding; otherwise use sample_top_k(..., top_k, temperature, generator).
use_cache=False: every step runs the WHOLE sequence through the model
and uses the last position's logits.
use_cache=True: run the prompt once (the "prefill"), keep the returned
presents, then feed only the newly chosen token each step together with the cache (the "decode" steps).
Experiment here: print shapes, call your functions on small inputs. This cell runs in the same Python process as the cells above, is not part of Run all and is not saved to the lab file (your browser keeps it).