Paul’s learnings

Neural networks › The Transformer

The Transformer

Vaswani et al. (2017) eliminated recurrence in favor of multi-head self-attention. This chapter derives tensor shapes through an attention layer, proves why dot products require √d_k scaling, derives the softmax Jacobian, analyzes attention vs FFN FLOP scaling, and walks through the pre-norm residual block.

Attention as a dynamic content-based lookup

In feedforward layers, weights are static connections learned during training. In self-attention, the weights connecting tokens are computed dynamically on the fly based on token compatibility. Each input token representation xi∈ℝd is projected into three subspaces:

  • Query (Q): what information token i is searching for.
  • Key (K): what features or context token j advertises.
  • Value (V): the actual content payload transmitted if attended to.

The matrix formulation evaluates all pairs simultaneously:

Attention(Q,K,V)=softmax(QKTdk+M)V

Enable JavaScript to use this local playground. The explanation and sources below work without it.

Tensor shape progression across a single layer

For an input sequence of length T with model dimension d and H attention heads (head dimension dk=d/H), shapes progress through the attention mechanism as follows:

TensorExpressionShapeDescription
XInput embeddings[T, d]Batch of T token vectors of width d
WQ, WK, WVProjection weights[d, d]Learned linear projection matrices
Qh, Kh, VhXWQ,K,V(h)[T, dk]Per-head projected queries, keys, and values
ShQhKhT/dk+M[T, T]Pairwise scaled compatibility scores
Phsoftmax(Sh)[T, T]Row-normalized attention probability weights (∑ⱼ Pij = 1)
OhPhVh[T, dk]Weighted combination of values for head h
Oconcat[O1,…,OH][T, d]Concatenated outputs across all H heads
YOconcatWO[T, d]Final linear output projection

Variance derivation: why divide by √d_k?

Assume components of query q and key k are independent, zero-mean, unit-variance random variables: E[qi]=E[ki]=0 and Var(qi)=Var(ki)=1. The dot product is q·k=∑i=1dkqiki.

For each term, independence gives:

E[qiki]=E[qi]E[ki]=0 Var(qiki)=E[qi2ki2]−(E[qiki])2=E[qi2]E[ki2]=1·1=1

Because the components are mutually independent, the variance of the sum is the sum of the variances:

Var(q·k)=∑i=1dkVar(qiki)=dk,StdDev(q·k)=dk

As head dimension dk increases (e.g. dk=128), unscaled dot products have standard deviation 128≈11.3. Dividing by dk scales variance back to 1.0:

Var(q·kdk)=1dkVar(q·k)=dkdk=1

The Softmax Jacobian and gradient saturation

Why does unscaled variance matter? The derivative of the row-wise softmax Pij=eSij/∑keSik with respect to input score Sim is:

∂Pij∂Sim=Pij(δjm−Pim)={Pij(1−Pij)j=m−PijPimj≠m

When scores Sij have large variance, the largest score completely dominates the exponential sum, driving its probability Pij→1 while all other probabilities Pim→0. At Pij≈1, Pij(1−Pij)≈0. At Pim≈0, −PijPim≈0. The entire Jacobian matrix approaches zero, completely vanishing the gradient signal flowing back into Q and K. Scaling by 1/dk prevents this saturation trap.

Causal masking

In autoregressive generation (GPT-style decoders), token i must not attend to future tokens j>i. An additive attention mask M is applied to scores before softmax:

Mij={0j≤i−∞j>i

Because e−∞=0, future entries receive identically zero attention probability weight, preventing information leakage from future tokens during parallel teacher-forced training.

Layer FLOPs: when does attention dominate the FFN?

Consider a standard Transformer layer with sequence length T, model dimension d, and feedforward intermediate dimension 4d. Counting multiply-accumulate operations (2 FLOPs per MAC):

  • Q, K, V projections: 3·2Td2=6Td2
  • Attention score matrix (QKT): 2T2d
  • Value aggregation (PV): 2T2d
  • Output projection (WO): 2Td2
  • Feedforward layer (W1∈ℝd×4d,W2∈ℝ4d×d): 2·2T(d·4d)=16Td2

Total layer FLOPs:

FLOPslayer=4T2d⏟O(T2) attention+24Td2⏟O(T) linear projections

Attention FLOPs exceed linear projection FLOPs when:

4T2d>24Td2⇒T>6d

For standard 7B/8B models where d = 4096, attention compute only dominates once sequence length T>6×4096=24 576 tokens. At short contexts (T≤4096), over 85% of total compute is spent in the feedforward projections.

The Pre-Norm Transformer block

Original Transformers placed LayerNorm after the residual addition (Post-LN: x=LN(x+SubLayer(x))), which suffered from gradient vanishing and required warmup learning rate schedules. Modern models adopt Pre-LN (or Pre-RMSNorm):

xmid=x+Attention(RMSNorm(x)) xout=xmid+FFN(RMSNorm(xmid))

In Pre-LN, the identity highway x+… is uninterrupted across the entire depth of the network. Gradients flow back from the loss directly to early token embeddings without attenuation.

Interactive Micro-Transformer Trainer

Train a 2-layer, 2-head Micro-Transformer on algorithmic sequence tasks (Sequence Reversal, Identity Copy, Sorting). Observe how attention weights self-organize along the anti-diagonal for sequence reversal, and inspect the impact of causal versus bidirectional masking.

Configuration & Controls

Epoch
0
Token CE Loss
—
Token Accuracy
—

Multi-Head Attention Heatmaps (Head 1 & Head 2)

Training on Reverse causes attention to concentrate along the anti-diagonal (position 0 attends to position 3). Under a Causal Mask, position 0 cannot attend ahead, demonstrating why bidirectional context is required for non-autoregressive tasks.

Sources and further reading