Python for AI Engineers · Part C · Lesson 25 of 26

Embeddings and attention in code: Q, K, V, masks and a transformer block in NumPy and PyTorch

Attention for Java and JavaScript developers, line by line: token ids to embeddings, scaled dot-product attention by hand in NumPy with numbers you can follow, the causal mask, positions, multi-head attention, the same in PyTorch checked against F.scaled_dot_product_attention, a transformer block and the KV cache.

⏱ 50 min3 exercises that check your codeRuns in your browser

By the end you can

  • Turn token ids into vectors with an embedding table, and explain why nn.Embedding is just a row lookup
  • Write scaled dot-product attention, softmax(Q Kᵀ / √d) V, from scratch in NumPy and follow every number
  • Add the causal mask, positions and multiple heads, and say what each one is for
  • Reproduce it in PyTorch, prove it equals F.scaled_dot_product_attention, and build a transformer block
  • Explain the KV cache and why attention cost grows with the square of the context length
1 / 6

1Token ids to vectors: an embedding is a lookup table

In the tokens lesson you saw that a model never sees text, only token ids: whole numbers such as [0, 1, 2]. The very first thing a model does is swap each id for a list of numbers, a vector, that it can do maths on. That vector is the token's embedding.

The mechanism is almost disappointing: a table with one row per token in the vocabulary. Row i is the vector for token i. Turning ids into vectors means picking rows, nothing more. In Java terms it is a double[][] table and table[id]. table[ids] with a whole array of ids is NumPy's fancy indexing from the NumPy lesson: it picks several rows at once, in order.

Here the table is random. In a real model it starts random too and training moves the rows so that tokens used in similar ways end up with similar vectors. d_model is the width of every vector: 4 here, 4,096 in an 8B model. np.set_printoptions(precision=2, suppress=True) only makes NumPy print 2 decimals and no scientific notation, so the numbers are easy to read.

Try it: edit and run
import numpy as np

np.set_printoptions(precision=2, suppress=True)

vocab = {"the": 0, "cat": 1, "sat": 2, "mat": 3, "on": 4}
d_model = 4                                  # numbers per token

rng = np.random.default_rng(0)               # seeded, so you see the same numbers
table = rng.normal(size=(len(vocab), d_model)).round(2)
print("table shape:", table.shape)           # one row per token in the vocabulary

ids = np.array([vocab[w] for w in "the cat sat".split()])
print("ids:", ids)

x = table[ids]                               # the whole "embedding layer": pick rows
print("x shape:", x.shape)
print(x)
print("row for 'cat' is table[1]:", np.array_equal(x[1], table[1]))
Expected output
table shape: (5, 4)
ids: [0 1 2]
x shape: (3, 4)
[[ 0.13 -0.13  0.64  0.1 ]
 [-0.54  0.36  1.3   0.95]
 [-0.7  -1.27 -0.62  0.04]]
row for 'cat' is table[1]: True

Each row of x is one token: shape (3, 4) means 3 tokens, 4 numbers each. Every layer after this point works on that (tokens, d_model) grid. The vectors in the embeddings concept page that power search are a related idea, but those come from a whole model reading the text; this table is only the first layer of a model, one fixed vector per token id.

Tip The table is big. A 128,000-token vocabulary times 4,096 numbers is about 524 million numbers, a noticeable share of a small model. That is why vocabulary size is a design decision, not a detail.

2Scaled dot-product attention, by hand

Embedding a token gives the same vector whatever sentence it is in. Attention is the step that lets each token look at the other tokens and pull in what matters, so "it" can borrow meaning from "the cat". The attention concept page explains the idea; here you write it.

Every token gets three vectors. Its query q says what it is looking for. Its key k says what it offers to be found by. Its value v is what it passes on if chosen. Stacked one row per token they are the matrices Q, K and V. (A real model computes them from x with three learned weight matrices, as section 5 shows; here they are typed in so you can check the maths.)

For one query: take the dot product with every key (bigger means a better match), divide by √d (d is the width of q, 4 here, so divide by 2), turn the scores into weights with softmax (exp of each, divided by the sum, so they are positive and add up to 1), and return the weighted average of the value rows. All queries at once is the famous one-liner softmax(Q Kᵀ / √d) V. K.T is the transpose of K (rows become columns), so Q @ K.T is every query dotted with every key.

Try it: edit and run
import numpy as np

np.set_printoptions(precision=2, suppress=True)

