Unit 4 of 9

Attention and the transformer block

  • 60 min
  • Includes a browser lab

What you’ll learn

  • Compute a row of causal attention by hand: scores, scaling, mask, softmax, and the weighted mix of values.
  • Explain why the causal mask sets future scores to negative infinity, and what leaks when it does not.
  • Follow the tensor shapes of multi-head and grouped-query attention in Llama 3.1 8B, from 4,096 features to 32 heads of 128.
  • Trace a decoder block through its norms, attention, SwiGLU MLP, and two residual adds, and count where its 218 million parameters live.
  • Estimate how attention work per token grows with context length, and explain why fast kernels never store the full score matrix.

What happens inside each layer

Profile Llama 3.1 8B serving a chat and you see the same pattern in each of its 32 layers: a few large matrix multiplications whose cost per token never changes, and one attention step whose cost grows as the conversation gets longer. At 1,000 tokens of context, attention is a small slice of the work. At 100,000 tokens, it is most of it.

Both parts come from the decoder block, the unit a language model repeats layer after layer. Attention lets each token gather information from the tokens before it. A multilayer perceptron (MLP), a pair of large matrix multiplications with a nonlinearity between them, then transforms each token on its own. You met the matrix multiplications as shapes in the tensors lesson; this lesson opens the block up.

By the end you will be able to compute attention by hand, read every tensor shape in a real model’s attention layer, say where Llama 3.1 8B keeps its 8.03 billion parameters, and predict how attention’s cost changes with context length. The KV cache, batching, and quantization lessons all build on these numbers.

Attention in plain words: queries, keys, and values

Take the prompt “The sky is blue”. To predict what comes after “is”, the model needs to know what is being described, so the vector at the position of “is” should pull in information from “sky”. Attention is how it does that, and it works like a soft lookup table.

Each position turns its vector into three smaller vectors using three learned weight matrices. The query describes what this position is looking for. The key describes what this position offers to others. The value is the information this position hands over when someone attends to it. A lookup compares one query with every visible key; a good match earns a high score.

In a dictionary, a lookup returns the one entry whose key matches exactly. Attention instead returns a blend: it turns the scores into weights that are positive and add up to 1, and outputs the weighted average of the values. A query that matches “sky” strongly gets mostly the value of “sky”, plus a little of everything else it can see.

Written as one formula for a whole sequence, with Q, K, and V holding one row per token and d the length of each query and key vector (the head size):

Scaled dot-product attention
Attention(Q, K, V) = softmax(Q × Kᵀ / √d + mask) × V

Q × Kᵀ    one score for every (query, key) pair
/ √d      keeps scores in a range softmax handles well
mask      0 for visible keys, −∞ for keys this query may not see
softmax   turns each row of scores into weights that sum to 1
× V       mixes the value vectors with those weights

The causal mask is what makes this a decoder: position i may attend only to positions 0 through i, never to later ones. The grid below shows the result for our four-token prompt. Each row is one query’s weights, and the crossed-out cells are the future keys the mask hides.

querykeyTheskyisblueThe1.001.00maskedmaskedmaskedsky0.380.380.620.62maskedmaskedis0.040.040.840.840.110.11maskedblue0.050.050.600.600.130.130.220.22
Causal attention weights for “The sky is blue”, computed from the small example in the next section. Each row sums to 1 (up to rounding), and no row puts weight on a later token.

The first row is always exactly 1, because the first token can see only itself. The last row matters most for generation: its output feeds the prediction of the next token.

Self-attention explained: how transformers know what 'it' means · Watch on YouTube

Compute causal attention step by step

Here is the computation behind the grid, with a head size of 4 so every number fits on a line. The query, key, and value vectors below are made up for the example; in a real model they come from multiplying each token’s vector by learned weight matrices.

Illustrative vectors for one attention head (head size 4)
TokenQueryKeyValue
The (position 0)[1, 0, 1, 0][1, 0, 1, 0][2, 0, 0, 1]
sky (position 1)[1, 1, 0, 0][0, 2, 0, 1][0, 4, 1, 0]
is (position 2)[0, 2, 0, 2][1, 1, 0, 0][1, 1, 3, 0]
blue (position 3)[0, 2, 0, 1][0, 1, 1, 1][0, 2, 0, 4]

