Unit 7 of 12 · about 4 hours · derive, measure

Persistent, activation, temporary and allocator memory in one training step

OOMs are decided before the step runs: persistent state sets the floor, activations scale with batch and sequence, and the allocator decides what fits in practice. A ledger turns an OOM into an arithmetic error with a line number.

You'll be able to

  • Derive parameter, gradient, optimizer, activation, temporary and checkpoint bytes by dtype for a small model.
  • Distinguish allocated, reserved and peak memory in a profiler snapshot and explain the gaps.
  • Validate one predicted memory number against measurement and explain allocator and temporary-buffer differences.

Covers

Persistent, activation, temporary and allocator memory accounting
1

Read

In this order, only the parts listed

0 of 3 done

  1. Weight, gradient, optimizer and activation bytesUltra-Scale Playbook - First Steps: Training on One GPU

    Memory usage in transformers: the FP32 and mixed-precision byte rules with the 1B, 7B, 70B and 405B table; the activation formula in sequence length, batch, width, heads and layers and its quadratic sequence dependence

    Derive the table rows by hand; use the interactive calculator only after fixing sequence length and recomputation mode, since it does not display either.

  2. Second derivation of the training ledgerTransformer Math 101

    Memory Requirements, Training: Model Parameters, Optimizer States, Gradients, Activations and Batch Size, Total Training Memory; Distributed Training, Sharded Optimizers for the ZeRO-1, ZeRO-2 and ZeRO-3 rows

  3. Bottleneck signatures around the ledgerMachine Learning Systems Volume I - ML Frameworks, Model Training and Benchmarking

    Model Training, Identifying Bottlenecks: MFU with the 7B, 1024-token, 1.2s A100 example at 11.5 percent, and the compute, memory and data-bound signatures that say which ledger row binds

2

Focus on

  • Persistent bytes follow : element count times byte width. Mixed precision without FP32 gradient accumulation holds bytes per parameter; with FP32 gradient accumulation it holds 20. The book table checks: 1B gives 16 GB and 20 GB, 7B gives 112 GB and 140 GB.
  • Eleuther counts the same 16 bytes differently: 2 for BF16 parameters, 2 for gradients and 12 for optimizer with the FP32 master inside. Reconcile presentations before comparing numbers across sources.
  • Activations scale with batch and quadratically with sequence while persistent state does not. For long sequences activations dominate; for short ones the persistent rows do.
  • Allocated is tensors alive, reserved includes the caching allocator pool, peak is the high-water mark. The Playbook budgets 1 to 2 GB for CUDA kernels on first use; measure yours, since lazy module loading makes it smaller, and fragmentation makes reserved exceed allocated even when the ledger balances.
Common mistakes · 3
  • Quoting GB against GiB without converting. The book table uses GB; profiler snapshots and the CS336 3.6 GiB per-layer numbers use GiB, 7 percent apart.
  • Treating mixed precision as memory saving for persistent state. It redistributes the same 16 bytes and adds 4 more with FP32 accumulation; the saving sits in activations and compute, not in the persistent rows.
  • Reading the Playbook widget number against the formula with unstated widget state. Without its sequence length and recomputation mode the two cannot be compared.
3

Try it yourself

Closed-book, before checking anything

Closed-book, ledger a 10M-parameter Adam model in mixed precision without FP32 gradient accumulation: parameters, gradients, optimizer and a stated activation shape in bytes. Then measure one row on your machine and explain the gap to allocator or temporary buffers.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.A 1B-parameter model trains mixed precision with Adam, no FP32 gradient accumulation. What are the persistent bytes?Answer

    16 GB: bytes, as 2 GB parameters, 2 GB gradients, 12 GB optimizer with master, momentum and variance.

  2. 2.Why do Eleuther (2 plus 2 plus 12) and the Playbook (2 plus 2 plus 4 plus 8) agree?Answer

    Both sum to 16 bytes per parameter. Eleuther files the 4-byte FP32 master inside the 12-byte optimizer row; the Playbook lists it as a separate parameters row.

  3. 3.Allocated reads 0.85 GB while reserved reads 1.29 GB after a step. Is memory leaking?Answer

    Not necessarily. Reserved includes the allocator pool held for reuse plus fragmentation; allocated is live tensors. A leak needs growth across steps, not a reserved gap.

  4. 4.Batch doubles but persistent state is unchanged. Which row grows and how?Answer

    Activations grow linearly with batch (and quadratically with sequence). Parameters, gradients and optimizer state are batch independent.

5

Practice

  • TensorTonic: Mixed-Precision Training Memory Accountant

    Implement memory_accountant: byte counts for parameters, gradients, saved activations and optimizer state (none for SGD, one per parameter for AdaGrad, two for Adam) from shapes and byte widths; the public cases check BF16 with FP32 gradients under Adam, FP32 SGD and BF16 AdaGrad

    The problem excludes allocator overhead and master-weight copies by construction; state both exclusions when you compare its totals with your measured ledger.

You're done when

Your hand ledger predicts the measured persistent bytes within allocator noise, and you can name which row any batch, sequence or dtype change moves.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 10 more in the section
  • Machine Learning Systems Volume I - ML Frameworks, Model Training and BenchmarkingML Systems Textbook · primary

    Read Model Training (Iron Law of Training Performance, Pipeline Architecture, Identifying Bottlenecks, Pipeline Optimizations), then ML Frameworks (Execution Problem, Differentiation Problem, Anatomy of a Training Step) at https://mlsysbook.ai/vol1/frameworks/frameworks.html and Benchmarking (Training Benchmarks, Benchmarking Best Practices) at https://mlsysbook.ai/vol1/benchmarking/benchmarking.html. Turn the reading into a state-ownership table and a deterministic train-resume trace before the CS336 exercises.

  • Ultra-Scale Playbook - First Steps: Training on One GPUHugging Face · required

    Read Memory usage in transformers, Activation recomputation and Gradient accumulation, then Appendix A1 on profiling. Derive weight, gradient, optimizer and activation bytes for your tiny model before measuring; the interactive calculator does not show its sequence length or recomputation setting, so compare it with the formulas only after setting both.

  • Transformer Math 101EleutherAI · support

    Use the compute, parameter, optimizer, gradient and activation memory equations as a second derivation of your memory ledger. Check each per-dtype byte count against your own trainer's state.

Also in this section

  • CS336 Assignment 2 (Spring 2026) - Sections 2 and 3Stanford University · required

    Complete benchmarking_script, nsys_profile, mixed_precision_accumulation, benchmarking_mixed_precision, memory_profiling and gradient_checkpointing on model sizes your hardware fits, with your own solutions. Keep timing tables, memory predictions and failure notes; the FlashAttention kernel (Section 4) and the leaderboard (Section 9) are outside this stage.

  • Distributed Training Guide - Chapter 1 and Related TopicsLambda Labs · required

    Trace 01-single-gpu/train_llm.py end to end with its README (argument parsing, model initialization, checkpoint save of model, optimizer and scheduler, timers and memory statistics), then the related-topics folders on determinism, gradient accumulation, effective batch size and optimized data loading. Produce a state-ownership table and prove identical data order and optimizer trajectory after a controlled interruption.

  • Machine Learning Engineering Open Book - Training and PyTorch DebuggingStas Bekman · required

    Read training/README.md, training/dtype.md, training/reproducibility/README.md and the tiny-model, memory and profiling sections of debug/pytorch.md. Use its commands as a field checklist while diagnosing your own loop.

  • AI Systems Performance Engineering - Chapters 13 and 14Chris Fregly (O'Reilly) · support

    Read Chapter 13 on NVTX markers, the PyTorch profiler, memory and allocator tuning, activation checkpointing and the data input pipeline, and the Chapter 14 sections on graph breaks and recompilation. Use them to explain one profiled step of your own trainer; treat bundled expectations as the author's hardware results.

  • Mixed Precision TrainingMicikevicius et al. (ICLR 2018) · support

    Read the sections on FP32 master weights, loss scaling and FP32 accumulation. Connect each to a failure your trainer can show: lost small updates, underflowed gradients or overflowed products.

  • PyTorch Profiler RecipesPyTorch · support

    Use the profiler, memory snapshot and benchmark recipes only when the CS336 handout calls for them. Annotate one complete step and explain every visible gap or synchronization event.

  • TensorTonic - Training Arithmetic ProblemsTensorTonic · support

    Solve Training FLOP Estimator, Mixed-Precision Training Memory Accountant and Gradient Accumulation Equivalence (free problems in the Language Modeling from Scratch plan) before the CS336 measurements.

  • Distributed Training SubsystemRoadmap-Final · support

    Start Milestone A with the deterministic sampler, state manifest, event trace and single-process oracle. Keep extending this repository through DT-9.

  • PyTorch data loading API - DataLoader, Sampler and multi-process loadingPyTorch · reference

    Read Data Loading Order and Sampler, Single- and Multi-process Data Loading with its Randomness subsection, and the DistributedSampler entry for set_epoch, drop_last padding and worker seeding. Use it to define sampler position and worker sharding for the lineage and resume units.

  • PyTorch Autograd mechanics notePyTorch · reference

    Read How autograd encodes the history with Saved tensors, Hooks for saved tensors, and Backward Hooks execution (whether each hook fires and in which order). Use it for the autograd graph, saved-tensor and hook-ordering claims.