# One row per token: "the", "cat", "sat". Width d = 4, so sqrt(d) = 2.
Q = np.array([[1., 0., 0., 0.],      # what each token is looking for
              [0., 1., 0., 0.],
              [0., 2., 0., 1.]])
K = np.array([[1., 0., 0., 0.],      # what each token offers to be found by
              [0., 2., 0., 0.],
              [0., 0., 1., 1.]])
V = np.array([[1., 0.],              # what each token passes on (any width; 2 here)
              [0., 1.],
              [1., 1.]])

# Step by step for one query: the token "sat" (row 2)
q = Q[2]
raw = K @ q                          # dot product of q with every key
print("raw scores:", raw)
scaled = raw / np.sqrt(Q.shape[1])   # divide by sqrt(d) = 2
print("scaled:    ", scaled)
w = np.exp(scaled) / np.exp(scaled).sum()   # softmax: positive, sums to 1
print("weights:   ", w, "sum", round(float(w.sum()), 2))
print("output:    ", w @ V)          # weighted mix of the value rows


def softmax(s):
    s = s - s.max(axis=-1, keepdims=True)    # same result, but exp never overflows
    e = np.exp(s)
    return e / e.sum(axis=-1, keepdims=True)


def attention(Q, K, V):
    d = Q.shape[-1]
    scores = Q @ K.T / np.sqrt(d)    # (3, 3): every query against every key
    weights = softmax(scores)        # each row sums to 1
    return weights @ V, weights


out, weights = attention(Q, K, V)
print("all weights:")
print(weights)
print("all outputs:")
print(out)
Expected output
raw scores: [0. 4. 1.]
scaled:     [0.  2.  0.5]
weights:    [0.1  0.74 0.16] sum 1.0
output:     [0.26 0.9 ]
all weights:
[[0.45 0.27 0.27]
 [0.21 0.58 0.21]
 [0.1  0.74 0.16]]
all outputs:
[[0.73 0.55]
 [0.42 0.79]
 [0.26 0.9 ]]

Follow the token "sat" (row 2): its query [0, 2, 0, 1] dotted with the three keys gives 0, 4 and 1. Divided by 2: 0, 2, 0.5. Softmax makes those 0.10, 0.74 and 0.16: "sat" pays 74% of its attention to "cat". The output is 0.10 × [1, 0] + 0.74 × [0, 1] + 0.16 × [1, 1] = [0.26, 0.90]. The last row of the full matrix is exactly that, so the function does the same sum for every row at once.

s - s.max(axis=-1, keepdims=True) subtracts each row's largest score before exp. The softmax result is mathematically identical, but exp(1000) no longer overflows to infinity. axis=-1 means "along the last dimension" (across each row), and keepdims=True keeps the result as a column so it broadcasts back over the row.

Tip Why divide by √d? A dot product of two random vectors of width d grows roughly like √d. With d = 128 the raw scores would be large, softmax would put almost all the weight on one token, and the gradients during training would vanish. Dividing by √d keeps the scores in a range where softmax stays soft.

3The causal mask: no peeking at the future

A language model is trained to predict the next token. If token 1 could see token 2 while learning to predict token 2, it would just copy it. So in an LLM every token may only attend to itself and earlier tokens. This is the causal mask.

The trick is to set the score of every future pair to minus infinity before softmax. exp(-inf) is exactly 0, so those tokens get weight 0 and the remaining weights still add up to 1. np.triu(..., k=1) gives True strictly above the diagonal, which is exactly "key comes after query". np.where(cond, a, b) picks a where cond is true and b elsewhere, like a vectorised cond ? a : b.

Try it: edit and run
import numpy as np

np.set_printoptions(precision=2, suppress=True)

Q = np.array([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 2., 0., 1.]])
K = np.array([[1., 0., 0., 0.], [0., 2., 0., 0.], [0., 0., 1., 1.]])
V = np.array([[1., 0.], [0., 1.], [1., 1.]])


def softmax(s):
    s = s - s.max(axis=-1, keepdims=True)
    e = np.exp(s)
    return e / e.sum(axis=-1, keepdims=True)


def causal_attention(Q, K, V):
    n, d = Q.shape
    scores = Q @ K.T / np.sqrt(d)
    future = np.triu(np.ones((n, n), dtype=bool), k=1)   # True above the diagonal
    scores = np.where(future, -np.inf, scores)           # a future token gets -infinity
    weights = softmax(scores)                            # exp(-inf) = 0: weight 0
    return weights @ V, weights


print(np.triu(np.ones((3, 3), dtype=bool), k=1))
out, weights = causal_attention(Q, K, V)
print(weights)
print(out)
Expected output
[[False  True  True]
 [False False  True]
 [False False False]]
[[1.   0.   0.  ]
 [0.27 0.73 0.  ]
 [0.1  0.74 0.16]]
[[1.   0.  ]
 [0.27 0.73]
 [0.26 0.9 ]]

Row 0 ("the") can only see itself, so its weight is 1 and its output is just its own value [1, 0]. Row 1 sees "the" and "cat": scores 0 and 1 become 0.27 and 0.73. Row 2 can already see everything before it, so it is unchanged from the previous section. Because of the mask, adding a token at the end never changes the outputs of the tokens before it. Section 8 uses exactly that fact to make generation fast.

Watch out Masking with 0 instead of -inf does not mask anything: a score of 0 still becomes exp(0) = 1 before normalising, so the future token keeps a real share of the weight. Mask the scores with -inf, never the weights with 0.

4Positions: attention cannot see word order on its own

Look again at the formula: nothing in it knows where a token is. Each token is scored against every other token by content alone. Shuffle the input and you get the same outputs, just shuffled. So without help, "dog bites man" and "man bites dog" look the same to the model.

The fix is to mix position into each vector. The example below does it the way GPT-2 did: a second table, one learned vector per position (0, 1, 2, ...), added to the token embedding. x @ Wq is how the query really gets made: the token vector times a learned weight matrix. (There is no causal mask in this box: without one, attention is completely blind to order. A causal mask leaks a little order information, because each token sees a different number of tokens, but far too little to rely on, so every model still adds positions.)

Try it: edit and run
import numpy as np

np.set_printoptions(precision=2, suppress=True)
rng = np.random.default_rng(1)
d = 4

vocab = {"dog": 0, "bites": 1, "man": 2}
table = rng.normal(size=(3, d))              # token embeddings
Wq, Wk, Wv = (rng.normal(size=(d, d)) for _ in range(3))
pos_table = rng.normal(size=(8, d))          # one learned vector per position 0..7


def softmax(s):
    e = np.exp(s - s.max(axis=-1, keepdims=True))
    return e / e.sum(axis=-1, keepdims=True)


def self_attention(x):
    Q, K, V = x @ Wq, x @ Wk, x @ Wv         # every token makes its own q, k and v
    return softmax(Q @ K.T / np.sqrt(d)) @ V


def embed(sentence, with_positions):
    ids = [vocab[w] for w in sentence.split()]
    x = table[ids]
    if with_positions:
        x = x + pos_table[:len(ids)]         # add the vector for position 0, 1, 2
    return x


for with_positions in (False, True):
    a = self_attention(embed("dog bites man", with_positions))
    b = self_attention(embed("man bites dog", with_positions))
    print("positions:", with_positions)
    print("  'dog' in sentence 1:", a[0])    # dog is word 0 here...
    print("  'dog' in sentence 2:", b[2])    # ...and word 2 here
    print("  same?", np.allclose(a[0], b[2]))
Expected output
positions: False
  'dog' in sentence 1: [-0.48  0.63  2.15 -0.79]
  'dog' in sentence 2: [-0.48  0.63  2.15 -0.79]
  same? True
positions: True
  'dog' in sentence 1: [-2.07  1.39  2.8   0.36]
  'dog' in sentence 2: [-0.91  1.03  0.07  0.52]
  same? False

Without positions, "dog" gets exactly the same output in both sentences, even though it is the one biting in the first and the one bitten in the second. With positions added the outputs differ, so later layers can tell the two meanings apart. Most current open models (Llama, Qwen, Mistral) use RoPE instead of a position table: it rotates each query and key by an angle that depends on the position, so the score between two tokens depends on how far apart they are. Different method, same job.

Tip A learned position table has a fixed number of rows, so the model simply cannot accept a longer input. That is one reason context length is a hard limit you read off a model card, not a soft suggestion.

5Multi-head attention: several lookups side by side

One attention computes one set of weights per token: one idea of "what matters". Real models want several at once: one head might track the subject of the sentence, another the previous word, another a matching bracket. Multi-head attention splits the width d_model into n_heads slices of head_dim numbers and runs attention on each slice separately.