Follow the row for “is”, position 2. A dot product multiplies matching entries of two vectors and adds them up, so the query [0, 2, 0, 2] scores 0 × 0 + 2 × 2 + 0 × 0 + 2 × 1 = 6 against the key of “sky”. The scale is √4 = 2, the future key is masked, and softmax exponentiates each score and divides by the total.

The row for “is”, step by step

  1. Dot products with The, sky, is, blue0, 6, 2, 4
  2. Divide by √4 = 20, 3, 1, 2
  3. Apply the causal mask0, 3, 1, −∞
  4. Exponentiate1, 20.09, 2.72, 0 (total 23.80)
  5. Divide by the total0.042, 0.844, 0.114, 0
  6. Mix the values0.042 × [2, 0, 0, 1] + 0.844 × [0, 4, 1, 0] + 0.114 × [1, 1, 3, 0]

ResultOutput for "is" = [0.20, 3.49, 1.19, 0.04], mostly the value of "sky"

Notice what the output is: a new vector that looks mostly like the value of “sky” ([0, 4, 1, 0]). Information has moved from position 1 to position 2. Attention is the only step in the block that moves information between positions; everything else works on each token separately.

The mask must be applied before the softmax, and it must use −∞ (in practice, the most negative number the format can hold). A masked score of 0 would still get e⁰ = 1 of weight, exactly like a visible key with a score of 0.

Why hide the future at all? In training, the model learns to predict token i + 1 from positions 0 to i, for every position of a text at once. If position i could see position i + 1, it could copy the answer instead of predicting it, and the model would learn nothing useful. At inference the future does not exist yet, and the mask keeps the prompt’s processing identical to what the model saw in training. It is also why earlier keys and values never change, which the KV cache lesson relies on.

Many heads at once: multi-head and grouped-query attention

One softmax row produces one weighted average, so a single head can follow one pattern of “who matters to me” at a time. Real models run many heads side by side. Each head has its own slice of the query, key, and value projections and computes its own attention. The heads’ outputs are then placed side by side and passed through one more matrix, the output projection.

Heads have no assigned jobs, but separate heads let the model track several relationships at once, such as the grammatical subject and the previous token.

Llama 3.1 8B has a hidden size of 4,096 and 32 query heads, so each head has 4,096 / 32 = 128 features. It uses grouped-query attention (GQA): there are only 8 key and value heads, and each is shared by 4 query heads. Queries still come in 32 flavors, but keys and values are computed and stored for only 8 heads, which shrinks the KV cache fourfold. The KV cache lesson works out that memory in full.

Shapes in one Llama 3.1 8B attention layer for a 6-token prompt
TensorShapeWhat the axes mean
Input to the layer(6, 4,096)tokens, hidden features
Queries after the projection(6, 4,096)tokens, 32 heads × 128 features
Queries split into heads(32, 6, 128)query heads, tokens, head features
Keys and values split into heads(8, 6, 128)KV heads, tokens, head features
Scores(32, 6, 6)query heads, queries, keys
Head outputs(32, 6, 128)query heads, tokens, head features
Joined, then output projection(6, 4,096)tokens, hidden features

The script below pushes six random token vectors through those exact shapes. The two moves to watch are the split, a reshape followed by a transpose, and the repeat that lets 4 query heads share each KV head.

attention_shapes.py
import numpy as np

n, d, heads, kv_heads, head = 6, 4096, 32, 8, 128  # 6 tokens, Llama 3.1 8B sizes
rng = np.random.default_rng(0)
x = rng.standard_normal((n, d), dtype=np.float32)
w_q = rng.standard_normal((d, heads * head), dtype=np.float32) / 64
w_k = rng.standard_normal((d, kv_heads * head), dtype=np.float32) / 64
w_v = rng.standard_normal((d, kv_heads * head), dtype=np.float32) / 64


def split(t, count):  # (tokens, count * head) -> (count, tokens, head)
    return t.reshape(n, count, head).transpose(1, 0, 2)


q, k, v = split(x @ w_q, heads), split(x @ w_k, kv_heads), split(x @ w_v, kv_heads)
print("x:", x.shape, " q:", q.shape, " k and v:", k.shape)
group = heads // kv_heads  # 4 query heads per KV head
k, v = np.repeat(k, group, axis=0), np.repeat(v, group, axis=0)
print("k and v shared by 4 query heads each:", k.shape)
scores = q @ k.transpose(0, 2, 1) / np.sqrt(head)
scores[:, np.triu(np.ones((n, n), dtype=bool), k=1)] = -np.inf
weights = np.exp(scores - scores.max(axis=-1, keepdims=True))
weights /= weights.sum(axis=-1, keepdims=True)
heads_out = weights @ v
joined = heads_out.transpose(1, 0, 2).reshape(n, d)
print("scores:", scores.shape, " head outputs:", heads_out.shape)
print("joined:", joined.shape)
You should see
x: (6, 4096)  q: (32, 6, 128)  k and v: (8, 6, 128)
k and v shared by 4 query heads each: (32, 6, 128)
scores: (32, 6, 6)  head outputs: (32, 6, 128)
joined: (6, 4096)

The decoder block: norm, attention, MLP, and two residual adds

A decoder block wraps attention and an MLP in a fixed pattern. Each branch first normalizes its input, then does its work, then adds its result back to what came in. That addition is the residual connection, and the running vector it updates, one per token, is called the residual stream.

One pre-norm decoder block
h = x + Attention(RMSNorm(x))
y = h + MLP(RMSNorm(h))
Input x4,096 numbers per tokenRMSNormAttention32 query heads, 8 KV headsAddh = x + attention outputRMSNormSwiGLU MLP4,096 → 14,336 → 4,096Addy = h + MLP outputOutput ysame shape, to the next blockresidualresidual
One Llama-style decoder block. The residual edges carry each branch’s input around it, so each branch adds an update instead of replacing the token vector.

Follow one token through the block:

  1. RMSNorm rescales the token’s 4,096 numbers so their root mean square is about 1, then multiplies each by a learned gain. The tokens lesson introduced it; here it keeps each branch’s input at a predictable scale.
  2. Attention mixes in information from earlier tokens, as computed above, and the output projection returns a vector of 4,096 numbers.
  3. The first residual add gives h = x + attention output. The token keeps everything it had and gains an update.
  4. The MLP works on each token on its own. Llama’s version, SwiGLU, projects the normalized h to 14,336 numbers twice, through a gate matrix and an up matrix, multiplies the two elementwise after passing the gate through the SiLU function, and projects back down to 4,096.
  5. The second residual add gives y = h + MLP output. It adds to h, the result of the first add, not to the original x.

SiLU is z × sigmoid(z): close to z for large positive inputs and close to 0 for large negative ones, so it acts as a gate. With gate outputs [2.0, −1.0] and up outputs [0.5, 3.0], SiLU gives [1.76, −0.27], and the elementwise product is [0.88, −0.81]: the first feature passes, the second is mostly shut off.

Why add instead of replace? If a branch has nothing useful to contribute, it can output values near zero and the token passes through unchanged. The residual stream gives information from early layers a direct path to late ones, which is a large part of why 32-layer and 80-layer models train at all. A final RMSNorm and the output head turn the last block’s y into scores for every vocabulary token, which the generation lesson picks up.

How do transformer models actually work? · Watch on YouTube

Where Llama 3.1 8B keeps its parameters

Every weight in a block is a matrix, and its shape comes straight from config.json. Llama 3.1 8B has no bias terms (attention_bias and mlp_bias are false), so each matrix’s parameter count is rows × columns.

0204060q_proj, 4,096 × 4,096q_proj, 4,096 × 4,096: 16.78 million16.78 millionk_proj, 4,096 × 1,024k_proj, 4,096 × 1,024: 4.19 million4.19 millionv_proj, 4,096 × 1,024v_proj, 4,096 × 1,024: 4.19 million4.19 milliono_proj, 4,096 × 4,096o_proj, 4,096 × 4,096: 16.78 million16.78 milliongate_proj, 4,096 × 14,336gate_proj, 4,096 × 14,336: 58.72 million58.72 millionup_proj, 4,096 × 14,336up_proj, 4,096 × 14,336: 58.72 million58.72 milliondown_proj, 14,336 × 4,096down_proj, 14,336 × 4,096: 58.72 million58.72 millionattentionMLP
Parameters in one Llama 3.1 8B block, calculated from its published configuration. The three MLP matrices hold about 81% of the block.

