Embeddings and self-attention

Queries, keys and values, the causal mask, and multi-head attention, derived and implemented.

Intermediate about 6 h

The picture

  1. 01

    Token embeddings

    ids → vectors

  2. 02

    Q, K, V

    three linear maps

  3. 03

    Scores

    QKᵀ / √d

  4. 04

    Causal mask

    no peeking ahead

  5. 05

    Weighted sum

    softmax · V

The idea

Each token needs to gather information from earlier tokens. Attention lets every position ask a question (query), advertise what it holds (key), and contribute content (value). The match between a query and each key decides how much of each value to take.

Attention(Q,K,V)=softmax ⁣(QK⊤dk+M)V\mathrm{Attention}(Q,K,V)=\mathrm{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}}+M\right)V

MM is the causal mask: −∞-\infty above the diagonal so a position cannot see the future. We divide by dk\sqrt{d_k} because the variance of a dot product grows with dkd_k; without scaling, softmax saturates and gradients vanish.

Implementation

import math, torch, torch.nn as nn, torch.nn.functional as F

class CausalSelfAttention(nn.Module):
    def __init__(self, d_model: int, n_heads: int, block_size: int):
        super().__init__()
        assert d_model % n_heads == 0
        self.h, self.dk = n_heads, d_model // n_heads
        self.qkv = nn.Linear(d_model, 3 * d_model, bias=False)
        self.proj = nn.Linear(d_model, d_model, bias=False)
        mask = torch.tril(torch.ones(block_size, block_size)).view(1, 1, block_size, block_size)
        self.register_buffer("mask", mask)

    def forward(self, x):                                   # x: (B, T, C)
        B, T, C = x.shape
        q, k, v = self.qkv(x).split(C, dim=2)
        q, k, v = (t.view(B, T, self.h, self.dk).transpose(1, 2) for t in (q, k, v))  # (B, h, T, dk)
        att = (q @ k.transpose(-2, -1)) / math.sqrt(self.dk)  # (B, h, T, T)
        att = att.masked_fill(self.mask[:, :, :T, :T] == 0, float("-inf"))
        att = F.softmax(att, dim=-1)
        y = att @ v                                          # (B, h, T, dk)
        y = y.transpose(1, 2).contiguous().view(B, T, C)
        return self.proj(y)

# the fused version you should use in practice
def fused(q, k, v):
    return F.scaled_dot_product_attention(q, k, v, is_causal=True)

Check that your version and fused agree to within floating-point error. Then profile both at sequence length 4096.

Why multiple heads

One head can express one pattern of attention. Several heads, each with a smaller dimension, let the model track different relations at once (previous token, matching bracket, subject of a verb) for the same cost.

Position

Attention alone is permutation-invariant, so the model needs to know order. The original paper added sinusoidal vectors; GPT-2 learned absolute position embeddings; modern models use rotary embeddings (RoPE), covered in the architectures topic.

Cost

The score matrix is T×TT\times T, so compute and memory grow quadratically with context length. That single fact explains why long contexts are expensive and why FlashAttention and KV caching exist.

Common mistakes

  • Applying the mask after softmax instead of before.
  • Forgetting contiguous() before view after a transpose.
  • Using bidirectional attention for a generative model (information leaks from the future and training loss looks suspiciously good).

Exercises

  1. Visualise an attention matrix for a short sentence in a pre-trained model (output_attentions=True) and describe one head.
  2. Measure memory use as you double the sequence length and plot it.

You are done when you can…

  • Write multi-head causal attention from memory and match PyTorch's fused kernel
  • Explain why we divide by the square root of the head dimension
  • State the time and memory cost of attention in the sequence length