The only new code is reshaping. reshape(n, n_heads, head_dim) cuts each token's row of 4 numbers into 2 pieces of 2. transpose(1, 0, 2) reorders the dimensions to (n_heads, n, head_dim), so that each head holds its own little (tokens, head_dim) matrix and @ works on all heads at once. NumPy's @ on 3D arrays multiplies matching 2D matrices, one per head. At the end the heads are glued back side by side and Wo mixes them.

Try it: edit and run
import numpy as np

np.set_printoptions(precision=2, suppress=True)
rng = np.random.default_rng(2)

n, d_model, n_heads = 3, 4, 2
head_dim = d_model // n_heads                # each head works on 2 of the 4 numbers
x = rng.normal(size=(n, d_model))            # 3 tokens after embedding + positions
Wq, Wk, Wv, Wo = (rng.normal(size=(d_model, d_model)) for _ in range(4))


def softmax(s):
    e = np.exp(s - s.max(axis=-1, keepdims=True))
    return e / e.sum(axis=-1, keepdims=True)


def split_heads(t):                          # (n, d_model) -> (n_heads, n, head_dim)
    return t.reshape(n, n_heads, head_dim).transpose(1, 0, 2)


def multi_head_attention(x):
    Q, K, V = split_heads(x @ Wq), split_heads(x @ Wk), split_heads(x @ Wv)
    scores = Q @ K.transpose(0, 2, 1) / np.sqrt(head_dim)   # (n_heads, n, n)
    future = np.triu(np.ones((n, n), dtype=bool), k=1)
    weights = softmax(np.where(future, -np.inf, scores))    # mask applies to every head
    out = weights @ V                                       # (n_heads, n, head_dim)
    out = out.transpose(1, 0, 2).reshape(n, d_model)        # glue the heads back side by side
    return out @ Wo, weights                                # Wo mixes the heads together


out, weights = multi_head_attention(x)
print("Q per head:", split_heads(x @ Wq).shape)
print("weights:", weights.shape)
print("head 0 weights:")
print(weights[0])
print("head 1 weights:")
print(weights[1])
print("output:", out.shape)
Expected output
Q per head: (2, 3, 2)
weights: (2, 3, 3)
head 0 weights:
[[1.   0.   0.  ]
 [0.99 0.01 0.  ]
 [0.3  0.32 0.38]]
head 1 weights:
[[1.   0.   0.  ]
 [0.02 0.98 0.  ]
 [0.85 0.06 0.09]]
output: (3, 4)

The two heads see the same three tokens but weigh them very differently: for the last token, head 0 spreads its attention evenly while head 1 puts 85% on the first token. That is the point of having several. The total work is the same as one big head of width 4, because each head is only 2 wide. Real models are the same shape, only bigger: an 8B Llama has 32 heads of 128 numbers each in every one of its 32 layers.

Watch out Splitting heads with reshape(n_heads, n, head_dim) directly, without the transpose, runs without an error and produces nonsense: it slices the rows in the wrong order, mixing numbers from different tokens into one head. Reshape to (n, n_heads, head_dim) first, then transpose.

6The same in PyTorch, checked against the built-in

PyTorch cannot run in these browser boxes, so this is a file you run on your machine (see the PyTorch basics lesson for installing it, including the small CPU-only build on Linux). Create a project and add PyTorch, pinned so your output matches this page:

Run
uv init attention-demo --python 3.12
cd attention-demo
uv add torch==2.15.0 numpy==2.5.5
You should see
 + numpy==2.5.5
 + torch==2.15.0
 (plus a few helper packages such as sympy, networkx and jinja2)
attention_check.py
import math

import torch
import torch.nn as nn
import torch.nn.functional as F

torch.manual_seed(0)

emb = nn.Embedding(num_embeddings=10, embedding_dim=8)   # 10 tokens in the vocabulary, 8 numbers each
print(emb.weight.shape)

ids = torch.tensor([[3, 1, 4, 1]])           # a batch of 1 sequence, 4 token ids
x = emb(ids)
print(x.shape)
print(torch.equal(x[0], emb.weight[ids[0]]))  # it really is a row lookup


def attention_by_hand(q, k, v):
    d = q.shape[-1]
    scores = q @ k.transpose(-2, -1) / math.sqrt(d)
    n = q.shape[-2]
    future = torch.triu(torch.ones(n, n, dtype=torch.bool), diagonal=1)
    scores = scores.masked_fill(future, float("-inf"))
    return torch.softmax(scores, dim=-1) @ v