Parameters in one block and in the whole model

  1. Attention: q and o are 4,096 × 4,096; k and v are 4,096 × (8 × 128)2 × 16,777,216 + 2 × 4,194,304 = 41,943,040
  2. MLP: gate, up, and down are 4,096 × 14,336 each3 × 58,720,256 = 176,160,768
  3. Two RMSNorm gains of 4,096 each8,192
  4. One block41,943,040 + 176,160,768 + 8,192 = 218,112,000
  5. 32 blocks32 × 218,112,000 = 6,979,584,000
  6. Embedding table and a separate output head, 128,256 × 4,096 each2 × 525,336,576 = 1,050,673,152
  7. Plus the final norm6,979,584,000 + 1,050,673,152 + 4,096 = 8,030,261,248

Result8.03 billion parameters, 16.06 GB in BF16

That total matches the published checkpoint exactly: its index file lists 16,060,522,496 bytes of BF16 weights, which is 8,030,261,248 × 2. The MLP matrices hold 70% of the whole model, attention 17%, and the embedding table and output head about 6.5% each.

For inference, parameters are bytes to move. Each decode step reads every weight once, about 16 GB, and the MLP accounts for most of that read. The attention weights are small, but attention also reads the KV cache, which grows with context. The next section shows why that growth matters.

