from_scratch.llm
The Transformer
07

Self-attention

the mechanism that makes transformers work
steps/04_transformer/07_self_attention.py ► Open as notebook (with output)

The heart of it all. Each token emits a Query (what I seek), a Key (what I offer), and a Value (what I pass on). Dot-product Query·Key gives relevance scores → softmax → a weighted sum of Values. Every token gets a new, context-aware representation.

The causal mask (the lower triangle below) forbids peeking at the future. Unlike the MLP's fixed window, attention scales to any context and learns what to focus on.

Attention(Q, K, V) = softmax( QKᵀ / √dₖ + mask )·Vcontent-based weighted average; scaling by √dₖ keeps the softmax gradients stable.
The theory

Attention is a content-based weighted average. Each token produces a query (what it's looking for), a key (what it offers), and a value (what it passes on). The dot product of a query with every key gives relevance scores; softmax turns those into weights that sum to one; the output is the weighted sum of values. Scaling scores by √dₖ keeps them from growing with dimension, which would otherwise saturate the softmax and kill its gradient.

Two properties make it powerful. It has a global receptive field — any token can attend to any earlier token in a single step, unlike the fixed window of an MLP or the slow recurrence of an RNN. And it is permutation-equivariant (it sees a set, not a sequence), which is precisely why transformers must add positional information separately. The causal mask sets future scores to −∞ so a token can never attend to what it's trying to predict.

Animation
Causal attention: each row (a query token) lights up the tokens it may attend to — itself and every earlier token. The upper triangle stays dark: the future is masked.
Visual walkthrough
Token columns emitting query, key, and value streams.
Q, K, V streamsEach token emits what it seeks, what it offers, and what it will pass on.
Lower-triangular attention matrix with future positions blocked.
Causal maskThe lower triangle lets each token attend only to itself and the past.
Weighted value vectors merging into updated token representations.
Weighted valuesAttention weights mix value vectors into context-aware token representations.
The notebook · steps/04_transformer/07_self_attention.ipynb — code cells & their output. Open & run on GitHub →
In [1]
import torch
import torch.nn as nn
import torch.nn.functional as F

torch.manual_seed(0)


class SelfAttentionHead(nn.Module):
    """A single causal self-attention head."""

    def __init__(self, n_embd, head_size):
        super().__init__()
        # Three linear projections turn each token's embedding into Q, K, V.
        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.head_size = head_size

    def forward(self, x, return_weights=False):
        # x: (B, T, C) = (batch, time/sequence length, embedding dim)
        B, T, C = x.shape
        q = self.query(x)   # (B, T, head_size)
        k = self.key(x)     # (B, T, head_size)
        v = self.value(x)   # (B, T, head_size)

        # Attention scores: how much each token (query) matches every other
        # token (key). Scale by sqrt(head_size) to keep softmax well-behaved.
        scores = q @ k.transpose(-2, -1) / self.head_size ** 0.5  # (B, T, T)

        # Causal mask: forbid attending to FUTURE positions.
        mask = torch.tril(torch.ones(T, T))            # lower-triangular 1s
        scores = scores.masked_fill(mask == 0, float("-inf"))

        weights = F.softmax(scores, dim=-1)            # (B, T, T), rows sum to 1
        out = weights @ v                              # (B, T, head_size)

        if return_weights:
            return out, weights
        return out
In [2]
# A toy sequence of 5 tokens, each a 4-dim embedding, single batch.
B, T, C = 1, 5, 4
x = torch.randn(B, T, C)

head = SelfAttentionHead(n_embd=C, head_size=4)
out, weights = head(x, return_weights=True)

print(f"input  shape: {tuple(x.shape)}  (batch, tokens, embd)")
print(f"output shape: {tuple(out.shape)}  (each token now context-aware)\n")

print("Attention weights — row i = how token i distributes attention over")
print("tokens 0..4. Note the lower-triangular shape: no token sees the")
print("future, and each row sums to 1.\n")
w = weights[0]
header = "        " + "".join(f"tok{j}  " for j in range(T))
print(header)
for i in range(T):
    row = "  ".join(f"{w[i, j]:.2f}" for j in range(T))
    print(f"  tok{i}  {row}")

print("\nRead it: token 0 can only attend to itself (1.00). Token 4 spreads")
print("attention across all 5 tokens. The upper triangle is exactly 0 —")
print("that's the causal mask doing its job.")
Output
input  shape: (1, 5, 4)  (batch, tokens, embd)
output shape: (1, 5, 4)  (each token now context-aware)

Attention weights — row i = how token i distributes attention over
tokens 0..4. Note the lower-triangular shape: no token sees the
future, and each row sums to 1.

        tok0  tok1  tok2  tok3  tok4  
  tok0  1.00  0.00  0.00  0.00  0.00
  tok1  0.48  0.52  0.00  0.00  0.00
  tok2  0.28  0.35  0.37  0.00  0.00
  tok3  0.20  0.27  0.30  0.24  0.00
  tok4  0.12  0.20  0.20  0.20  0.29

Read it: token 0 can only attend to itself (1.00). Token 4 spreads
attention across all 5 tokens. The upper triangle is exactly 0 —
that's the causal mask doing its job.