batch, heads, n, head_dim = 1, 2, 4, 4
q = torch.randn(batch, heads, n, head_dim)
k = torch.randn(batch, heads, n, head_dim)
v = torch.randn(batch, heads, n, head_dim)

mine = attention_by_hand(q, k, v)
theirs = F.scaled_dot_product_attention(q, k, v, is_causal=True)
print(mine.shape, theirs.shape)
print(torch.allclose(mine, theirs, atol=1e-6))

keep = torch.tril(torch.ones(n, n, dtype=torch.bool))     # True = this pair MAY attend
masked = F.scaled_dot_product_attention(q, k, v, attn_mask=keep)
print(torch.allclose(masked, theirs, atol=1e-6))
  1. torch.nn.functional, imported as F by convention: the stateless functions (no weights), such as softmax and attention.line 5
  2. nn.Embedding holds a (10, 8) weight table that training updates. Same idea as the NumPy table, but learnable.line 9
  3. PyTorch layers expect a **batch** dimension first, so one sentence is [[...]]: shape (1, 4).line 12
  4. Calling the layer and indexing its weight table give exactly the same tensor: nn.Embedding is a row lookup.line 15
  5. transpose(-2, -1) swaps the last two dimensions, the PyTorch spelling of K.T that also works with batch and head dimensions in front.line 20
  6. masked_fill(mask, value) writes -inf wherever the mask is True: the future pairs, as in section 3.line 23
  7. The layout PyTorch expects for attention: (batch, heads, tokens, head_dim).line 27
  8. The built-in: same maths, but when one is available it picks a fast fused kernel (such as FlashAttention on a GPU) that avoids storing the whole score matrix.line 33
  9. allclose compares with a small tolerance, because a fused kernel adds the numbers in a different order and float32 rounding differs in the last digits.line 35
  10. A **boolean** attn_mask in this function means the **opposite** of masked_fill: True marks pairs that are **allowed**. The lower triangle (tril) is the causal pattern.line 37
Output
torch.Size([10, 8])
torch.Size([1, 4, 8])
True
torch.Size([1, 2, 4, 4]) torch.Size([1, 2, 4, 4])
True
True

Run it with uv run python attention_check.py. Every comparison prints True: your eight lines and PyTorch's built-in compute the same thing. In real code always use F.scaled_dot_product_attention. On a GPU it can be several times faster and use far less memory, because its fused kernels avoid building the full (tokens × tokens) score matrix.

Two arguments worth knowing: scale= overrides the 1 / √d factor, and enable_gqa=True allows fewer key and value heads than query heads (grouped-query attention, which Llama 3 uses to shrink the KV cache from section 8).

Watch out Passing both attn_mask= and is_causal=True raises RuntimeError: _scaled_dot_product_attention: Explicit attn_mask should not be set when is_causal=True. Pick one. And mind the boolean mask direction: True means "may attend" here, but "hide this" in masked_fill.

7A transformer block, and a tiny language model

A transformer is the same block stacked many times. Each block has two parts, each wrapped in a residual connection (x = x + part(x): the block adds a correction to its input instead of replacing it, which keeps very deep stacks trainable): attention, where tokens look at each other, then a small MLP (two Linear layers with an activation between them), where each token is processed on its own. Each part first normalises its input with LayerNorm, which rescales every token vector to mean 0 and variance 1 so the numbers stay in a stable range.

An nn.Module is PyTorch's base class for anything with weights: you create the layers in __init__ and say how data flows in forward. Calling model(ids) runs forward. The model below is a complete (untrained) GPT-style language model in about 50 lines: embeddings plus positions, two blocks, a final norm, and a Linear "head" that gives a score (logit) for every token in the vocabulary.

tiny_lm.py
import torch
import torch.nn as nn
import torch.nn.functional as F