llama_block_params.py
# The relevant fields from meta-llama/Llama-3.1-8B/config.json
config = {
    "hidden_size": 4096,
    "intermediate_size": 14336,
    "num_attention_heads": 32,
    "num_key_value_heads": 8,
    "num_hidden_layers": 32,
    "vocab_size": 128256,
}
d = config["hidden_size"]
kv = config["num_key_value_heads"] * (d // config["num_attention_heads"])
ffn = config["intermediate_size"]

block = {
    "q_proj": d * d,
    "k_proj": d * kv,
    "v_proj": d * kv,
    "o_proj": d * d,
    "gate_proj": d * ffn,
    "up_proj": d * ffn,
    "down_proj": ffn * d,
    "two norms": 2 * d,
}
per_block = sum(block.values())
for name, count in block.items():
    print(f"{name:>10}: {count:>11,}  {count / per_block:6.1%}")
print(f"one block: {per_block:,}")

table = config["vocab_size"] * d  # embedding table; the untied output head matches it
total = config["num_hidden_layers"] * per_block + 2 * table + d  # + final norm
print(f"whole model: {total:,} parameters, {total * 2:,} bytes in BF16")
You should see
    q_proj:  16,777,216    7.7%
    k_proj:   4,194,304    1.9%
    v_proj:   4,194,304    1.9%
    o_proj:  16,777,216    7.7%
 gate_proj:  58,720,256   26.9%
   up_proj:  58,720,256   26.9%
 down_proj:  58,720,256   26.9%
 two norms:       8,192    0.0%
one block: 218,112,000
whole model: 8,030,261,248 parameters, 16,060,522,496 bytes in BF16

Why attention gets expensive as context grows

The block’s matrix multiplications cost the same for every token, whatever the context. Count work in floating-point operations (FLOPs), with one multiply and one add counting as two. The weight matrices cost about 2 FLOPs per parameter per token, a rule from the tensors lesson.

Attention is different. During decode, the new token’s query is compared with every cached key and mixes every cached value, so its work grows in proportion to the context length. During prefill, every prompt token attends to every earlier one, so the total grows with the square of the prompt length.

FLOPs per generated token for Llama 3.1 8B

  1. Weight matrices: 7.50 billion parameters used in matrix multiplications (the embedding lookup is not one)2 × 7,504,658,432 ≈ 15.0 GFLOPs, at any context length
  2. Scores for one layer: 32 heads × c keys × 128 features × 28,192 × c FLOPs
  3. Mixing values for one layer: the same size8,192 × c FLOPs
  4. All 32 layers32 × 16,384 × c = 524,288 × c FLOPs
  5. At c = 1,000 tokens0.52 GFLOPs, about 3.5% of the weight work
  6. At c = 100,000 tokens52.4 GFLOPs, 3.5 times the weight work

ResultAttention matches the weight work at about 28,600 tokens of context

GFLOPs per generated token020406080032,76865,53698,304131,072Context length (tokens)Weight matrices: 0, 15Weight matrices: 131,072, 15Attention: 0, 0Attention: 32,768, 17.2Attention: 65,536, 34.4Attention: 131,072, 68.7AttentionWeight matricesWeight matricesAttention
Idealized FLOPs per generated token for Llama 3.1 8B. The weight matrices cost the same at every context length; attention grows in a straight line and passes them near 28,600 tokens.

Memory grows too. A plain implementation materializes the full score matrix: for an 8,192-token prompt that is 32 heads × 8,192 × 8,192 scores, 4 GiB in BF16 for a single layer. Nobody does that in production. Fast kernels such as FlashAttention compute the same result in tiles and never store the whole matrix, as the go-deeper panel below shows.

Try it: attention by hand, a whole block, and the lab

The script below reproduces the worked example: the scaled scores for “is”, the full grid of causal weights, and the output vector. You need Python 3.9 or later and NumPy.

attention_by_hand.py
import numpy as np

tokens = ["The", "sky", "is", "blue"]
q = np.array([[1, 0, 1, 0], [1, 1, 0, 0], [0, 2, 0, 2], [0, 2, 0, 1]], dtype=float)
k = np.array([[1, 0, 1, 0], [0, 2, 0, 1], [1, 1, 0, 0], [0, 1, 1, 1]], dtype=float)
v = np.array([[2, 0, 0, 1], [0, 4, 1, 0], [1, 1, 3, 0], [0, 2, 0, 4]], dtype=float)

scores = q @ k.T / np.sqrt(k.shape[1])             # row: query, column: key
future = np.triu(np.ones((4, 4), dtype=bool), k=1)  # True above the diagonal
scores[future] = -np.inf                           # future keys get zero weight
weights = np.exp(scores - scores.max(axis=1, keepdims=True))
weights /= weights.sum(axis=1, keepdims=True)
output = weights @ v

np.set_printoptions(precision=3, suppress=True)
print("scaled scores for 'is':", scores[2])
print("attention weights:")
print(weights)
print("row sums:", weights.sum(axis=1))
print("output for 'is':", output[2])
You should see
scaled scores for 'is': [  0.   3.   1. -inf]
attention weights:
[[1.    0.    0.    0.   ]
 [0.378 0.622 0.    0.   ]
 [0.042 0.844 0.114 0.   ]
 [0.049 0.598 0.133 0.22 ]]
row sums: [1. 1. 1. 1.]
output for 'is': [0.198 3.489 1.186 0.042]

Check three things in the output. The row for “is” shows -inf in the last position, so the mask was applied before the softmax. Every row sums to 1. And the grid is zero above the diagonal. If any row puts weight on a later token, the mask is missing or applied after the softmax.

The next script assembles a whole pre-norm decoder block at toy size: 4 tokens, 8 features, 2 heads of size 4, and a SwiGLU MLP 16 wide. It uses the same two lines as the block section, h = x + Attention(RMSNorm(x)) and y = h + MLP(RMSNorm(h)), then runs three checks a shape check cannot make:

decoder_block.py
import numpy as np

n, d, heads, head, ffn = 4, 8, 2, 4, 16  # 4 tokens, a tiny Llama-style block
rng = np.random.default_rng(0)
w = {name: rng.standard_normal(shape) / np.sqrt(shape[0]) for name, shape in [
    ("q", (d, d)), ("k", (d, d)), ("v", (d, d)), ("o", (d, d)),
    ("gate", (d, ffn)), ("up", (d, ffn)), ("down", (ffn, d))]}


def rms_norm(t):  # learned gains left at 1
    return t / np.sqrt((t ** 2).mean(axis=-1, keepdims=True) + 1e-5)


def attention(t):
    split = lambda m: m.reshape(n, heads, head).transpose(1, 0, 2)
    q, k, v = split(t @ w["q"]), split(t @ w["k"]), split(t @ w["v"])
    scores = q @ k.transpose(0, 2, 1) / np.sqrt(head)
    scores[:, np.triu(np.ones((n, n), dtype=bool), k=1)] = -np.inf
    weights = np.exp(scores - scores.max(axis=-1, keepdims=True))
    weights /= weights.sum(axis=-1, keepdims=True)
    return (weights @ v).transpose(1, 0, 2).reshape(n, d) @ w["o"]


def mlp(t):  # SwiGLU: down(SiLU(gate) * up)
    g = t @ w["gate"]
    return (g / (1 + np.exp(-g)) * (t @ w["up"])) @ w["down"]


def block(x):
    h = x + attention(rms_norm(x))
    return h + mlp(rms_norm(h))


x = rng.standard_normal((n, d))
y = block(x)
print("x:", x.shape, "-> y:", y.shape)

x2 = x.copy()
x2[-1] += 5.0  # change only the last token
y2 = block(x2)
print("earlier tokens unchanged:", np.allclose(y[:-1], y2[:-1]))
print("last token changed:", not np.allclose(y[-1], y2[-1]))

h = x + attention(rms_norm(x))
wrong = x + mlp(rms_norm(h))  # second residual added to x, not h
print("wrong residual:", wrong.shape, "matches y:", np.allclose(y, wrong))
You should see
x: (4, 8) -> y: (4, 8)
earlier tokens unchanged: True
last token changed: True
wrong residual: (4, 8) matches y: False

The block returns the shape it was given, which is what lets 32 of them stack. Changing only the last token leaves the outputs of the first three tokens exactly as they were, because the causal mask stops them from reading it; that property is what later lets an engine cache their keys and values. The last line adds the MLP output to x instead of h. The result has the right shape and the wrong values, the silent bug in the common-mistakes table below.

Finally, open the browser lab at the end of this lesson. With its default inputs and the causal mask on, select query 2 and predict its output before you press Check: its scores are 0.707, 0.707, and 0, so its weights are 0.40, 0.40, and 0.20, and the output is about 3.99. Then untick the causal mask and inspect query 0. Its output jumps from 2.00 to 4.80, because it can now read the value 8 from a position after it.

Common mistakes

Symptoms you may see, their usual cause, and the fix
SymptomLikely causeFix
Outputs for early tokens change when you append textThe causal mask is missing, applied after the softmax, or sets scores to 0 instead of −∞.Set masked scores to −∞ (or the format’s most negative value) before the softmax.
Attention weights are nearly one-hot everywhere and outputs look wrongThe 1/√d scale is missing, or you divided by d instead of √d.Divide scores by √(head size), which is √128 ≈ 11.3 for Llama 3.1 8B.
Shapes work but results differ from a reference implementationHeads were split with a reshape but no transpose.Reshape to (tokens, heads, 128), then transpose to (heads, tokens, 128).
A decode step with a cache gives wrong outputs in PyTorchis_causal=True with one query and many keys aligns the mask to the top left, so the query sees only key 0.For a single new query, pass no mask; for a chunk of new queries, build a mask offset by the cache length.
NaN outputs appear for padded rowsEvery key in a row is masked, so the softmax divides 0 by 0.Special-case fully masked rows, for example by returning zeros for them.
The block’s output is subtly wrong but has the right shapeThe second residual adds the MLP output to x instead of h.y = h + MLP(RMSNorm(h)). A shape check cannot catch this.

How real engines run attention and the block

Production engines compute exactly this math. What changes is how they schedule it on a GPU.

  • Tiled attention kernels. FlashAttention is an exact attention algorithm that works through the keys in tiles held in fast on-chip memory, so the N × N score matrix never goes to GPU memory. Standard implementations need memory that grows with N²; FlashAttention’s grows linearly with sequence length.
  • PyTorch’s `scaled_dot_product_attention`. It takes is_causal, a scale (1/√E by default), and enable_gqa for grouped-query attention, and can dispatch to FlashAttention-2 or memory-efficient attention kernels. A boolean mask uses True for keys that take part.
  • The reference implementation in Transformers. Llama’s eager attention repeats each KV head to match the query heads (a function called repeat_kv) and computes the softmax in FP32 even when the model runs in BF16, then casts back.
  • Fused layers in vLLM. vLLM 0.28.0 loads q, k, and v into one qkv_proj matrix (4,096 × 6,144) and gate and up into one gate_up_proj (4,096 × 28,672), so each block runs four large matrix multiplications instead of seven. It also folds each residual add into the following RMSNorm with a fused kernel.
  • Decode reads the cache. During decode, attention’s cost is mostly reading cached keys and values from memory. The KV cache lesson sizes that cache.

In a profile, expect the matrix multiplications to dominate at short contexts and attention to take a growing share as contexts lengthen. If decode attention time grows faster than linearly with context, look for code that materializes the score matrix or recomputes past keys.

Go deeperWhy the scale is √d, and how tiled softmax gets the exact answer

If the entries of a query and a key are independent with mean 0 and variance 1, their dot product has variance d, so its typical size is √d. With d = 128, raw scores spread about 11.3 wide, and a gap of 20 between two scores gives the larger one e²⁰ ≈ 485 million times the weight. The softmax becomes a hard pick and its gradients vanish, which is why the original transformer paper divides by √d.

Tiled kernels face a puzzle: softmax needs the maximum and the total of a whole row, but a tile sees only part of it. The fix is an online softmax. Keep a running maximum, a running total, and a running weighted sum of values. When a new tile brings a larger maximum, multiply the old total and sum by e^(old max − new max) before adding the new tile. At the end, divide once. The result is exactly the same as the full softmax, as this script checks:

scale_and_tiles.py
import numpy as np

rng = np.random.default_rng(0)
q = rng.standard_normal((10_000, 128))
k = rng.standard_normal((10_000, 128))
dots = (q * k).sum(axis=1)
print(f"spread of raw scores: {dots.std():.2f}")
print(f"spread after dividing by sqrt(128): {(dots / np.sqrt(128)).std():.2f}")

# Attention for one query, computed in two tiles of keys (online softmax).
scores, values = rng.standard_normal(8) * 3, rng.standard_normal((8, 4))
full = np.exp(scores - scores.max()) @ values / np.exp(scores - scores.max()).sum()
m, total, acc = -np.inf, 0.0, np.zeros(4)
for tile in (slice(0, 4), slice(4, 8)):
    new_m = max(m, scores[tile].max())
    rescale = np.exp(m - new_m)          # shrink what we summed under the old maximum
    e = np.exp(scores[tile] - new_m)
    total = total * rescale + e.sum()
    acc = acc * rescale + e @ values[tile]
    m = new_m
print("tiled result matches full softmax:", np.allclose(acc / total, full))
You should see
spread of raw scores: 11.33
spread after dividing by sqrt(128): 1.00
tiled result matches full softmax: True

Real kernels do this per block of queries and per block of keys, and they skip key tiles that lie entirely in a query block’s future, which roughly halves the work of causal prefill.

Cheat sheet

  • Attention(Q, K, V) = softmax(Q × Kᵀ / √d + mask) × V, computed per head.
  • The causal mask sets future scores to −∞ before the softmax, so position i sees only positions 0 to i.
  • Each attention row is a set of weights that sum to 1; the output is the weighted average of the visible values.
  • Llama 3.1 8B: 32 query heads and 8 KV heads of 128 features; 4 query heads share each KV head.
  • Decoder block: h = x + Attention(RMSNorm(x)), then y = h + MLP(RMSNorm(h)).
  • One Llama 3.1 8B block has 218,112,000 parameters, 81% of them in the SwiGLU MLP; 32 blocks plus embeddings make 8.03 billion.
  • Weight work per token is fixed at about 15 GFLOPs; attention adds 524,288 × context FLOPs and passes it near 28,600 tokens.
  • Fast kernels tile attention and never store the full score matrix.

Walkthrough

Calculate one attention row

Request traceReady

Browser lab

Attention, one row at a time

Attention probabilitiessoftmax(QKᵀ / √2 + mask)
query ↓ / key →012
01.000——
10.3300.670—
20.4010.4010.198
ReadoutQuery 2 scores: [0.707, 0.707, 0.000]. Row sum: 1.000.

Predict the selected query output.

Knowledge check

Why does causal attention mask future keys?

Choose one answer

Sources and further reading

Finished this unit?