Lesson 4.3 — Transformer Architecture
Previous lesson · 4.2 Attention Mechanisms · Curriculum · Next lesson · 4.4 Autoregressive Language Modeling
Transformer Overview · From Attention to a Full Network
In Lesson 4.2, attention compares each query with the keys and reads a weighted sum of the values. A Transformer stacks blocks that combine attention with a nonlinear transformation at each token, normalization, and residual connections. Attention exchanges information across tokens. The feed-forward network (FFN) transforms the features of each token independently. This lesson uses batch-first tensors with shape (B, T, D).
Encoder-only
Bidirectional self-attention lets each position read all valid input positions and produces contextual representations. Vision Transformer (ViT) is an encoder-only example.
Decoder-only
Causal self-attention lets each position read the prefix through that position. Lesson 4.4 uses this setup for next-token prediction.
Encoder–Decoder
The encoder represents the source sequence. The decoder processes the target prefix with causal self-attention and reads the encoded source with cross-attention.
Pre-Norm Block Dataflow
Imagine a sequence of sensor readings. Keep the middle reading fixed and change a neighbor. To find where that edit can affect the middle output, trace one row through a pre-norm encoder block.

Follow the two outer arrows. Attention brings information from those other positions into the middle row. A changed neighbor can change its key, its value, and the mixture received by . At the first plus sign, the block adds that update to the original row , producing . Now cover every other row. You can still compute the entire second half for from alone. The FFN uses the same learned function at every position, and its hidden units mix feature coordinates within that row. Information from a neighbor can reach because it has already entered .
Layer normalization here operates across the features of each token. The carried rows bypass that normalization. Consequently, if both update branches return zero, the entire block passes its input through exactly.
The residual stream has width D, with a temporary expansion to width F inside the FFN. The original 2017 Transformer used Post-Norm. The training experiment in this lesson uses Pre-Norm. The equations and numerical examples use the row-vector product XW, so linear weights have shape (in, out). PyTorch nn.Linear stores its weight as (out, in).
Trace the tensor shapes of both updates
Transformer Block Dataflow
Multi-head Attention · Split, Attend, Concatenate
Different heads can match information in different feature subspaces. In equal-width multi-head attention, the number of heads H must divide model width D, giving head width d = D/H. Pack the head-specific projections into larger matrices, apply them, and split the last axis into heads. Every head reads the same input X through its own query, key, and value projection columns.
Reshape (B, T, D) to (B, T, H, d), then apply transpose(1, 2) to get (B, H, T, d). Transposition changes strides, so its result can be noncontiguous. To merge the heads, transpose back and use reshape, or make the tensor contiguous before calling view. The attention score tensor has shape (B, H, T, T).
Multi-head Shape Inspector
With bias disabled, the four Q, K, V, and output projections contain 4D² parameters at any head count for fixed D. The head count affects head width, the size of the explicit score tensor, and hardware performance.
Positional Encoding · Absolute Position & RoPE
Self-attention with no positional encoding or mask is permutation equivariant. If X′ = ΠX, then Attention(X′) = ΠAttention(X). A causal mask imposes an ordering constraint. Positional encodings supply additional information about token positions. Common approaches include additive sinusoidal encodings, learned position tables, and rotary position embeddings.
Sinusoidal position encoding
Each pair of coordinates uses one frequency, and the frequency decreases with the coordinate index. Learned absolute position embeddings add row P[p] from a trainable position table at position p. Positions outside the training range may generalize poorly.
Sinusoidal Position Encoding
Rotary Position Embedding (RoPE)
RoPE applies position-dependent rotations to pairs of query and key coordinates within each head. Values typically pass through unchanged. This example pairs adjacent coordinates. Some implementations pair corresponding coordinates from the first and second halves of the head. The pairing convention must agree with the model weights and implementation.
Each two-dimensional rotation preserves the norm. For fixed query and key vectors q and k, the positional term in their rotated dot product depends only on the relative offset n − m. This identity applies to an individual dot product. Whole-model behavior and extrapolation to longer sequences require separate evaluation. The animation rotates one coordinate pair.
Rotary Position Embedding (RoPE)
Feed-forward Network · GELU & SwiGLU
Attention mixes information across positions. The FFN applies the same parameters independently at each position. Its intermediate width F is usually larger than D, and its output returns to width D for residual addition. The original Transformer used ReLU. Modern models often use GELU or a gated FFN.
SwiGLU uses two separate input projections. It multiplies the activated gate and the up projection elementwise. With bias disabled, the standard FFN has 2DF parameters and SwiGLU has 3DF. At a fixed parameter budget, use a smaller intermediate width for SwiGLU.
FFN & SwiGLU Explorer
Normalization & Residual · Pre-Norm vs Post-Norm
Lesson 2.3 introduces LayerNorm and RMSNorm. In a Transformer, both typically compute statistics over the last axis for each token independently, keeping sequence positions and batch items separate. LayerNorm subtracts the mean and scales the centered features. RMSNorm scales by the root mean square and typically uses only the learned gain γ.
The Pre-Norm Jacobian includes a direct identity term. In Post-Norm, the residual path passes through normalization. Pre-Norm often helps train deep stacks. Stability across depths and generalization remain empirical questions. Many Pre-Norm architectures add a final normalization after the stack. The small model in this lesson omits it to keep the dataflow easy to follow.
Pre-Norm vs. Post-Norm
Encoder & Decoder Blocks · Masks and Information Sources
A standard encoder can read both earlier and later positions in the input. An autoregressive decoder uses a causal self-attention mask. In an encoder–decoder model, the decoder also uses cross-attention, with queries from the decoder representations and keys and values from the encoder output.
Encoder
Input → bidirectional self-attention → FFN. The encoder produces T contextual token representations.
Decoder-only
Input → causal self-attention → FFN. Each position reads the current and earlier positions.
Encoder–Decoder
Target prefix → causal self-attention → cross-attention to the source → FFN. Each sublayer has its own normalization and residual connection.
The output length equals the query length, which is the decoder sequence length. Cross-attention typically lets each query read all valid source positions. The padding mask blocks invalid source keys. Exclude padded target positions from the loss. Lab 01 switches between causal and full self-attention. Lesson 4.2 works through a numerical cross-attention example and explains how boolean mask conventions vary across PyTorch APIs. Lesson 4.5 extends the sequence view to vision tokens.
q_proj, k_proj, v_proj, and o_proj first. Then trace the reshapes and transposes, the mask, residual addition, and the FFN. Track the attention output separately from the block output. Establishing causal importance requires evidence beyond the attention weights.Parameter & Complexity · Architecture Budget
Let B be the batch size, T the sequence length, D the model width, H the number of heads, F the FFN width, and L the number of layers. These estimates cover dense equal-width multi-head attention in a block with no linear biases. LayerNorm contributes γ and β, and RMSNorm contributes only γ. The block parameter total excludes vocabulary parameters, input and output projections, position tables, and final normalization.
One MAC is one multiply–accumulate. Counting each multiply and add separately gives approximately two FLOPs per MAC for the main matrix products. The estimate excludes activation, normalization, softmax, masking, and backpropagation, and assumes dense operations. A causal mask leaves that dense estimate unchanged. Implementations can skip some masked operations. FlashAttention reduces the need to materialize the score matrix and reduces memory traffic. Exact dense attention still has quadratic arithmetic cost in sequence length.
Parameter & Complexity Calculator
| Operation | Parameters | Forward MACs |
|---|---|---|
| Projection | 2,359,296 | 9,663,676,416 |
| Attention products | 0 | 3,221,225,472 |
| FFN | 4,718,592 | 19,327,352,832 |
| Normalization | 3,072 | Excluded |
Engineering Experiment · Hidden-State Sequence Predictor
The experiment uses the synthetic dynamics generator, data split, and MSE metric from Lesson 4.1. The model observes only the input sequence u and predicts the final output y_T. The internal states a and b are hidden and start at zero for each sample.
The model projects scalar inputs to width 4, then adds fixed sinusoidal position encodings. One Pre-LayerNorm block has two attention heads and a GELU FFN of widths 4 → 8 → 4. A linear readout uses the final token representation. The default run uses 157 parameters, 32 training trajectories, and 24 validation trajectories, with sequence length 12. Full-batch Adam runs for 120 updates at learning rate 0.025 with seed 3. The browser computes gradients for all parameters by hand. Adjust the settings and click Train to run the experiment. The timeline replays the checkpoints saved every 10 updates.
Live Mini Transformer Training
Default benchmark · actual PyTorch results
| Model | Params | Train MSE | Validation MSE |
|---|---|---|---|
| MLP (0401 current input) | 13 | 0.094375 | 0.161051 |
| RNN (0401) | 33 | 0.001840 | 0.001939 |
| LSTM (0401) | 117 | 0.000217 | 0.000853 |
| GRU (0401) | 89 | 0.000448 | 0.001076 |
| Transformer, position on | 157 | 0.010724 | 0.033153 |
| Transformer, position off | 157 | 0.017174 | 0.033647 |
The initial validation MSE was 0.432935 with position encoding and 0.182951 without it. Both variants finished with similar validation MSE, above the values for the recurrent models in this experiment. The simulated system has a recurrent state, so an RNN may have a better-matched inductive bias. That hypothesis requires a controlled test. Parameter counts, initialization, and optimizer suitability vary across models, so the table compares these specific runs. With a single block and no position encoding, the final token attends to all earlier inputs and its output is invariant to permutations of those earlier tokens. The output therefore cannot encode an order-sensitive recurrence in that configuration. In deeper causal stacks, earlier token representations can already contain information about their prefixes.
Complete reproducible PyTorch code
Save the script as transformer0403.py and run python transformer0403.py. The model uses PyTorch LayerNorm, scaled dot-product attention (SDPA), and GELU. It stores linear weights explicitly as (in, out), matching the browser model. Training uses float64 and the default Adam parameters. The script runs with position encoding enabled and disabled.
import math
import torch
from torch import nn
from torch.nn import functional as F
torch.set_default_dtype(torch.float64)
torch.set_num_threads(1)
class RNG:
def __init__(self, seed): self.s = seed & 0xffffffff
def __call__(self):
self.s = (1664525*self.s+1013904223)&0xffffffff
return self.s / 4294967296
def dataset(n,T,seed):
r=RNG(seed); X=[]; Y=[]
for _ in range(n):
a=b=0.; seq=[]
for t in range(T):
u=2*r()-1; seq.append([u])
a=.88*a+.3*u; b=.4*b+.2*u
X.append(seq); Y.append([a+.4*b+.1*u+.12*math.sin(2*a)])
return torch.tensor(X),torch.tensor(Y)
def pos_encoding(T,D):
return torch.tensor([[math.sin(t/10000**(2*(j//2)/D)) if j%2==0 else math.cos(t/10000**(2*(j//2)/D)) for j in range(D)] for t in range(T)])
class MiniTransformer(nn.Module):
# Row-vector parameter layout: W[in,out]; no linear biases except input/output.
def __init__(self,D=4,H=2,Fdim=8,seed=3):
super().__init__(); assert D%H==0
self.D,self.H,self.Fdim=D,H,Fdim
r=RNG(seed+2000)
shapes=[('E',1,D),('eb',1,D),('Q',D,D),('K',D,D),('V',D,D),('O',D,D),('U',D,Fdim),('W',Fdim,D),('g1',1,D),('b1',1,D),('g2',1,D),('b2',1,D),('R',D,1),('rb',1,1)]
self.p=nn.ParameterDict()
for name,a,b in shapes:
v=[1. if name.startswith('g') else 0. if name in ('eb','b1','b2','rb') else (r()-.5)*.8 for _ in range(a*b)]
self.p[name]=nn.Parameter(torch.tensor(v).reshape(a,b))
def forward(self,x,position=True,causal=True):
p=self.p; B,T,_=x.shape; D,H=self.D,self.H; d=D//H
X=x@p['E']+p['eb']
if position: X=X+pos_encoding(T,D).to(x)
N=F.layer_norm(X,(D,),p['g1'].flatten(),p['b1'].flatten(),1e-5)
split=lambda a:a.reshape(B,T,H,d).transpose(1,2)
q,k,v=[split(N@p[n]) for n in ('Q','K','V')]
a=F.scaled_dot_product_attention(q,k,v,is_causal=causal,dropout_p=0)
A=a.transpose(1,2).reshape(B,T,D)@p['O']
Y=X+A
M=F.layer_norm(Y,(D,),p['g2'].flatten(),p['b2'].flatten(),1e-5)
Z=Y+F.gelu(M@p['U'],approximate='tanh')@p['W']
return Z[:,-1]@p['R']+p['rb']
def run(seed=3,T=12,D=4,H=2,lr=.025,updates=120,position=True,causal=True):
x,y=dataset(32,T,seed); v,w=dataset(24,T,seed+1000)
m=MiniTransformer(D,H,2*D,seed); opt=torch.optim.Adam(m.parameters(),lr=lr); hist=[]
for t in range(updates+1):
loss=(m(x,position,causal)-y).square().mean()
if t%10==0 or t==updates:
with torch.no_grad():
pred=m(v,position,causal); hist.append(dict(t=t,train=loss.item(),val=(pred-w).square().mean().item(),pred=pred.flatten().tolist(),p={k:p.detach().tolist() for k,p in m.p.items()}))
if t<updates:
opt.zero_grad(); loss.backward(); opt.step()
return hist
if __name__=='__main__':
for pos in (True,False):
h=run(position=pos);print('position',pos,'params',sum(p.numel() for p in MiniTransformer().parameters()),'initial',h[0]['val'],'final train',h[-1]['train'],'final val',h[-1]['val'])
Compact Multi-head Attention reference
This standalone NumPy forward pass uses the row-vector weight layout. It supports causal and unmasked attention, and focuses on attention without an FFN or gradient computation.
import numpy as np
def mha(x, wq, wk, wv, wo, heads, causal=True):
B, T, D = x.shape
assert D % heads == 0
d = D // heads
def split(a):
return a.reshape(B, T, heads, d).transpose(0, 2, 1, 3)
q, k, v = [split(x @ w) for w in (wq, wk, wv)]
s = q @ k.swapaxes(-1, -2) / np.sqrt(d)
if causal:
keep = np.tril(np.ones((T, T), dtype=bool))
s = np.where(keep, s, -np.inf)
e = np.exp(s - s.max(axis=-1, keepdims=True))
a = e / e.sum(axis=-1, keepdims=True)
o = (a @ v).transpose(0, 2, 1, 3).reshape(B, T, D)
return o @ wo, a
(B, T, D) to (B, H, T, d) to (B, H, T, T). Compare the NumPy output with SDPA and use autograd to check the gradients. Keep the data fixed when changing one design choice and recording validation metrics. The browser training experiment backpropagates through all four attention projections, the FFN, both LayerNorm operations, the input projection, and the readout. The RoPE, RMSNorm, and SwiGLU demos are separate from the training run.Authoritative References & Next Lesson
Attention Is All You Need
Sections 3.1–3.5 of Vaswani et al. (2017) cover the encoder and decoder, multi-head attention, the FFN, and positional encoding.
Original paperGLU Variants Improve Transformer
Shazeer (2020) studies SwiGLU and other gated feed-forward variants.
Original paperOn Layer Normalization in the Transformer Architecture
Xiong et al. (2020) analyze Pre-Norm and Post-Norm Transformers.
Original paperPyTorch & Textbooks
TransformerEncoderLayer · SDPA · Understanding Deep Learning Ch.12 · D2L Attention and Transformers
Lesson 4.4, Autoregressive Language Modeling, connects the Transformer block to a tokenizer, an embedding table, and a language modeling head. It covers next-token cross-entropy, perplexity, and autoregressive generation.
Previous lesson · 4.2 Attention Mechanisms · Curriculum · Next lesson · 4.4 Autoregressive Language Modeling