Check a transformer's shapes and causality
Trace a five-token forward pass through a tiny causal transformer and prove that changing the last token cannot change earlier logits.
“The transformer is the computation” is a claim that can be checked at two
levels. The first is shape: a batch of five token ids becomes a [1, 5, 8]
residual stream, two attention heads produce a [1, 2, 5, 5] score tensor, and
the language-model head produces [1, 5, 16] logits. The second is causality: a
change to the last input token must leave every earlier position’s output
unchanged.
This example runs both checks on a deliberately tiny model. It is not GPT-2 and does not claim to reproduce one. It makes the tensor flow and the mask inspectable at a size where every dimension can be read. The chapter’s separate GPT-2 script checks the stronger claim that a hand-written forward pass matches a library model.
Run it
From the canonical repository at commit
f958967d70992d7b09d9c75000bd8c543f1644d4:
python examples/ch04/tiny_transformer.py --seq-len 5 --vocab-size 16 --jsonPython 3.11 or later with PyTorch. CPU-only, seeded, no model download, network, GPU or credentials. It finishes in about a second.
Implementation
The mask is an upper-triangular boolean matrix with the diagonal excluded. It is
applied to the scaled scores before softmax, so a query at position i cannot
attend to a key at position j > i. causal_check changes the final token and
compares every earlier logit with the original.
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
# x: [batch, seq, d_model]
batch, seq, _ = x.shape
qkv = self.qkv(x).reshape(batch, seq, 3, self.n_heads, self.head_dim)
qkv = qkv.permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2]
# q,k,v: [batch, heads, seq, head_dim]
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
mask = torch.triu(torch.ones(seq, seq, device=x.device, dtype=torch.bool), diagonal=1)
scores = scores.masked_fill(mask, float("-inf"))
weights = torch.softmax(scores, dim=-1)
attended = torch.matmul(weights, v)
attended = attended.transpose(1, 2).reshape(batch, seq, self.d_model)
return self.out(attended), weights
def manual_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
"""Reference implementation for a single head or batched heads."""
head_dim = q.shape[-1]
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(head_dim)
seq = q.shape[-2]
mask = torch.triu(torch.ones(seq, seq, device=q.device, dtype=torch.bool), diagonal=1)
scores = scores.masked_fill(mask, float("-inf"))
weights = torch.softmax(scores, dim=-1)
return torch.matmul(weights, v)
def causal_check(model: TinyTransformer, input_ids: torch.Tensor) -> bool:
# Changing a future token must not change outputs at earlier positions.
base = model(input_ids)[0].clone()
modified = input_ids.clone()
modified[0, -1] = (modified[0, -1] + 1) % model.vocab_size
changed = model(modified)[0]
earlier = torch.allclose(base[:, :-1, :], changed[:, :-1, :], atol=1e-5)
return bool(earlier)Expected outcome
Observed with the command above (exit 0):
{
"input_ids": [
[
0,
1,
2,
3,
4
]
],
"logits_shape": [
1,
5,
16
],
"shape_report": {
"input_ids": [
1,
5
],
"token_embeddings": [
1,
5,
8
],
"attention_output": [
1,
2,
5,
5
],
"mlp_output": [
1,
5,
16
],
"logits": [
1,
5,
16
]
},
"causal_check": true
}The attention output in the report is the score tensor shape, not the final
attended values: two heads, five queries and five keys. causal_check: true
means every earlier position matched within 1e-5 after the last token changed.
Mechanism and limitations
Documented: the model has two blocks, two heads, d_model=8, d_ff=16, a
learned position embedding and a linear language-model head. The mask is applied
inside every attention layer. run_demo seeds PyTorch, builds the model, runs a
five-token input, and reports both shapes and the causality check. The tests
cover the shape report, the causal mask, manual_attention equivalence and the
model’s forward contract.
Observed: the command exited 0 with the shapes above and
causal_check: true. The targeted tests.test_ch04_transformer ran in a
36-test batch with Chapters 02, 03 and 05 and reported OK.
Not shown: that this model produces useful text; that its weights are
trained; that it matches GPT-2; or that the mask is the only source of causality
in a real architecture. The chapter’s GPT-2 comparison is a separate recorded run
(maximum absolute logit difference 6.1e-5 to 1.2e-4 on four prompts), not
this tiny model. No GPU, memory or throughput claim is made.
Challenge this result
Remove the two masked_fill lines and run the command again. Predict
causal_check before running: with the mask gone, the modified last token can
influence earlier positions through attention, so the check should become
false. Then restore the mask and change the last token to the same id; the
check should remain true but prove nothing, because nothing changed. Explain
why a causality test needs both a positive and a negative case.
Source and verification
Canonical source:
examples/ch04/tiny_transformer.py
at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests:
tests/test_ch04_transformer.py
.
Chapter: The Transformer as a Computation
.
The run above is a fresh local execution on Windows 11 with Python 3.13.15 and
PyTorch 2.6.0+cu124; it uses random weights, not a checkpoint.
Understand this example
Copy this prompt into your AI tool. No code runs here.
Apply this example
Copy this prompt into your AI tool. No code runs here.