Skip to content
mentoor

Topic 2 of 6 · 5 min read

Causal self-attention in code

Goal: Find the bug in a self-attention implementation, such as a missing causal mask or wrong scaling, by tracing tensor shapes and values.

Self-attention lets each position build its output as a weighted average of the value vectors of the positions it is allowed to see, with the weights computed from how well its query matches their keys.

Check yourself · 1 of 3

In causal self-attention, when is the lower-triangular mask applied?

Choose one answer

Why it matters

Attention is the only place where tokens exchange information. Everything else in a GPT works on each position separately. A mask bug here is the most dangerous kind: the model sees the future during training, loss falls to a suspiciously low value, and generation then fails because the future is not there.

How to do it

Input x has shape (B, T, C): batch, time (positions), channels (embedding size).

  1. Project x three times with linear layers: q, k and v, each (B, T, head_size).
  2. Score: att = q @ k.transpose(-2, -1) gives (B, T, T). Entry [t, s] says how much position t wants to read from position s.
  3. Scale by head_size ** -0.5. Without it, the dot products grow with head size, softmax saturates to nearly one-hot, and gradients get tiny.
  4. Mask: set every entry where s > t to -inf before softmax. A lower-triangular matrix from torch.tril marks the allowed entries. After softmax, masked entries become exactly 0.
  5. Softmax over the last dimension, so each row sums to 1.
  6. Mix values: out = att @ v, shape (B, T, head_size).

For multiple heads, project to n_head smaller heads, run the same steps in parallel by reshaping to (B, n_head, T, head_size), then concatenate and pass through one output projection. Heads let the model look for several kinds of relation at once.

Before and after

This version looks right and trains:

att = (q @ k.transpose(-2, -1)) * k.shape[-1] ** -0.5
att = F.softmax(att, dim=-1)   # bug: no causal mask
out = att @ v

Every position can read every later position. Training loss drops far below what a real predictor could reach, because the answer is in the input. The fix is one line before softmax:

att = att.masked_fill(tril[:T, :T] == 0, float("-inf"))

A quick test: change a token at position 5 and confirm the output at positions 0 to 4 does not change.

What goes wrong

  • Missing or wrong mask. Masking after softmax, or masking with 0 instead of -inf, still lets weight flow to future tokens.
  • Softmax on the wrong dimension. Using dim=-2 normalizes over queries, so rows no longer sum to 1.
  • Scaling by the wrong size. Using C instead of head_size, or forgetting it, changes training stability without raising an error.
  • Reshape without transpose. Viewing (B, T, C) as (B, n_head, T, hs) directly scrambles positions and heads. Reshape to (B, T, n_head, hs), then transpose.

PyTorch also ships F.scaled_dot_product_attention(q, k, v, is_causal=True), which fuses these steps. Write it by hand once; use the fused call afterwards.

Examples

One causal head in PyTorch

class Head(nn.Module):
    def __init__(self, n_embd, head_size, block_size):
        super().__init__()
        self.key = nn.Linear(n_embd, head_size, bias=False)
        self.query = nn.Linear(n_embd, head_size, bias=False)
        self.value = nn.Linear(n_embd, head_size, bias=False)
        self.register_buffer("tril", torch.tril(torch.ones(block_size, block_size)))

    def forward(self, x):
        B, T, C = x.shape
        k, q, v = self.key(x), self.query(x), self.value(x)
        att = q @ k.transpose(-2, -1) * k.shape[-1] ** -0.5
        att = att.masked_fill(self.tril[:T, :T] == 0, float("-inf"))
        att = F.softmax(att, dim=-1)
        return att @ v

For T = 3 the second row of att has non-zero weights only in columns 0 and 1; column 2 is exactly 0.

Key points

  • Attention computes weights from query-key dot products and uses them to average value vectors.
  • Scale scores by the inverse square root of head size so softmax does not saturate.
  • The causal mask sets future positions to negative infinity before softmax, so their weight becomes exactly zero.
  • A reliable test for a causal model: changing a later token must not change the outputs at earlier positions.
  • Multi-head attention reshapes to (B, n_head, T, head_size) via view then transpose, never a bare reshape.

Common mistakes

  • Applying the mask after softmax or with zeros, so future tokens still receive weight.
  • Skipping the head-size scaling and getting unstable training with no error message.
  • Running softmax over the query dimension instead of the key dimension.
  • Reshaping to heads without the transpose, which mixes positions and heads.

Check yourself · 2 of 3

Why are attention scores multiplied by head_size ** -0.5?

Choose one answer

Check yourself · 3 of 3

A causal model's training loss falls far below what next-token prediction should allow, then generation is gibberish. What is the most likely cause?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic