Unit 4.7 · about 4 h
317 / 324Memory, arithmetic intensity and reconciling estimates
Analytical math sets the budget, but allocators, graphs and kernels decide what fits. Reconciliation is what makes the next capacity plan trustworthy.
- derive
- measure
You can now
- Derive gradient, optimizer, activation and KV memory for a stated precision and config, including checkpointing savings.
- Explain arithmetic and accelerator intensity and predict memory-bound versus compute-bound regimes for prefill and decode.
- Reconcile an analytical estimate with measured memory and state quality-compute comparisons as ranges, not points.
Covers
- Gradient, optimizer, activation and temporary memory
- Arithmetic intensity vocabulary and hardware-independent limits
- Allocator, graph, kernel and framework overhead reconciliation
- Quality-compute comparisons and uncertainty ranges
Study, in this order
4 steps
- Modern LLM Notebook Appendix B: activations, inference, training and checkpointingModern LLM Notebook - evaluation and FLOP accounting
Section 2 (attention \(6BSD\) plus \(BHS^2\), FFN \(2BSD\) plus \(2BSF\) to \(8BSD\), per-layer \(14BSD\) plus \(BNS^2\) with the \(S\)4096 dominant-term check), Section 5 (FP16 weights \(2P\), KV \(B\) times \(S\) times \(K\) times \(d_h\) times \(L\) times 2 times bytes with 7B scenarios and weights, KV and activations regimes), Section 6 (AdamW ledger with FP32 master, BF16 copy, \(m, v\) and grads plus BF16 activations and A100 fit) and Section 7 (checkpoint trade to \(O(\sqrt{L})\) with
torch.utils.checkpointAPI) - CS336 Lecture 2: intensity, roofline and checkpointingStanford CS336 - resource accounting, inference and evaluation
arithmetic_intensity_reluthrougharithmetic_intensity_matmulwith H100 accelerator intensity androofline_plots(),activation_checkpointing()with the \(O(\sqrt{L})\) rule,tensors_memory()with dtypes and the 2.3GB example, andoptimizer()memory plus erees and adamcasson links - CS336 Lecture 10: inference intensity and throughputStanford CS336 - resource accounting, inference and evaluation
review_of_arithmetic_intensity()with \(2BDF\) over \(2BD\) plus \(2DF\) plus \(2BF\) to intensity \(B\) and the H100 295 bound,arithmetic_intensity_of_inference()with MLP \(6BTDF\) and attention \(4BSTD\) to \(BT\) and \(ST/(S + T)\) plus prefill \(S/2\) and generation below 1, andthroughput_and_latency()with Llama 2 13B at \(B\)1, \(B\)64 and \(B\)256 plus the TTFT note - LLM Foundations Checkpoint: debug and measure contractLLM Foundations Checkpoint - evaluation and arithmetic slice
Debug and measure bullets: reconcile analytical parameters, FLOPs, state and KV with profiles and separate prefill and decode across batch and context regimes
Focus on
- State the precision for every term. Mixed bf16 params and grads with fp32 master and moments is 12 bytes without master and 16 to 18 with it, so measure to confirm which ledger your loop keeps.
- Compare arithmetic intensity to accelerator intensity (H100 about 295). Below it you are memory-bound no matter how good the kernels are.
- Prefill grows with \(B\) times \(T\) for MLP and \(S/2\) for attention, while generation sits at \(B\) for MLP and below 1 for attention. Batching rescues MLP generation, not attention.
- Expect measured memory above the formula. Name allocator caching, fragmentation, graph, workspace and framework overhead before doubting the math.
Reproduce closed-book
Traps
- Quoting the formula as the fit result.
torch.cuda.memory_allocatedincludes caching and fragmentation, so report both numbers and explain the gap. - Assuming a bigger batch fixes generation attention. Its intensity stays below 1 because each sequence owns its KV, while batching only helps the MLP part.
- Comparing quality at unequal compute. Fix prompts, decoding, budgets and evaluator versions, then report quality with compute ranges.
Practice
Modern LLM Notebook Appendix B Exercise 2: 13B training memory
Exercise 2 with \(D\)5120 \(L\)40 \(H\)40 \(B\)8 \(S\)4096 \(P\)13B; fixed \(16P\), activations \(L\) times (\(14BSD\) plus \(BHS^2\)) times 2 bytes, total GB and A100 count; the cells assert fixed bytes, elements and count
Self-test
-
What is the Exercise 2 training total for the 13B config?
Fixed \(16 \times 13 \times 10^9 = 208\text{ GB}\), activations are 617GB in BF16, total 825GB, so 11 A100 80GB units. -
When is an \(XW\) matmul compute-bound on an H100?
Intensity \(B\) versus 295. Compute-bound iff \(B\) is above 295. \(B\) equals 1 gives 1, which is memory-bound, and that is the inference matvec regime. -
How do prefill and generation intensities differ for MLP versus attention?
MLP intensity is \(B\) times \(T\) (prefill with large \(BT\) is compute-bound, generation with \(T\) equals 1 needs a large batch), while attention is \(ST/(S + T)\) (prefill \(S/2\) is good, generation below 1 is bad, and batching does not help). -
Measured memory is 10 percent above the formula. Name the suspects and one isolation per suspect.
Allocator cache and fragmentation, saved graph tensors, kernel workspace, framework overhead and KV reserve. Isolate with allocated versus reserved readings, a batch and length sweep, and a checkpointing toggle.
Completion criterion
Stop when
You predict memory-bound versus compute-bound for one prefill and one decode case before measuring, and your worksheet reconciles one analytical total with allocated memory.
Mark passed, then open 5.1 Only mark this when you can do it without notes.Leads to
- 5.4 KV memory arithmetic Apply KV math to cache capacity and layout design.
- 5.5 Two regimes: prefill and decode Carry intensity regimes into separate prefill and decode measurement.
Comes after
- 4.4 Uncertainty, robustness and honest claimsCarry interval discipline into quality-compute comparisons with uncertainty ranges.
- 4.6 Counting parameters and FLOPsTurn FLOP counts into memory budgets and intensity regimes.
Resources for this unit
- Stanford CS336 - resource accounting, inference and evaluation Use Spring 2026 Lectures 2, 10 and 12 for FLOPs, memory, arithmetic intensity, inference and evaluation. Reproduce the small calculations locally. Assignment 3 IsoFLOPs analysis is optional; do not require its hosted training API or costly experiments.
- Modern LLM Notebook - evaluation and FLOP accounting Use English notebook 25-evaluation and Appendix B FLOP and memory accounting. Build a 20-example evaluator with two slices, raw outputs and bootstrap intervals, and deliberately create one parser, prompt or judge failure.
- LLM Foundations Checkpoint - evaluation and arithmetic slice Use the contamination, evaluator-bias, parameter, FLOP, activation, state and KV requirements as the assessment contract. Keep raw outputs and distinguish a verified task result from a broad model capability claim.
Also in this section
- LLMs from Scratch companion - GPT FLOP analysis Use ch04/02_performance-analysis/flops-analysis.ipynb as a concrete calculator, then rebuild the formulas from the model configuration and reconcile parameters and at least one memory or operation estimate with runtime state.
- Language Model Evaluation Harness After the small evaluator passes, inspect task versioning, request construction and result schemas to understand production evaluation plumbing. Do not use the harness as a substitute for owning the task and metric contract.
- Stanford CS336 Assignment 3 - IsoFLOPs scaling Use Section 2.1 and Problem
chinchilla_isoflopswithdata/isoflops_curves.jsonfor the bounded curve-fitting exercise only. Do not use the hosted training API or costly experiments.