class CausalSelfAttention(nn.Module):
    def __init__(self, d_model: int, n_heads: int):
        super().__init__()
        self.n_heads = n_heads
        self.qkv = nn.Linear(d_model, 3 * d_model)   # Wq, Wk and Wv in one matrix
        self.out = nn.Linear(d_model, d_model)       # Wo: mixes the heads

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        b, n, d = x.shape                            # batch, tokens, d_model
        q, k, v = self.qkv(x).split(d, dim=-1)       # three (b, n, d) tensors
        h = self.n_heads                             # (b, n, d) -> (b, h, n, d // h)
        q, k, v = (t.view(b, n, h, d // h).transpose(1, 2) for t in (q, k, v))
        y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
        y = y.transpose(1, 2).reshape(b, n, d)       # glue the heads back together
        return self.out(y)


class Block(nn.Module):
    def __init__(self, d_model: int, n_heads: int):
        super().__init__()
        self.norm1 = nn.LayerNorm(d_model)
        self.attn = CausalSelfAttention(d_model, n_heads)
        self.norm2 = nn.LayerNorm(d_model)
        self.mlp = nn.Sequential(                    # the feed-forward part
            nn.Linear(d_model, 4 * d_model),
            nn.GELU(),
            nn.Linear(4 * d_model, d_model),
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = x + self.attn(self.norm1(x))             # tokens look at each other
        x = x + self.mlp(self.norm2(x))              # each token thinks on its own
        return x


class TinyLM(nn.Module):
    def __init__(self, vocab: int, d_model: int, n_heads: int, n_layers: int, max_len: int):
        super().__init__()
        self.tok = nn.Embedding(vocab, d_model)
        self.pos = nn.Embedding(max_len, d_model)    # learned positions, like GPT-2
        self.blocks = nn.ModuleList([Block(d_model, n_heads) for _ in range(n_layers)])
        self.norm = nn.LayerNorm(d_model)
        self.head = nn.Linear(d_model, vocab)        # a score for every token in the vocab

    def forward(self, ids: torch.Tensor) -> torch.Tensor:
        n = ids.shape[1]
        x = self.tok(ids) + self.pos(torch.arange(n))
        for block in self.blocks:
            x = block(x)
        return self.head(self.norm(x))               # (batch, n, vocab): the logits


torch.manual_seed(0)
model = TinyLM(vocab=100, d_model=32, n_heads=4, n_layers=2, max_len=64)
print(sum(p.numel() for p in model.parameters()), "parameters")

model.eval()
with torch.no_grad():
    a = model(torch.tensor([[5, 17, 42, 8]]))
    b = model(torch.tensor([[5, 17, 42, 99]]))       # only the last token differs
print(a.shape)
print("next token guess:", a[0, -1].argmax().item())
print("earlier positions unchanged:", torch.allclose(a[:, :3], b[:, :3]))
print("last position changed:", not torch.allclose(a[:, 3], b[:, 3]))
  1. super().__init__() must come first in every module: it sets up the bookkeeping that finds the weights of the layers you assign below.line 8
  2. One Linear that outputs 3 * d_model numbers is the same as three separate Wq, Wk, Wv matrices, just one bigger multiplication.line 10
  3. split(d, dim=-1) cuts the last dimension into pieces of d: the queries, keys and values.line 15
  4. Split into heads exactly as in section 5: view cuts each row into h pieces, transpose(1, 2) moves the head dimension in front of the tokens.line 17
  5. Causal multi-head attention in one call. The mask is applied for you.line 18
  6. Back to (b, n, d). reshape (not view) because the transpose left the memory out of order.line 19
  7. GELU is a smooth version of ReLU (negative inputs give roughly 0), the activation GPT-2 used.line 31
  8. Pre-norm: normalise, attend, then add the result back onto x. This is the residual connection.line 36
  9. nn.ModuleList is a list PyTorch can see inside, so the weights of every block are registered. A plain Python list would hide them.line 46
  10. torch.arange(n) is [0, 1, ..., n-1]: one position id per token, looked up in the position table and added.line 52
  11. One logit per vocabulary token, for every position. The last position's logits pick the next token.line 55
  12. eval() switches layers such as dropout to inference mode. torch.no_grad() skips gradient bookkeeping, since nothing is trained here.line 62
  13. Proof the mask works: changing the last token leaves every earlier position's output untouched.line 68
Output
34020 parameters
torch.Size([1, 4, 100])
next token guess: 68
earlier positions unchanged: True
last position changed: True

Run it with uv run python tiny_lm.py. The "next token guess" (argmax, the index of the highest logit) is meaningless because the weights are random; training them to predict the next token over billions of tokens is what turns this exact code into a real model. The previous lesson has the training loop.

Real LLMs use this same skeleton with a few upgrades: RMSNorm instead of LayerNorm (PyTorch has nn.RMSNorm), a gated MLP called SwiGLU, RoPE instead of the position table, and fewer key and value heads (GQA). The sizes are what change most: Llama 3.1 8B is 32 blocks of width 4,096, about 8 billion parameters against our 34,020.

Tip Counting parameters with sum(p.numel() for p in model.parameters()) is the first thing to do with any model. Multiply by bytes per number (4 for float32, 2 for bf16) and you know how much memory just the weights need.

8Generation, the KV cache and the n² cost

An LLM writes one token at a time: run the model, pick a token, append it, run again. Naively each step would recompute keys and values for the whole text so far. But the causal mask means earlier tokens never change when a new one is added, so their keys and values never change either. The KV cache stores them: each step computes q, k and v for the new token only, appends k and v to the cache, and scores the one new query against all cached keys.

The box generates 5 steps with a cache and checks the result against running full causal attention over all 5 tokens at once. Then it prints the size of the score matrix for longer prompts. {n * n:>10,} is an f-string format: right-aligned in 10 characters, with thousands separators.

Try it: edit and run
import numpy as np

rng = np.random.default_rng(3)
d = 4
Wq, Wk, Wv = (rng.normal(size=(d, d)) for _ in range(3))
tokens = rng.normal(size=(5, d))             # 5 tokens, already embedded


def softmax(s):
    e = np.exp(s - s.max(axis=-1, keepdims=True))
    return e / e.sum(axis=-1, keepdims=True)


def full_causal(x):                          # the whole sequence at once
    Q, K, V = x @ Wq, x @ Wk, x @ Wv
    n = len(x)
    scores = Q @ K.T / np.sqrt(d)
    scores = np.where(np.triu(np.ones((n, n), dtype=bool), k=1), -np.inf, scores)
    return softmax(scores) @ V


k_cache, v_cache, outs = [], [], []
for t in range(len(tokens)):                 # generation: one new token per step
    x = tokens[t]
    k_cache.append(x @ Wk)                   # only the NEW token's key and value
    v_cache.append(x @ Wv)                   # are computed; older ones are reused
    q = x @ Wq
    K, V = np.array(k_cache), np.array(v_cache)
    outs.append(softmax(K @ q / np.sqrt(d)) @ V)   # one query against t + 1 keys
    print(f"step {t}: keys in cache = {len(k_cache)}")

print("same as full causal attention:", np.allclose(np.array(outs), full_causal(tokens)))

for n in (1_000, 2_000, 4_000, 8_000):
    print(f"{n:>5} tokens: score matrix {n * n:>10,} numbers")
Expected output
step 0: keys in cache = 1
step 1: keys in cache = 2
step 2: keys in cache = 3
step 3: keys in cache = 4
step 4: keys in cache = 5
same as full causal attention: True
 1000 tokens: score matrix  1,000,000 numbers
 2000 tokens: score matrix  4,000,000 numbers
 4000 tokens: score matrix 16,000,000 numbers
 8000 tokens: score matrix 64,000,000 numbers

Same numbers, much less work per step: step t scores 1 query against t + 1 keys instead of rebuilding everything. That is why, in a chat app, the first token takes the longest: the model must process the whole prompt (the prefill, which is the full n × n attention and fills the cache). After that each new token is cheap (the decode phase), as the how LLMs work page describes.

The second part shows the cost of that prefill: doubling the prompt from 4,000 to 8,000 tokens makes the score matrix 4 times bigger, per head and per layer. That is the O(n²) in "attention is quadratic", and the reason long-context calls cost more and stuff-everything-in prompts are slower than a good RAG retrieval of the few chunks that matter.

The cache costs memory instead: for every token it keeps a key and a value per layer and per key/value head. For Llama 3.1 8B (32 layers, 8 key/value heads of 128 numbers, 2 bytes each in bf16) that is 2 × 32 × 8 × 128 × 2 = 131,072 bytes, 128 KB per token, so a full 128K-token context needs 16 GB of cache on top of the weights. Exercise 3 has you write that calculation.

Watch out In PyTorch, F.scaled_dot_product_attention(q, k, v, is_causal=True) with one new query and a cache of many keys is wrong: the built-in causal mask is aligned to the top-left corner, so the single query may only see key 0. When decoding with a cache, the new token is allowed to see every cached key, so pass is_causal=False (or no mask) there.

Common mistakes

  • Forgetting to divide by √d. The code still runs, but with real widths softmax becomes almost one-hot and training stalls.
  • Masking with 0 instead of -inf, or masking the weights after softmax instead of the scores before it. The future still leaks in, or the rows no longer sum to 1.
  • Taking softmax along the wrong axis. Each row (one query against all keys) must sum to 1: use axis=-1 in NumPy and dim=-1 in PyTorch.
  • Splitting heads with a plain reshape and no transpose, which silently mixes numbers from different tokens into one head.
  • Mixing up PyTorch's boolean attn_mask (True means allowed) with masked_fill (True means hidden), or passing attn_mask together with is_causal=True.
  • Using is_causal=True for a single new query against a KV cache: the top-left aligned mask lets it see only the first key.

Practice

Write the code, then press Check. Your work is saved in this browser.

1A softmax that never overflows

softmax(s) must turn every row of s into weights that are positive and sum to 1, and it must still work when the scores are huge ([1000, 1000] must give [0.5, 0.5], not nan). It should accept a 1D array (one row) or a 2D array (many rows).

Exercise
import numpy as np


def softmax(s):
    e = np.exp(s)
    return e / e.sum(axis=-1, keepdims=True)
Hint

Subtract each row's maximum first: `s = s - s.max(axis=-1, keepdims=True)`. Softmax gives the same answer, and the biggest value becomes `exp(0) = 1`.

2Add the causal mask

causal_attention(Q, K, V) computes attention but forgets the causal mask, so tokens can see the future. Fix it so token i only attends to tokens 0..i, and return the output (shape (n, width of V)).

Exercise
import numpy as np


def softmax(s):
    e = np.exp(s - s.max(axis=-1, keepdims=True))
    return e / e.sum(axis=-1, keepdims=True)


def causal_attention(Q, K, V):
    d = Q.shape[-1]
    scores = Q @ K.T / np.sqrt(d)
    return softmax(scores) @ V
Hint

Build `future = np.triu(np.ones((n, n), dtype=bool), k=1)` with `n = len(Q)`, then `scores = np.where(future, -np.inf, scores)` before the softmax.

3How big is the KV cache?

Write kv_cache_bytes(layers, kv_heads, head_dim, tokens, bytes_per_number=2): the bytes a KV cache needs. For every token, every layer stores a key and a value vector of head_dim numbers for each key/value head. The starter forgets something.

Exercise
def kv_cache_bytes(layers, kv_heads, head_dim, tokens, bytes_per_number=2):
    return layers * kv_heads * head_dim * tokens * bytes_per_number


print(kv_cache_bytes(32, 8, 128, 1))   # Llama 3.1 8B, one token
Hint

There are two tensors per layer, keys **and** values: multiply by 2.

Interview questions

Q1Write scaled dot-product attention and explain each step.

softmax(Q Kᵀ / √d) V. Each token has a query, key and value (learned projections of its embedding). Q Kᵀ scores every query against every key, dividing by √d keeps the scores from growing with the width, softmax along each row turns scores into weights that sum to 1, and multiplying by V gives each token a weighted average of the value vectors.

Q2Why divide by the square root of d?

The dot product of two random vectors of width d has a spread of about √d. Without scaling, large widths push scores so far apart that softmax becomes almost one-hot, so the gradients for all other tokens are near zero and training slows or stalls. Dividing by √d keeps the variance around 1.

Q3What is the causal mask and how is it implemented?

It stops a token attending to later tokens, so a model trained to predict the next token cannot see it. Scores above the diagonal are set to minus infinity before softmax, which makes their weights exactly 0 while each row still sums to 1. In PyTorch: is_causal=True in F.scaled_dot_product_attention.

Q4Why multiple heads?

One head produces one weighting per token. Several heads, each on a slice of the width with its own projections, can track different relationships at the same time (syntax, coreference, position). The total cost is about the same as one wide head; an output projection mixes the heads back together.

Q5What is the KV cache, and what does it trade?

During generation, the keys and values of earlier tokens never change because of the causal mask, so they are stored and reused; each step only computes the new token's q, k, v and scores one query against the cache. It trades memory for compute: 2 × layers × kv_heads × head_dim × bytes per token, which is why long contexts need lots of GPU memory and why GQA shares key/value heads.

Q6Why is attention O(n²) and what does that mean in practice?

Every token is scored against every earlier token, so the prefill of an n-token prompt computes about n² scores per head per layer. Doubling the prompt roughly quadruples that work, which shows up as slower time to first token and higher cost for long prompts. Fused kernels like FlashAttention avoid storing the n × n matrix but still do the n² work.