Build a Causal Transformer Language Model Block by Block
Machine LearningModel answerLast updated
Write a decoder-only transformer from memory in PyTorch: embeddings, hand-written causal multi-head attention, feed-forward layers, residual wiring, and a logits head.
You are asked to write a small autoregressive transformer language model in Python, using PyTorch or NumPy, with no template to start from. Explain the tensor shape at each step as you write.
Task
Build a model that takes a batch of integer token IDs and returns, for every position, a score for each vocabulary entry as the next token.
The model must include:
- token embeddings combined with positional information;
- multi-head self-attention that you implement yourself, with a causal mask so that each position can only look at itself and earlier positions;
- a position-wise feed-forward network;
- residual connections and layer normalization around each sub-layer;
- a stack of identical blocks, followed by a final projection to vocabulary logits.
Interface
- Input: an integer tensor of shape
(batch, seq_len), whereseq_lenis at most a maximum context length given to the constructor. - Output: a float tensor of shape
(batch, seq_len, vocab_size). - Causality: the logits at position
tmay depend only on input tokens0..t. - Constructor arguments: vocabulary size, maximum context length, model width, number of heads, number of layers, and feed-forward hidden width.
Rules
- Primitive layers (linear, embedding, layer norm, softmax, dropout) are allowed.
- Prebuilt attention or transformer modules are not allowed.
What to discuss
Before coding, state your assumptions: decoder-only versus encoder-decoder, whether padding must be handled, and your choice of pre-norm or post-norm and of positional encoding. After coding, show how you would verify that the model runs and that future tokens cannot influence earlier outputs, and comment on compute and memory cost.
Hints
Hint 1
Split the model width into `n_heads` chunks of size `head_dim = d_model / n_heads`. Project once to Q, K and V, reshape to `(B, H, T, head_dim)`, and merge back with a transpose and reshape at the end.
Hint 2
Scale the score matrix `Q @ K^T` by `1/sqrt(head_dim)`, then set entries above the diagonal to negative infinity BEFORE the softmax, so that masked positions get exactly zero weight.
Hint 3
To test for leakage, run the model on a sequence, change only the last token, and check that the logits at all earlier positions are unchanged.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions to state up front
- Decoder-only language model (no cross-attention), forward pass first. I would add the loss and generation loop if time allows.
- Pre-norm blocks (LayerNorm before each sub-layer), which train more stably than post-norm at depth and need no warm-up tricks to the same degree.
- Learned positional embeddings of size
(max_len, d_model). Sinusoidal or rotary encodings are alternatives. - No padding handling by default. With right-padding and a causal mask, real tokens never attend to pads, so only the loss needs to ignore them. Left-padding would need an extra key mask.
Design and shapes
Let B be the batch size, T the sequence length, D the model width, H the number of heads and d = D/H the head dimension.
- Embedding:
ids (B,T)becomestok (B,T,D). Addpos (T,D), which broadcasts over the batch. - Attention:
- One linear layer maps
x (B,T,D)toqkv (B,T,3D), which is split into Q, K and V. - Each is reshaped to
(B,T,H,d)and transposed to(B,H,T,d). - Scores are
Q @ K^T / sqrt(d), shape(B,H,T,T). - The mask sets scores where
j > ito-inf. Softmax over the last axis then gives zero weight to future positions. - Weights
@ Vgives(B,H,T,d). Transpose and reshape to(B,T,D), then apply the output projection.
- One linear layer maps
- Feed-forward:
Linear(D, F), then GELU, thenLinear(F, D), applied independently at each position.Fis typically4D. - Block (pre-norm):
x = x + attn(ln1(x)), thenx = x + ffn(ln2(x)). - Head: a final layer norm, then
Linear(D, V)gives logits(B,T,V). Tying this weight to the token embedding savesV*Dparameters and usually helps.
Code
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class CausalSelfAttention(nn.Module):
def __init__(self, d_model, n_heads, max_len, dropout=0.0):
super().__init__()
assert d_model % n_heads == 0
self.h = n_heads
self.d = d_model // n_heads
self.qkv = nn.Linear(d_model, 3 * d_model)
self.out = nn.Linear(d_model, d_model)
self.drop = nn.Dropout(dropout)
mask = torch.tril(torch.ones(max_len, max_len, dtype=torch.bool))
self.register_buffer("mask", mask, persistent=False)
def forward(self, x):
B, T, D = x.shape
q, k, v = self.qkv(x).split(D, dim=-1)
q, k, v = (t.view(B, T, self.h, self.d).transpose(1, 2) for t in (q, k, v))
scores = q @ k.transpose(-2, -1) / math.sqrt(self.d) # (B,H,T,T)
scores = scores.masked_fill(~self.mask[:T, :T], float("-inf"))
w = self.drop(F.softmax(scores, dim=-1))
y = (w @ v).transpose(1, 2).reshape(B, T, D) # (B,T,D)
return self.out(y)
class Block(nn.Module):
def __init__(self, d_model, n_heads, d_ff, max_len, dropout=0.0):
super().__init__()
self.ln1 = nn.LayerNorm(d_model)
self.attn = CausalSelfAttention(d_model, n_heads, max_len, dropout)
self.ln2 = nn.LayerNorm(d_model)
self.ffn = nn.Sequential(
nn.Linear(d_model, d_ff), nn.GELU(),
nn.Linear(d_ff, d_model), nn.Dropout(dropout))
def forward(self, x):
x = x + self.attn(self.ln1(x))
return x + self.ffn(self.ln2(x))
class TransformerDecoder(nn.Module):
def __init__(self, vocab_size, max_len, d_model, n_heads, n_layers, d_ff, dropout=0.0):
super().__init__()
self.max_len = max_len
self.tok = nn.Embedding(vocab_size, d_model)
self.pos = nn.Embedding(max_len, d_model)
self.blocks = nn.ModuleList(
Block(d_model, n_heads, d_ff, max_len, dropout) for _ in range(n_layers))
self.ln_f = nn.LayerNorm(d_model)
self.head = nn.Linear(d_model, vocab_size, bias=False)
self.head.weight = self.tok.weight # weight tying
def forward(self, ids):
B, T = ids.shape
assert T <= self.max_len
x = self.tok(ids) + self.pos(torch.arange(T, device=ids.device))
for blk in self.blocks:
x = blk(x)
return self.head(self.ln_f(x)) # (B,T,V)
Verification
- Shape test: random IDs of shape
(2, 10)should produce logits of shape(2, 10, V). - Leakage test: in eval mode, copy the input, change only the last token, and run both. Logits at positions
0..T-2must match withtorch.allclose, while the last position should differ. - Overfit test: training on one tiny batch should drive the loss close to zero. This catches wiring bugs the shape test misses.
Cost
- Attention time and memory scale as
O(T^2 * D)andO(B*H*T^2)for the score matrix. This is the bottleneck for long contexts, which is why fused kernels such as FlashAttention avoid materializing it. - Parameters per block are about
4D^2for attention plus2*D*F(about8D^2) for the feed-forward network, so roughly12D^2per layer. The embedding addsV*D. - For generation, a KV cache avoids recomputing keys and values for earlier tokens, which reduces per-step cost from
O(T^2)toO(T).
Common mistakes
- Applying the mask after the softmax, which leaves rows that do not sum to one and still leaks information.
- Scaling by
sqrt(D)instead ofsqrt(d). - Calling
viewaftertransposewithoutcontiguousor usingreshape, which raises an error or scrambles data. - Softmax over the wrong axis (it must be over keys, the last axis).
- Forgetting the final layer norm in a pre-norm model.
- Using
0instead of-infin the mask, which still gives masked positions nonzero weight. - Mixing pre-norm and post-norm wiring inconsistently across the block.