3 Coding attention mechanisms

Language Models · v1.0.4

2026-11-03 01:40:25

Where we are

Where this fits

Built already

  • Tokenization and byte pair encoding.
  • Sliding-window batches.
  • Token and positional embeddings.

Handed forward

  • A tensor of shape (batch, tokens, embedding dim).

Built here

  • The layer that consumes that tensor: attention.

The four attention variants of this unit, each keeping everything from the one before.

Outline of key topics

  • Self-attention — relating all positions within one sequence.
  • Dot-product scores — alignment between two vectors.
  • Query, key, value — trainable projections into three roles.
  • Scaling by \(\sqrt{d_k}\) — keeping softmax gradients alive.
  • Causal masking — forbidding access to future tokens.
  • Dropout — regularizing the attention weights.
  • Multi-head attention — several attention operations in parallel.

The mechanism and its rationale; the full transformer block belongs to a later unit.

Why attention

The bottleneck it removes

An RNN encoder compresses the whole source sequence into one final hidden state, from which the decoder generates token by token.
  • One vector must encapsulate the entire input; long-range context is lost.
  • 2014 — Bahdanau attention lets the decoder access all input positions, weighted.
  • 2017 — the RNN turns out to be unnecessary: the transformer is built on self-attention alone.

Self-attention relates positions within one sequence; ordinary attention relates two.

Simplified self-attention

The context vector

Each position weighs the relevance of every other position in the same sequence.

For a query token \(x^{(q)}\) among \(T\) tokens:

\[\omega_{q,i} = x^{(q)} \cdot x^{(i)}\] \[\alpha_{q,\cdot} = \operatorname{softmax}(\omega_{q,\cdot})\] \[z^{(q)} = \sum_{i} \alpha_{q,i}\, x^{(i)}\]

  • Score, normalize, combine.
  • No trainable weights yet — this isolates the shape of the computation.

Every query at once

One row of weights generalized to every row: the full \(T \times T\) score matrix.

\[\Omega = X X^{\top} \in \mathbb{R}^{T \times T}\]

scores  = X @ X.T              # (T, T)
weights = softmax(scores, dim=-1)
context = weights @ X          # (T, d)
  • Softmax runs along the row — over keys for a fixed query.
  • Normalizing the wrong axis is the classic bug; every row summing to \(1\) is the check.

Trainable self-attention

Query, key, value

Each input is multiplied by \(W_q\), \(W_k\) and \(W_v\) to produce its query, key and value vector.

\[q^{(i)} = W_q x^{(i)},\quad k^{(i)} = W_k x^{(i)},\quad v^{(i)} = W_v x^{(i)}\]

  • Three trainable matrices project each token into three roles.
  • The context vector becomes a weighted sum over the value vectors.

Scaling the scores

\[\alpha_{q,\cdot} = \operatorname{softmax}\!\left(\frac{q^{(q)} \cdot k^{(\cdot)}}{\sqrt{d_k}}\right)\]

  • Large embedding dimensions produce large dot products.
  • Unscaled, softmax approaches a step function and the gradients approach zero.
  • Dividing by \(\sqrt{d_k}\) keeps the scores where softmax still has useful gradients.

The module

class SelfAttention(nn.Module):
  def __init__(self, d_in, d_out):
    L = nn.Linear
    self.W_q = L(d_in, d_out, bias=0)
    self.W_k = L(d_in, d_out, bias=0)
    self.W_v = L(d_in, d_out, bias=0)

  def forward(self, x):
    q = self.W_q(x)
    k = self.W_k(x)
    v = self.W_v(x)
    s = q @ k.T / d_out**0.5
        return softmax(s, dim=-1) @ v

A bias-free linear layer computes the same operation as a raw parameter matrix, with a better weight initialization.

\(X\) is projected to \(Q\), \(K\) and \(V\); the weight matrix comes from \(Q\) and \(K\) and is applied to \(V\).

Causal masking and dropout

Restricting attention to the past

Masking the scores with \(-\infty\) before the softmax; each row still sums to \(1\).

Next-token prediction requires a token to consider only positions prior to it.

Two equivalent routes:

  • Normalize, zero the entries above the diagonal, renormalize.
  • Fill the scores with \(-\infty\), then apply softmax once.

The second is preferred: one softmax pass, no renormalization.

Dropout on the attention weights

A dropout mask applied on top of the causal mask during training.
  • Randomly zeroes a fraction \(p\) of the normalized weights; surviving entries are scaled by \(1/(1-p)\).
  • The rescaling keeps the average influence consistent between training and inference.
  • Applied during training only, immediately after the weights are computed.
  • Consequences: rows no longer sum to \(1\), and a whole row can be zeroed. Both are expected.

A batched causal module

# x: (b, T, d_in)
def forward(self, x):
    q, k, v = self.qkv(x)
    s = q @ k.transpose(-2, -1)
    s = s.masked_fill(mask, -inf)
    w = softmax(s / d_out**0.5)
    return self.dropout(w) @ v
  • Transposing only the last two axes leaves the batch axis untouched.
  • The mask is state but not trainable state — registered as a buffer so it follows the model between devices.
  • Built once at the maximum context length, then sliced to the sequence in use.

Multi-head attention

Several heads in parallel

Two heads with two sets of \(W_q, W_k, W_v\), producing \(Z_1\) and \(Z_2\), combined into one matrix \(Z\).
  • A single causal attention module is single-head attention.
  • Several heads run independently, each with its own learned projections, each attending to different aspects of the data.
  • Stacking copies works, but repeats the projection matmul once per head — the dominant cost.

One projection, split into heads

Two heads computed separately (top) versus one larger projection split into heads (bottom).
hd = d_out // n_heads
q = W_q(x).view(b, T, n_heads, hd)
q = q.transpose(1, 2)
# -> (b, n_heads, T, hd)
  • One matmul per role, whatever the number of heads.
  • Heads move ahead of tokens so one batched matmul covers all of them.
  • Recombined to width d_out, then an output projection.
  • Mathematically identical to stacking; materially cheaper.

Summary

Summary

  • Attention produces context vectors that incorporate information about all inputs — what the encoder-decoder bottleneck could not do.
  • A context vector is a weighted sum; \(XX^\top\) and \(\alpha X\) replace nested loops with the identical result.
  • Scaled dot-product attention adds trainable \(W_q, W_k, W_v\) and divides by \(\sqrt{d_k}\) to keep gradients alive.
  • A causal mask filled with \(-\infty\) before the softmax forbids future tokens in one pass; dropout regularizes the weights during training.
  • Multi-head attention obtains its heads from one projection per role, reshaped and batched.

Next: implementing a GPT model from scratch — attention is one sub-layer of the transformer block.