The Transformer as a Computation
A GPT-2 forward pass written out by hand, checked against the library, and used to count parameters, FLOPs and time component by component.
So far we have treated the middle of the model as a black box: embedding vectors go in, logits come out. This chapter opens the box by writing GPT-2 small’s entire forward pass by hand, in plain PyTorch tensor operations, and checking it against the real library.
The hand-written version uses the parameters from the pinned GPT-2 snapshot. On four prompts of 5 to 18 tokens, its logits differ from the installed Transformers implementation by at most \(1.22 \times 10^{-4}\), and at every tested position both pick the same top token. That is strong agreement for those inputs in that environment. It is not proof for every input, batch size, precision or runtime.
Once the computation is written down as a sequence of tensor operations, shapes and parameters, we can do useful things with it:
- count every parameter and predict the total exactly;
- estimate how much arithmetic a token costs, and how that changes with context length;
- inspect intermediate values, such as unusually large activations;
- test properties directly, such as whether a later token can influence an earlier prediction.
Some important properties do not follow from arithmetic alone. Peak memory, wall-clock time, floating-point differences and the effect of optimised kernels have to be measured. Throughout the chapter we keep three kinds of statement apart: architectural facts (what the computation is), cost estimates (how much arithmetic it implies) and measurements (what one machine actually did).
Where this sits
What Is Inference? found that the forward pass dominated one simple request. From Training to Execution inventoried the model artefact, including causal-mask buffers that are not learned parameters. Tokens, Embeddings and Probability covered the first and last steps: the embedding lookup and the tied output projection. This chapter fills in everything between.
The Inference Lab gains two instruments:
- A readable reference implementation,
examples/ch04/gpt2_from_scratch.py, that can be compared with the library’s GPT-2 for stated inputs, devices, dtypes and tolerances. It is a working reference, not a mathematical proof or a universal oracle for other architectures. - A cost model,
parameter_count(config)andflops_per_token(config, context), that counts parameters and matrix-multiplication arithmetic.
Both matter for the rest of the book and the wider Pi series. A fast GPU kernel or serving runtime can be checked against a readable reference by comparing intermediate tensors, final logits and chosen tokens. Agreement on a handful of examples is useful evidence; trustworthy comparison also needs artefact identity, stated tolerances, input coverage and a plan for nondeterminism. Later optimisation chapters build on that discipline rather than treating speed alone as success.
The whole computation
GPT-2 small’s shape is fixed by a handful of numbers:
| Symbol | Meaning | GPT-2 small |
|---|---|---|
| \(L\) | Decoder blocks (layers) | 12 |
| \(d\) | Model width | 768 |
| \(h\) | Attention heads | 12 |
| \(d_h\) | Width of each head (\(d/h\)) | 64 |
| \(4d\) | MLP hidden width | 3,072 |
| \(V\) | Vocabulary size | 50,257 |
| — | Learned position rows | 1,024 |
For a batch of \(B\) sequences, each \(T\) tokens long, the full forward pass is short enough to read in one go. (It assumes evaluation mode, valid ids and positions, and a full-sequence pass rather than cached incremental decoding.)
x = wte[ids] + wpe[0..T-1] # [B, T, d]
for layer in 1..12:
x = x + attention(layer_norm(x)) # [B, T, d]
x = x + mlp(layer_norm(x)) # [B, T, d]
x = layer_norm(x)
logits = x @ wte.T # [B, T, V]
The central object is the residual stream \(x\), a tensor of shape \([B,T,d]\): one 768-number vector per token. Each block reads it, computes something, and adds the result back. Attention adds first, then the MLP.
One structural fact matters more than any other: in GPT-2, attention is the only operation that moves information between positions. Layer norm and the MLP work on each position independently, and the position embedding is a per-position lookup. Causal attention lets position \(t\) see only positions up to \(t\). That structure is what makes it possible to reuse earlier work during generation, as Key-Value Caching will show. It does not mean that a full-prefix implementation automatically avoids recomputing old work; it does not.
The code is examples/ch04/gpt2_from_scratch.py. It uses matrix multiplication, elementwise arithmetic, torch.softmax, square roots and tanh, and builds an explicit causal mask. One detail trips people up: GPT-2’s Hugging Face Conv1D layers store weights as \([\text{in},\text{out}]\), so the operation is x @ W + b, the reverse of the convention for torch.nn.Linear. The reference exposes every intermediate rather than calling a fused attention operator. That makes it easy to inspect, not fast.
The rest of this section follows the residual stream through the pass, one operation at a time.
Embeddings and positions
The pass begins by adding two lookups. Each token at position \(t\) (counting from zero) starts as:
Without position embeddings, GPT-2 would lose its explicit record of absolute position. (It would not become a pure “bag of tokens”: the causal mask still gives each position a different visible prefix. But that is not a general-purpose positional signal.)
The table has 1,024 rows, so position index 1,024 does not exist for this checkpoint and code path. That is a limit of this model, not of attention in general. Rotary and other position methods change the engineering constraints without making context unlimited; Multi-Head and Multi-Latent Attention, Sliding-Window Attention and Long-Context Inference cover them.
The residual stream
Each sublayer is wrapped like this:
A look inside the stream
The reference’s trace option records summary statistics of the residual stream after each block. On one 17-token prompt:
| After layer | Max absolute value | Position | Dimension | Median absolute value |
|---|---|---|---|---|
| 1 | 95 | 0 | 138 | 0.58 |
| 2 | 588 | 0 | 138 | 0.69 |
| 3 | 2,460 | 0 | 447 | 0.81 |
| 6 | 2,836 | 0 | 447 | 1.19 |
| 11 | 2,956 | 0 | 447 | 2.77 |
| 12 | 338 | 0 | 447 | 3.27 |
The typical value stays small, between about 0.6 and 3.3. But from block 3 to block 11, a single entry, at position 0 and dimension 447, is enormous, reaching about 2,956. Its effect on overall statistics is dramatic: at block 4 the root-mean-square value across all positions is about 23.8, but only 2.5 if position 0 is left out. (After block 12, the two are about 15.9 and 16.1.)
This is one prompt, not a survey of activation outliers. It suggests why reduced precision may be tricky: if this pattern were typical, a single scale factor chosen to fit 2,956 would leave little resolution for values near 1. Quantization and Numerical Precision tests this properly, comparing errors under different scaling schemes across prompts rather than assuming one global scale must fail.
Layer normalisation
Layer normalisation rescales the 768 features of each token so they have zero mean and unit variance, then applies a learned scale and shift. With population variance, as in the chapter’s code:
Each instance has 1,536 parameters, and GPT-2 small has 25 of them (two per block plus a final one). Layer norm does almost no matrix multiplication, so the matmul-only cost model below ignores it. It still takes time, as the measurements will show: “few FLOPs” is not “zero cost”.
Attention
The question. How does information get from one token to another?
The intuition. Each position asks a question (“what am I looking for?”), each position advertises what it offers (“this is what I contain”), and each position carries some content to pass on. A position compares its question with every earlier position’s advertisement, turns those comparisons into weights, and takes a weighted average of their content. Those three roles are the query, key and value.
The mechanism. GPT-2 normalises the stream, then creates all three with one learned projection:
| Step | Operation | Shape |
|---|---|---|
| 1 | Combined projection | \([B,T,3d]\) = \([B,T,2304]\) |
| 2 | Split into Q, K, V and reshape into 12 heads | each \([B,h,T,d_h]\) = \([B,12,T,64]\) |
| 3 | Scores: \(QK^\top/\sqrt{d_h}\), plus mask | \([B,h,T,T]\) |
| 4 | Softmax over keys | \([B,h,T,T]\) |
| 5 | Weighted sum of values | \([B,h,T,d_h]\) |
| 6 | Merge heads | \([B,T,d]\) |
| 7 | Output projection \(W_o\in\mathbb{R}^{d\times d}\) | \([B,T,d]\) |
In symbols, for each head:
Why divide by \(\sqrt{d_h}\)? If query and key components were independent, with mean zero and variance one, their dot product over \(d_h\) terms would have variance \(d_h\). Dividing by \(\sqrt{d_h}\) keeps the scores on a similar scale whatever the head width, so the softmax does not saturate. That is the design motivation; real learned activations need not meet those assumptions, and we did not measure them.
The consequence: quadratic storage. Steps 3 and 4 produce \(T \times T\) matrices for every head. In this naive implementation both \(S\) and \(A\) hold \(B h T^2\) numbers. At \(B=1\), \(h=12\) and \(T=1024\), one such float32 tensor takes:
The limitation. Quadratic storage is a property of this implementation, not of attention itself. The reference computes the full \(T\times T\) product and masks the upper triangle afterwards. Algorithms such as FlashAttention tile the computation so the full matrix never has to be stored in high-bandwidth memory. Their output is the same attention, up to floating-point differences. Attention and Its Computational Cost starts exploring that design space.
Testing the mask
The mask is supposed to guarantee that a prediction at one position cannot depend on any later token. Rather than trust a diagram, gpt2_from_scratch.py mask tests it: it changes the tenth input token and checks whether the logits at the nine earlier positions change.
| Largest change in earlier logits | Earlier positions whose top token changed | |
|---|---|---|
| With causal mask | 0.0 exactly | 0 of 9 |
| Without causal mask | 15.9 | 3 of 9 |
With the mask, earlier positions were bit-for-bit unchanged. Without it, the future token leaked backwards and changed three earlier predictions. (The tenth position itself changes either way, since its own token changed.)
The property that caching relies on is the absence of any dependency on future tokens. The mask guarantees that mathematically: masked scores are \(-\infty\), so their weights are exactly zero. Bit-for-bit equality is a stronger, separate observation about this particular run. Two implementations that add numbers in a different order need not produce identical bits, so later kernels should be tested for both causal isolation and agreement within a tolerance.
The feed-forward network
The second sublayer works on each position on its own. It expands the 768 features to 3,072, applies a non-linearity, and projects back:
With biases, the two MLP projections hold 4,722,432 parameters per block. Because the MLP’s cost per position does not depend on sequence length, it dominates the arithmetic at short contexts, as we are about to see.
Counting what is there
The shapes, plus GPT-2’s bias conventions and weight tying, are enough to predict every parameter. parameter_count adds up the embeddings, all twelve blocks’ attention and MLP projections, and all 25 layer norms:
| Component | Parameters | Share |
|---|---|---|
| Token embedding (also the output projection) | 38,597,376 | 31.0% |
| Position embedding | 786,432 | 0.6% |
| Attention: Q, K, V projection (12 layers) | 21,261,312 | 17.1% |
| Attention: output projection | 7,087,104 | 5.7% |
| Feed-forward: up projection | 28,348,416 | 22.8% |
| Feed-forward: down projection | 28,320,768 | 22.8% |
| Layer norms (25 instances) | 38,400 | 0.03% |
| Total | 124,439,808 |
The prediction is 124,439,808, exactly equal to sum(p.numel() for p in model.parameters()) in the recorded run. Roughly: feed-forward 45.5%, tied embeddings 31.0%, attention 22.8%.
Matching the total catches mistakes such as a missing bias or a forgotten final layer norm. But a matching total alone cannot prove that every shape, weight mapping and operation is right; that is what the numerical comparison later in the chapter is for.
Counting what it costs
Define the workload first. “FLOPs per token” means different things for different workloads, and confusing them is a common error. The convention: a multiply-accumulate counts as two FLOPs, so multiplying a \([T,m]\) matrix by an \([m,n]\) matrix costs about \(2Tmn\).
flops_per_token(config, context) counts the matrix multiplications for one query position attending over \(T\) positions, including itself. That is the extra work of one decode step when earlier keys and values are cached:
| Workload | What it counts | Use |
|---|---|---|
| Per query (this formula) | One new position attending over \(T\) | Marginal cost of a cached decode step |
| Dense full prefix | All \(T\) positions, with the full \(T\times T\) attention product computed before masking | What gpt2_from_scratch.py actually executes |
| Uncached generation | A full-prefix pass repeated at every step | Chapter 1’s baseline loop |
The whole-sequence dense matmul count, matching the reference code, is \(T\bigl[L(24d^2)+2Vd\bigr]+4LdT^2\).
For GPT-2 small, the per-query estimate, with all vocabulary logits computed, is:
| Context \(T\) | MFLOP per query | QK + AV | MLP | Vocabulary projection |
|---|---|---|---|---|
| 16 | 247.7 | 0.2% | 45.7% | 31.2% |
| 128 | 251.8 | 1.9% | 45.0% | 30.7% |
| 512 | 265.9 | 7.1% | 42.6% | 29.0% |
| 1,024 | 284.8 | 13.3% | 39.8% | 27.1% |
Three consequences follow.
Per-query work grows slowly with context, for this model and range. From 16 to 1,024 tokens the estimate rises from 247.7 to 284.8 MFLOP, about 15%. That does not mean uncached generation latency is nearly flat: re-running the whole prefix repeats the projection and MLP work for every earlier position. Nor does it mean cached decoding is flat: memory bandwidth, scheduling and cache size also matter. Autoregressive Generation separates these paths.
The vocabulary projection is large, and often unnecessary. One position’s output projection costs \(2Vd=77{,}194{,}752\) FLOPs, about 31% of the short-context estimate. A full-sequence implementation that projects every position to vocabulary scores wastes most of that work during generation, because only the last position’s scores are needed. Skipping the others could, in principle, remove roughly 30% of the matmul work; that is a prediction, not a measured speed-up (exercise 6 measures it).
Chapter 1’s rough estimate is consistent with the formula. At context 16, the formula gives 247.7 million FLOPs, about 0.248 GFLOP, consistent with the 0.25 GFLOP heuristic used in What Is Inference?. This is a consistency check of the formula, not a hardware counter.
Where the time goes
FLOP counts ignore the cost of moving data, launching operations and running elementwise steps. So we also timed the reference.
The set-up. The full GPT-2 reference ran on random input sequences of 16, 128 and 512 tokens, in float32, on one CPU thread, with one warm-up and five recorded runs. Each component’s time is its median over the runs, and the total is the sum of those medians (not the median of whole-run times).
| Tokens | Total (s) | Attention time | MLP time | Output time | Layer-norm time | Dense-matmul GFLOP/s* |
|---|---|---|---|---|---|---|
| 16 | 0.129 | 25.6% | 43.3% | 28.1% | 2.9% | 30.7 |
| 128 | 0.452 | 24.6% | 45.7% | 27.8% | 1.9% | 71.3 |
| 512 | 1.936 | 34.7% | 40.6% | 23.2% | 1.4% | 70.3 |
Dense matmul FLOPs divided by the archived sum of component-median times. A derived rate, not a hardware counter. See the correction note below.
A correction to the archived report. The stored results file computes GFLOP/s using a triangular attention count, which assumes masked entries are never computed. But
attention()computes the full dense \(T\times T\) product and masks it afterwards. The table above recomputes the rate using the dense count that matches the executed code, from the same recorded times; nothing was re-run. The archived values were 30.7, 70.7 and 67.8 GFLOP/s, and they should not be compared with the dense implementation as if they counted its real work. The archived FLOP shares used the same approximation and need the same update (exercise 4).
Three observations, each with a different status.
Throughput rises with size (measured, derived rate). The effective rate is about 30.7 GFLOP/s at 16 tokens and about 71 at 128 and 512. Chapter 1’s rough estimate of about 34 GFLOP/s at a similar short length is of the same order. Larger matrix operations generally use the hardware better, which fits these numbers, but the experiment does not isolate the cause.
Attention takes more time than its arithmetic suggests at 512 tokens (measured, plus arithmetic). Under the dense-operation count, attention (projections plus \(QK^\top\) and \(AV\)) is about 23.1%, 24.4% and 28.4% of matmul FLOPs at 16, 128 and 512 tokens. Its share of time is 25.6%, 24.6% and 34.7%. At 512 tokens, attention spends noticeably more time than its arithmetic share. Mask creation, writing scores, softmax, reshapes and memory allocation are plausible reasons, and their sizes all grow with \(T^2\) here. But memory traffic was not measured, so “attention is memory-bound here” remains a hypothesis.
Layer norm costs time without FLOPs (measured). It takes about 1.4–2.9% of measured time while contributing nothing to the matmul count. Elapsed time includes reductions, elementwise work, allocations and data movement. A FLOP count measures selected arithmetic; it is neither a lower bound on latency nor a reliable predictor on its own.
These shares describe one unfused, eager PyTorch implementation on one CPU thread. They are not results for the Transformers library’s own kernels, and they will not transfer to fused GPU implementations. FlashAttention’s results are useful context: they show that cutting the movement of attention intermediates can matter even when the arithmetic is unchanged. They do not verify any speed-up here.
Is it the same computation?
A hand-written reference is only useful if it computes the same thing as the real model. For each prompt, verify runs both with the same loaded parameters and compares the entire logit tensor, not just the next token:
| Prompt | Tokens | Largest |difference| | Mean |difference| | Same argmax at every position |
|---|---|---|---|---|
The capital of France is |
5 | \(7.6 \times 10^{-5}\) | \(1.9 \times 10^{-5}\) | yes |
An inference engine takes … into |
17 | \(7.6 \times 10^{-5}\) | \(1.2 \times 10^{-5}\) | yes |
def fibonacci(n): … |
14 | \(1.2 \times 10^{-4}\) | \(1.7 \times 10^{-5}\) | yes |
Once upon a time, … fisherman who |
18 | \(6.1 \times 10^{-5}\) | \(1.0 \times 10^{-5}\) | yes |
The largest difference anywhere is about \(1.22\times10^{-4}\), and the top token agrees at every tested position.
How small is that? The largest logit magnitudes were about 130, 171, 323 and 149, but magnitude alone is not an error bound. What matters for token choice is the gap between the top two scores: a tiny difference can flip the choice when they nearly tie. So the evidence is the absolute and mean differences together with the argmax checks. Future runs should also record the smallest top-two margin.
What this covers: four prompts, 5–18 tokens, batch of one, CPU float32, the installed library and the pinned snapshot. Two further tests add independent checks: a randomly initialised two-layer library GPT-2 with a batch of two sequences, compared to within \(10^{-4}\), and a small-model causal-isolation test. (Neither covers tiny_transformer.py, which is a different model; see the last item under Limits.) What it does not cover: sequences near 1,024 tokens, production batch shapes, lower precision or GPU kernels. A reference earns trust by expanding its coverage and investigating disagreements, not by declaring one universal tolerance in advance.
What is not canonical
“Transformer block” names a family resemblance, not an executable specification. GPT-2’s pre-norm decoder differs from post-norm Transformers, RMSNorm models, rotary-position variants, grouped-query or multi-query attention, and gated MLPs. Each difference changes parameter shapes, buffers, numerical operations, and what can be cached or fused.
So the artefact manifest from From Training to Execution must identify much more than a family name. What carries over to other architectures is the method: state the exact computation, derive its cost for a stated workload, and verify every optimisation against a reference with explicit acceptance criteria.
Inference Lab increment
The Lab now contains a readable GPT-2 reference and two arithmetic helpers:
forward(ids, weights, config, causal=True, trace=None): the eager reference, producing logits for every input position.causal=Falseis a deliberate fault injection that shows information leaking backwards;tracecollects per-block activation summaries.parameter_count(config): the learned-parameter inventory for the GPT-2-style architecture, including tied embeddings and biases.flops_per_token(config, context): the per-query matmul count. For the dense full-prefix reference, use \(T\bigl[L(24d^2)+2Vd\bigr]+4LdT^2\). Don’t substitute a triangular count for dense multiplication.
It also gains a verification discipline. Before declaring an optimisation equivalent, record the artefact identity, inputs, dtypes, device, maximum and mean logit differences, argmax or top-k agreement, and the acceptance tolerance. A mismatch means the optimisation needs investigating; it does not automatically make the output unusable.
The request record can now carry a predicted arithmetic cost alongside measured timings and artefact identity. It must also say which workload the estimate describes (a cached query, a full prefill or an uncached repeated pass), or two correctly computed numbers will be compared as if they described the same work. Memory Bandwidth and Compute Bottlenecks adds the data-movement side needed for a sound bottleneck analysis.
Limits of this chapter’s evidence
About the set-up
- One model, one environment. GPT-2 small, float32, CPU, one thread, one session. None of this extrapolates to a production GPU server.
- A reference, not a production kernel. The implementation uses unfused eager operations, dense attention and a request-sized mask. The Transformers library and fused kernels may schedule work quite differently.
About the cost model
- Matmul only. The FLOP formula excludes biases, embedding lookups, layer norm, GELU, softmax, residual additions and memory movement. It is not a latency model.
- The archived benchmark denominator needs fixing.
cmd_timinguses a triangular attention count although the code runs dense products. The dense rates shown here are recalculated from archived times; the code and stored evidence must be updated before publication.
About the measurements
- Agreement coverage is narrow. Four real-model prompts of 5–18 tokens, plus small-model tests. No full-context, half-precision or production multi-batch qualification.
- The residual trace is one prompt. Its outlier coordinate says nothing yet about typical activation statistics or quantisation error.
- The causal-equality result is one experiment. Mathematical independence from future tokens does not imply bit-for-bit equality across kernels.
- No hardware counters, fused kernels or GPU timing. The explanation for attention’s excess time share is a hypothesis.
About scope
- No claim of correctness for other architectures. RoPE, GQA, RMSNorm and other designs have not been reproduced by this reference.
tiny_transformer.pyis a different model, not a small GPT-2. It has bias-free attention projections, usesnn.GELU()rather than the tanh approximation, and does not tie its embedding to its output head. It is fine for shape reports and causal-mask tests, but its parameter count and logits should not be expected to match the GPT-2 cost model orgpt2_from_scratch.py.
What you should now be able to do
- Trace the tensor shapes through GPT-2’s full-sequence pass, including the attention score and probability matrices.
- Explain why the causal mask prevents information flowing from future tokens, and why bit-for-bit equality across kernels is a separate question.
- Derive GPT-2 small’s 124,439,808 parameters from its shapes, biases and weight tying.
- Distinguish per-query matmul FLOPs, dense full-prefix FLOPs and total uncached generation work, rather than calling all three “FLOPs per token”.
- Say which attention intermediates need quadratic storage in a naive implementation, and why a tiled exact-attention algorithm can avoid storing them.
- Compare a hand-written forward pass with a library using explicit tolerances, test coverage and logit margins.
- Keep measured time shares separate from arithmetic predictions and from hypotheses about memory traffic.
- Say which conclusions are specific to GPT-2 and which carry over to other transformers.
We now know what one forward pass computes and roughly what it costs. Generation runs that pass over and over, and the details of the loop around it (what gets recomputed, when to stop, how tokens reach the user) turn out to matter as much as the pass itself. Autoregressive Generation examines that loop.
Key terms
- Residual stream: the \([B,T,d]\) tensor that receives each sublayer’s contribution by addition.
- Pre-norm: layer normalisation on a sublayer’s input, before its residual addition.
- Layer normalisation: normalisation of each token’s feature vector with learned scale and shift.
- Query, key, value: projections used to compare positions and combine attended information.
- Head: one parallel attention computation with head dimension \(d_h\).
- Causal mask: exclusion of future keys from each query position.
- Dense attention: computing full \(T\times T\) score and probability matrices, including entries later masked.
- Feed-forward network (MLP): the independent per-token two-projection transformation with a wider hidden representation.
- FLOP estimate: an arithmetic operation count for a precisely stated workload; not a measured execution time.
- KV-cached query: one incremental token’s attention query using previously computed keys and values.
- Reference implementation: a readable executable baseline with bounded, demonstrated agreement to another implementation.
- Activation outlier: an activation magnitude unusually large relative to other values in an observed tensor; its prevalence requires measurement.
Reader exercises
- Evaluate
parameter_countagainst five GPT-2-style configurations instantiated through the library. Hold bias conventions and weight tying fixed. Separately show whytiny_transformer.pyis not covered by that formula. - Disable \(1/\sqrt{d_h}\) in the reference and compare attention-weight entropy with and without scaling. Preserve model, inputs, position and numerical dtype in the report.
- Replace tanh-approximate GELU with exact GELU. Report maximum and mean logit differences and the smallest top-two-logit margin, not only whether argmax changes.
- Repair the benchmark accounting: for \(T=16,128,512\), compute whole-sequence dense attention FLOPs as \(4LdT^2\) and compare them with the original triangular estimate \(2LdT(T+1)\). Recalculate GFLOP/s from the archived times. Update
cmd_timingandresearch/ch04/results.jsononly after tests verify the definition. - Extend
verifyto sequence lengths near 1,024 and batches larger than one. Define acceptance criteria before running it, and record both maximal absolute logit difference and token-selection disagreement. - Modify the reference to compute vocabulary logits only at the final position. Measure change in matmul count and wall-clock time independently; explain why they need not have the same percentage saving.
- Repeat the residual trace for at least five additional prompts. Report where the maximum occurs and compare scaling error under per-tensor versus per-channel quantisation before making a general outlier claim.
- Implement tiled or blockwise causal attention without storing all \(T^2\) probabilities, compare it with the dense reference and report peak allocated memory as well as output error. Do not claim a speedup without timing it.
References
- Vaswani et al. (2017), Attention Is All You Need — original scaled dot-product and multi-head attention, residual blocks and post-norm Transformer; background for the equations, not evidence for this CPU benchmark.
- Ba, Kiros and Hinton (2016), Layer Normalization — mathematical basis for feature-wise layer normalisation.
- Radford et al. (2019), Language Models are Unsupervised Multitask Learners — original GPT-2 model family and training context; implementation specifics are checked against the pinned artefact rather than inferred from the paper alone.
- Dao et al. (2022), FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness — why attention memory traffic and intermediate materialisation matter independently of a simple FLOP count; does not validate a local performance claim.
- OpenAI GPT-2 repository — primary model implementation and configuration reference.
- PyTorch numerical operations documentation — API behaviour for matrix products, softmax and layer normalisation; the experiment uses the versions recorded in
research/ch04/results.json.
Evidence in this chapter
| Claim | Evidence classification |
|---|---|
| Attention, layer norm and GPT-2-style decoder operations have the stated mathematical definitions | Established background; Vaswani et al., Ba et al., Radford et al. |
| FlashAttention reduces external-memory traffic without materialising the full attention matrix | Established published result; Dao et al.; not tested locally |
| GPT-2 small has 124,439,808 learned parameters under the stated configuration and tied-output convention | Book result: formula equals checkpoint parameter count |
| Reference logits agree with the library within \(1.22\times10^{-4}\) for four short prompts, with the same argmax at every tested position | Book result; bounded input/device/dtype coverage |
| Changing the last token caused an exact measured 0.0 difference at earlier positions with the mask and changed three earlier argmaxes without it | Book result; one input; causal non-dependence is the architectural invariant |
| Naive full attention materialises \(T^2\)-sized score and probability matrices | Established by the reference code and tensor shapes |
| Per-query matmul estimate grows from 247.7 to 284.8 MFLOP as context grows from 16 to 1,024 | Book arithmetic model; applies to the specified workload |
| Original timing report’s GFLOP/s uses a triangular count despite dense attention operations | Code/evidence audit finding; correction required in benchmark code and stored report |
| Corrected estimated dense-matmul throughput is about 30.7, 71.3 and 70.3 GFLOP/s at 16, 128 and 512 tokens | Recalculation from archived times; not a new measurement |
| Attention takes a larger elapsed-time share than its dense matmul share at 512 tokens | Book result plus corrected arithmetic comparison |
| That excess time is specifically caused by memory-bandwidth limits | Book hypothesis; memory traffic not measured |
| A residual coordinate reaches about 2,956 at position 0 | Book result; one prompt |
| Computing only the final vocabulary projection may remove approximately 30% of short-context matmul work | Arithmetic opportunity; wall-clock improvement not measured |
| GPU speed, reduced precision, fused attention, full-context equivalence and broader architectures | Not measured |