Unit 3 of 12 · about 4 hours · derive, implement
Microbatches, accumulation, global batch, token accounting and update semantics
The global batch sets gradient noise and learning-rate scaling, while the microbatch sets memory. Confusing the two changes the optimized objective without changing any config name.
You'll be able to
- Derive global batch and token counts from microbatch size, accumulation steps, packing and data-parallel degree.
- Implement accumulation with correct mean weighting over uneven microbatches and one optimizer step per global batch.
- Explain when accumulation matches a large batch and which padding and zeroing choices break the match.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Gradient accumulation and the batch equationUltra-Scale Playbook - First Steps: Training on One GPU
Gradient accumulation through Revisiting global batch size: microbatch size, accumulation steps and ; the note that accumulation keeps separate gradient buffers alive across the step
- Accumulation and effective batch sizeDistributed Training Guide - Chapter 1 and Related Topics
Effective batch as
batch * accum_stepswithbackwardeach step andsteponly wheni % accum == 0; related-topicseffective-batch-size-and-lrREADME for linear versus square-root learning-rate scaling with batch size - Capacity levers: accumulation and checkpointingMachine Learning Systems Volume I - ML Frameworks, Model Training and Benchmarking
Model Training, Pipeline Optimizations: gradient accumulation and activation checkpointing as the capacity responses when a batch does not fit
Focus on
- Global batch is , with tokens . In LLM reports the batch is quoted in tokens so the count survives a sequence-length change.
- Uneven microbatches need size-weighted averaging. With per-microbatch mean gradients over 2 examples and over 1, the full-batch gradient is ; averaging the two means gives the wrong .
- Accumulation keeps gradient buffers across micro-steps but holds only one microbatch's activations at a time, so its peak sits below a single large batch when activations dominate, even though the update matches. The optimizer steps once per global batch, then gradients are cleared.
- Padding and packing change the denominator. Padded positions and cross-document transitions excluded from the loss must not count as tokens in the batch.
Common mistakes · 3
- Averaging per-microbatch losses or gradients instead of weighting by microbatch size. Equal weight per microbatch overweights small ones.
- Stepping the optimizer per microbatch. That trains with the microbatch size while the config claims the global size.
- Counting padded or masked positions as batch tokens. Throughput and scaling rules then use tokens the loss never saw.
Try it yourself
Closed-book, before checking anything
Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Microbatch 8 with seq 4096, 4 accumulation steps, dp 2. What is the global batch in samples and tokens?Answer
samples, or tokens.
2.Why does naive averaging of per-microbatch gradients fail for uneven microbatches?Answer
Each microbatch gradient is already a mean over its own size. The full-batch mean must weight each by its example count; unweighted averaging gives small microbatches excess influence.
3.Does accumulation with the same global batch always match a large batch numerically?Answer
It matches when every microbatch uses the same graph, the correctly weighted mean, one step per global batch and identical ordering. It differs when padding, dropout draws, batch statistics or ordering differ.
4.Where does the extra memory of accumulation sit?Answer
In gradient buffers held across micro-steps plus one microbatch of activations at a time, instead of the full-batch activation peak.
Practice
- TensorTonic: Gradient Accumulation Equivalence
Implement
gradient_accumulation_step: accumulate the full-batch mean-squared-error gradient over uneven microbatches and return the updated parameter and full gradient; the public cases check uneven sizes, equal sizes and zero lossAnswer the weighting by hand first: each example contributes equally even when microbatch sizes differ. Then run the same comparison in your own trainer against a full-batch step.
You're done when
You derive the global batch in samples and tokens for any setting, and your accumulator matches a full-batch step while the naive mean-of-means fails as predicted.
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.
- Distributed Training Guide - Chapter 1 and Related TopicsLambda Labs · required
Trace
01-single-gpu/train_llm.pyend 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.
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_profilingandgradient_checkpointingon 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. - 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.
- 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.
- 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_lastpadding 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.