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.
I reconstructed GPT-2 small’s forward pass in unfused PyTorch tensor operations: token and position lookups, twelve pre-normalised attention-and-MLP blocks, final layer normalisation and a tied vocabulary projection. With parameters from the pinned GPT-2 snapshot, its logits differ from the installed Transformers implementation by at most \(1.22 \times 10^{-4}\) across four prompts of 5–18 tokens. Every tested position has the same highest-scoring token. This is a strong, reproducible agreement check for those inputs and that environment—not proof that every input, batch size, numerical precision or runtime will behave identically.
The chapter’s claim is practical: a particular transformer can be described as an executable sequence of tensor operations, shapes and parameter values. From that description we can count parameters, estimate matrix-multiplication work, inspect intermediates and design falsifiable comparisons. Not every important property follows from arithmetic alone: peak memory, wall-clock time, floating-point differences and the effects of optimised kernels require separate measurements.
Chapter 3 followed text through tokenisation, an embedding lookup, vocabulary logits and token selection. Here we open the computation between embeddings and logits, using GPT-2 small as a concrete reference. The method is to state the computation, run it against a second implementation and distinguish three things throughout: an architectural identity, a cost-model estimate and a machine-specific measurement.
Where this sits
Chapter 1 measured forward-pass latency for a deliberately simple generation path; its reported share belongs to that particular request, not to inference workloads generally. Chapter 2 inventoried the model artefact, including causal-mask buffers that are not learned parameters. Chapter 3 identified the tied token-embedding and output-projection weights. This chapter explains the remaining decoder blocks and connects their structure to measurable cost.
The Inference Lab adds two instruments. First, a readable reference implementation in examples/ch04/gpt2_from_scratch.py that can be compared with the library’s GPT-2 for specified inputs, devices, dtypes and tolerances. It is an operational reference, not a mathematical proof of correctness or a universal oracle for other architectures. Second, a cost model in parameter_count(config) and flops_per_token(config, context) that counts parameters and selected matrix-multiplication FLOPs. The cost model must be interpreted alongside the implementation: a masked dense matrix product can execute work that an ideal triangular causal-attention count omits.
This distinction also matters across the Pi books. A GPU kernel or serving runtime can be checked against a readable reference by comparing intermediate tensors, final logits and selected tokens under controlled conditions. A matching output on a handful of examples is useful evidence, but trustworthy cross-runtime comparison also needs artefact identity, numerical tolerances, input coverage and explicit handling of nondeterminism. Later optimisation chapters will build on that discipline rather than treating speed alone as success.
The whole computation
GPT-2 small has \(L=12\) decoder blocks, model width \(d=768\), \(h=12\) attention heads of width \(d_h=64\), MLP width \(4d=3072\), vocabulary size \(V=50{,}257\), and 1,024 learned positional rows. With batch size \(B\) and sequence length \(T\), the inference-time computation below assumes evaluation mode (dropout disabled), valid token and position indices, and an ordinary full-sequence forward pass rather than KV-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]
flowchart TD
IDS[token ids] --> EMB[token embedding + position embedding]
EMB --> X0[residual stream x]
X0 --> LN1[layer norm]
LN1 --> ATT[causal self-attention]
ATT --> ADD1[add]
X0 --> ADD1
ADD1 --> LN2[layer norm]
LN2 --> MLP[feed-forward network]
MLP --> ADD2[add]
ADD1 --> ADD2
ADD2 --> NEXT[next layer, ×12]
NEXT --> LNF[final layer norm]
LNF --> OUT[× embedding table transposed]
OUT --> LOG[logits]
The residual stream is a tensor of shape \([B,T,d]\). At each block, attention and then the MLP add their results to it. In GPT-2, attention is the only sublayer that mixes information across token positions; layer norm and the MLP operate separately on each position, while position embeddings are looked up separately. Causal attention restricts position \(t\) to a prefix ending at \(t\). That dependency structure permits reuse of earlier keys and values during incremental generation, as Chapter 10 will show. It does not mean a full-prefix implementation automatically avoids recomputing old work.
The corresponding code is examples/ch04/gpt2_from_scratch.py. Its building blocks include matrix multiplication, elementwise arithmetic, torch.softmax, square roots and tanh; the code also constructs an explicit causal mask. GPT-2’s Hugging Face Conv1D parameter storage uses weight matrices in \([\text{in},\text{out}]\) order, so the forward operation is x @ W + b, unlike the stored convention for torch.nn.Linear. The reference intentionally exposes intermediates instead of relying on a fused attention operator. That makes it easy to inspect, not fast by definition.
Embeddings and positions
The first calculation adds token and position vectors. The token table \(E_{\text{tok}}\in\mathbb{R}^{50257\times768}\) was examined in Chapter 3; the absolute-position table \(E_{\text{pos}}\in\mathbb{R}^{1024\times768}\) adds 786,432 learned parameters. In a full forward pass with positions numbered from zero, each token at position \(t\) starts with:
The residual stream
Each sublayer is wrapped as
A residual trace is useful before studying reduced precision. The reference’s trace option records absolute maxima, median magnitudes and RMS values after each complete transformer block, before the final layer norm. On one 17-token prompt, the recorded values were:
| 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 |
For this prompt the largest residual entry from block 3 through block 11 occurs at position 0, dimension 447, and reaches about 2,956. At block 4 the RMS across all token positions is about 23.8, compared with 2.5 when position 0 is excluded. After block 12, the corresponding RMS values are about 15.9 and 16.1. These are observations from a single trace, not a measured distribution of activation outliers. They motivate a test for quantisation: compare error under different scaling granularities and prompts rather than assuming that one global scale must fail.
Layer normalisation
Layer normalisation acts separately on the \(d\) features at each token position. With population variance as used in the chapter’s implementation, its forward formula is:
Attention
Attention creates cross-position dependencies. GPT-2 first applies the attention sublayer’s layer norm, then uses a single learned affine projection to create queries, keys and values together:
The \(1/\sqrt{d_h}\) factor is justified by the familiar variance argument: if the components of queries and keys are independent, zero-mean and unit-variance, a dot product of \(d_h\) terms has variance \(d_h\). Scaling makes the magnitude less sensitive to head width. Real learned activations need not satisfy those assumptions; the argument explains the design motivation, not a measurement of variance in this GPT-2 checkpoint.
Quadratic attention storage. In this naive full-sequence implementation, both \(S\) and \(A\) contain \(B h T^2\) elements. At \(B=1\), \(h=12\), \(T=1024\), float32 storage for one such tensor is \(12\times1024^2\times4=50{,}331{,}648\) bytes, or about 50.3 MB (48 MiB). Both can coexist during execution, and temporary masks or backward activations can add further memory. In addition, Chapter 2 identified a precomputed maximum-length mask buffer in the checkpoint; its fixed allocation should not be confused with a request-sized attention score matrix. The reference computes dense \(T\times T\) matrix products and masks the upper triangle afterwards. Algorithms such as FlashAttention instead tile the computation to reduce external-memory traffic and avoid materialising the full attention matrix in high-bandwidth memory; their output is mathematically exact attention, subject to floating-point differences. That is the design space Chapter 8 begins to explore.
What the mask does
The mask enforces the decoder’s intended information flow: the prediction at an earlier position must not depend on a later input token. To test this rather than infer it from a diagram, gpt2_from_scratch.py mask changes the tenth input token and compares logits at the preceding nine positions. The reported result for the pinned GPT-2 run is:
| Largest change in earlier logits | Earlier positions whose most probable token changed | |
|---|---|---|
| With causal mask | 0.0 exactly | 0 of 9 |
| Without causal mask | 15.9 | 3 of 9 |
With masking enabled, the two runs produced identical earlier-position logits in this experiment; without masking, three earlier positions changed their highest-scoring token, and the maximum earlier-logit difference was 15.9. The final position was not expected to remain unchanged in either case, because its own token was changed. The important invariant for caching is absence of a dependency on future tokens. This observed bitwise agreement is a stronger property of this particular execution, not a promise about every alternative kernel or hardware configuration.
Mathematically, causal masking sets the contribution from every future key to zero. In this implementation those masked score entries are \(-\infty\), so their exponentials are exactly zero in the softmax. That explains why changing only a future token cannot affect an earlier position’s intended function. It does not require two implementations with different reduction orders to produce identical floating-point bit patterns. Later kernels should be tested both for causal isolation and for agreement with the reference under an appropriate tolerance.
The feed-forward network
The second sublayer acts on each position separately:
Counting what is there
The shapes and bias conventions are enough to predict the parameter inventory of this GPT-2-style, tied-output decoder. The parameter_count helper counts embeddings, all 12 sets of attention and MLP projections, and both layer norms in every block plus the final layer norm. Against the loaded checkpoint, it gives:
| 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 predicted total is 124,439,808 learned parameters, exactly equal to sum(p.numel() for p in model.parameters()) in the recorded run. Feed-forward projections account for about 45.5%, attention projections about 22.8%, and the tied token embeddings about 31.0%. This agreement catches omissions such as a projection bias or final layer norm, but a matching scalar total alone would not prove every tensor shape, weight mapping or forward operation correct. The numerical forward comparison provides a complementary check.
Counting what it costs
Define the workload before counting FLOPs. Under the conventional approximation of two FLOPs for each multiply-accumulate, multiplying a \([T,m]\) matrix by an \([m,n]\) matrix costs about \(2Tmn\) FLOPs. The function flops_per_token(config, context) counts weighted projections and the two attention matrix products for one query position attending over a context of length \(T\), including its own position. This is a useful marginal-work model for incremental KV-cached decoding, and it also expresses the work attributable to a position in dense full-sequence attention. It does not by itself describe the total work of repeatedly recomputing an uncached prefix. In particular, the runnable reference’s full-prefix attention uses dense matrix multiplication even for entries later removed by the causal mask. Its whole-sequence executed arithmetic must be counted separately.
| 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 are worth drawing out.
The weighted work per query changes slowly with context for this model and context range. In the stated per-query model, the estimate rises from 247.7 to 284.8 MFLOP as context grows from 16 to 1,024 tokens, about 15%. That is not a claim that uncached generation latency is nearly constant: recomputing an ever-longer prefix repeats the projection and MLP work for all preceding positions. Nor does it imply constant wall-clock time under KV caching; memory bandwidth, scheduling and cache size still matter. Chapter 5 separates those paths.
The vocabulary projection is substantial—and often unnecessary at earlier positions during generation. For one query it costs \(2Vd=77{,}194{,}752\) FLOPs, about 31% of the short-context matmul estimate. In a full-sequence implementation that projects every hidden position into vocabulary logits, a decoder needing only the final next-token distribution can in principle omit earlier-position projections. The arithmetic saving depends on the operation actually skipped and its context; the time saving also depends on the runtime and memory traffic. The approximately 30% matmul fraction is a prediction, not a benchmarked speedup.
Chapter 1’s estimate is consistent with the model. At context length 16 the formula gives 247.7 million matmul FLOPs for one query position, approximately 0.248 GFLOP. That is a consistency check for the specified formula, not an independently measured hardware work counter.
Where the time goes
FLOP estimates omit the cost of moving tensors, launching operations and running elementwise reductions. The recorded timing experiment instead executes the full GPT-2 reference on random input-id sequences of 16, 128 and 512 tokens, float32, one CPU thread and five recorded runs after one warm-up. Each component’s time is summarised by its median; the displayed total is the sum of the component medians, not the median of complete-run times. One audit correction is necessary: the stored report calculates “achieved GFLOP/s” with a triangular causal-attention FLOP count, whereas attention() computes a dense \(T\times T\) score and value product before masking. The corrected figures below recompute the denominator from that observed code path without rerunning any timings.
| 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 |
Derived by dividing dense matmul FLOPs by the archived sum of component-median times, not measured with a hardware FLOP counter. The original results file reports 30.7, 70.7 and 67.8 GFLOP/s using the triangular-count denominator; these values must not be compared to the dense implementation as if they counted its actual matrix operations.
Three observations, each with a different evidential status.
The corrected dense-matmul estimate is about 30.7 GFLOP/s at 16 tokens, 71.3 at 128, and 70.3 at 512 using the original recorded times. Chapter 1 estimated roughly 34 GFLOP/s at a nearby short sequence length, so the two are of the same order on this setup. Throughput is higher for the longer calls, consistent with better use of large matrix operations; the measurements do not isolate the cause. These are effective rates obtained from an operation count divided by elapsed time, not directly observed floating-point instruction counts.
A second comparison uses each timed component’s share of the total. Under the dense-operation model corresponding to attention(), attention projections plus \(QK^\top\) and \(AV\) account for about 23.1%, 24.4% and 28.4% of matmul FLOPs at 16, 128 and 512 tokens. The observed attention time shares are 25.6%, 24.6% and 34.7%, respectively. The 512-token run spends a larger share of time in attention than its matmul count alone suggests. Mask creation, score writes, softmax, tensor reshapes and allocator activity are plausible contributors, and their working-set sizes scale with \(T^2\) in this implementation. Memory bandwidth or traffic was not measured, so a memory-bound explanation is a research hypothesis, not the established result. The originally archived FLOP shares used the triangular approximation and should be updated alongside the throughput calculation.
Layer norm accounts for roughly 1.4–2.9% of measured time, despite contributing nothing to the chapter’s counted matrix multiplications. This demonstrates a limitation of a matmul-only cost model: elapsed time includes reductions, elementwise kernels, temporary allocations and data movement. FLOP count is a measure of selected arithmetic work, not a physical lower bound on latency or an adequate standalone predictor of performance.
These timing shares characterise one unfused eager-PyTorch implementation on one CPU thread. They are not results for the Transformers library’s own kernels and cannot be transferred unchanged to fused GPU implementations. FlashAttention’s IO-aware formulation is useful supporting research here because it demonstrates that reducing movement and materialisation of attention intermediates can matter even when the mathematical attention operation is unchanged; it does not verify any speedup in this book’s local experiment.
Is it the same computation?
The purpose of the hand-written implementation is to make the architecture inspectable, but it first needs an empirical equivalence check. For each prompt, verify runs the reference and the installed Transformers model with the same loaded parameters and compares the full logit tensor, not just the generated 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 reference and library logits differ by at most approximately \(1.22\times10^{-4}\) across these tests, and their argmax token agrees at every tested position. Maximal logit magnitudes are approximately 130, 171, 323 and 149, but a large logit magnitude alone is not a numerical error bound: relative error becomes uninformative near zero logits, and a tiny absolute perturbation can change the chosen token when the top two scores nearly tie. The evidence is therefore the reported absolute and mean differences together with the argmax checks; future runs should also record worst-case top-two margins and longer sequences.
This establishes agreement for four prompts, 5–18 tokens, one batch element, CPU float32, against the installed library and pinned GPT-2 snapshot. It does not cover the 1,024-token limit, production batch shapes, lower precision or GPU kernels. There is an additional test on a randomly initialised two-layer library GPT-2 that uses a batch of two sequences and checks an absolute maximum difference below \(10^{-4}\); a separate small-model test checks causal isolation. These are valuable independent fixtures, but they are not a held-out suite of production workloads. A reference earns trust through expanding coverage and investigation of disagreements, not through one universal tolerance declared in advance.
tiny_transformer.py is deliberately a different model, not a smaller checkpoint-compatible GPT-2. Among other differences, it has bias-free attention projections, uses nn.GELU() rather than GPT-2’s tanh approximation and does not tie its token embedding to its output head. It remains useful for shape reports and causal-mask tests. Avoid using its parameter count or logits as though they were expected to match the GPT-2 cost model or gpt2_from_scratch.py. The latter is a reference implementation for the GPT-2-style architecture specified above, not for the generic tiny fixture.
What is not canonical
A “transformer block” is a family resemblance, not an executable specification. GPT-2’s pre-norm decoder differs from post-norm Transformers, RMSNorm-based models, rotary-position variants, grouped-query or multi-query attention, and gated MLPs. Those differences affect parameter shapes, buffer requirements, numerical operations and opportunities for caching or fusion. Consequently, the artefact manifest from Chapter 2 must identify more than a model family name. The transferable method is to state the exact computation, derive its costs for a stated workload, and verify each optimisation against an appropriate reference and acceptance criteria.
What the numbers do not show
- One model and execution environment. GPT-2 small, float32, CPU, one thread and one recorded experimental session; these measurements cannot be extrapolated to a production GPU server.
- Forward comparison coverage. Four real-model prompts of 5–18 tokens, plus small-model tests. No full-context, half-precision or production multi-batch qualification.
- Reference, not production kernel. The implementation uses unfused eager operations, a dense attention matrix and a request-sized mask; the Transformers library and fused attention kernels may execute different operation schedules.
- Matmul-only cost model. The per-query FLOP formula excludes biases, embedding lookups, layer norm, GELU, softmax, residual sums and device-memory movement. It is not a measured latency model.
- Corrected benchmark denominator. The original
cmd_timingreport uses a triangular causal-attention FLOP denominator even though the code executes dense products. The table above supplies derived dense-operation rates; update the code and stored evidence before publication. - Residual trace is one prompt. Its outlier coordinate does not establish typical activation statistics or quantisation error.
- Observed causal equality is local. The 0.0 earlier-logit difference is from one mask experiment; mathematical non-dependence on future tokens does not imply bitwise equality across all kernels.
- No hardware traffic counters or fused/GPU timing. The explanation of attention’s excess elapsed-time share is a hypothesis pending controlled measurement.
- No architecture-general correctness claim. RoPE, GQA, RMSNorm and other designs have not been reproduced by this reference.
Inference Lab increment
The Lab now contains a readable GPT-2 reference pass and two arithmetic helpers. Its immediate value is that later chapters can state what is being compared and keep the observed outputs separate from predicted resource cost:
forward(ids, weights, config, causal=True, trace=None): GPT-2-style eager reference producing logits for every input position.causal=Falseis an intentional fault injection used to show information leakage;tracecollects per-block activation summaries.parameter_count(config): learned-parameter inventory for the stated GPT-2-style architecture, including tied embeddings and biases.flops_per_token(config, context): matmul-only per-query count. For a dense full-prefix reference, use \(T\bigl[L(24d^2)+2Vd\bigr]+4LdT^2\) as the matching whole-sequence matmul estimate; do not substitute a triangular count for the executed dense multiplication.- Verification discipline: record artefact identity, inputs, dtypes, device, maximum and mean logit differences, argmax or top-k agreement, and acceptance tolerances before declaring an optimisation equivalent. A mismatch means the optimisation needs investigation; it does not automatically prove the output is invalid for every application.
The request record can now include a predicted arithmetic cost as well as measured stage timing and artefact identity. It must also identify whether the estimate concerns an incremental cached query, a complete prefill, or an uncached repeated forward pass. Otherwise two perfectly computed figures can be compared as if they describe the same work when they do not. Chapter 11 will add the data-movement side needed for a defensible bottleneck analysis.
What you should now be able to do
- Trace the tensor shapes of GPT-2’s full-sequence inference path, including both attention score and attention-probability matrices.
- Explain why the causal mask prevents future-token information flow, while recognising that bitwise output equality across kernels is a separate numerical question.
- Derive GPT-2 small’s 124,439,808 learned parameters from its architectural shapes, biases and weight tying.
- Separate per-query matmul FLOPs, dense full-prefix FLOPs and total uncached generation work instead of calling all three “FLOPs per token”.
- Identify which attention intermediates require quadratic storage in a naive implementation and why a tiled exact-attention algorithm can avoid materialising them.
- Compare a hand-written forward pass with the library using explicit tolerances, test coverage and logit margins.
- Distinguish the measured component time shares from arithmetic predictions and hypotheses about memory traffic.
- Explain which conclusions are model-specific and which can be carried to other transformer architectures.
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 |