Slides · ML systems and interviews
Training at scale: memory arithmetic, parallelism, mixed precision and scaling laws
1 / 27
Training at scale
Memory arithmetic, parallelism, mixed precision and scaling laws.
Concept
Why this is worth 120 minutes
- A model’s training state can be larger than any one device. Basic data parallelism does not shrink it.
- Every technique trades one resource for another: memory for compute, memory for network traffic, speed for numerical risk.
- Mental model: a memory budget with four line items (weights, gradients, optimizer states, activations) and a network.
Five things you will be able to do:
- Do the memory arithmetic and say whether a model fits.
- Scale batch and learning rate, accumulate gradients, use mixed precision.
- Choose DDP, ZeRO or FSDP, tensor or pipeline parallelism.
- Checkpoint activations, find loader bottlenecks, plan for failures.
- Estimate compute and cost, and read the scaling laws.
Diagram
Where the memory goes
Source[1] ZeRO: Memory Optimizations Toward Training Trillion Parameter Models
Math
16 bytes per parameter
(2+2+K)Ψ=16Ψ bytes,K=12- 2 bytes fp16 weights, 2 bytes fp16 gradients, 12 bytes fp32 copy plus two Adam moments.
- 1.5B parameters: 24 GB. 7B: 112 GB. 70B: 1,120 GB. All before activations.
- Three quarters of the 16 bytes are optimizer state.
Sources[1] ZeRO: Memory Optimizations Toward Training Trillion Parameter Models[2] Adam: A Method for Stochastic Optimization
Check yourself
Check: a 3B model
You fine-tune a 3-billion-parameter model with mixed-precision Adam on a 40 GB device with no sharding. Does the model state fit, and what is missing from your count?
Answer
3e9 x 16 bytes = 48 GB, which is more than 40 GB, so it does not fit even before activations. Activations, temporary buffers and fragmentation come on top, and they grow with batch and sequence length.
Worked example
Batch size and learning rate
ηt=η+(kη−η)Twarmt (t<Twarm),ηt=kη (t≥Twarm)| Step | 0 | 1,000 | 2,500 | 5,000 |
|---|---|---|---|---|
| Rate (0.1 at batch 256, batch 8,192) | 0.1 | 0.72 | 1.65 | 3.2 |
- Linear scaling rule: batch times k, rate times k, gradual warmup.
- In the ImageNet study the error was stable from 64 to 8,192 and rose after that.
- A critical batch size marks where more data per step stops buying fewer steps.
Sources[3] Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour[4] Scaling Laws for Neural Language Models
Worked example
Gradient accumulation
Ten points, one line, full-batch gradient (−28.885,−8.29).
| How the micro-batches are combined | First component |
|---|---|
| Weighted by size, divided once by 10 | -28.885 |
| Chunks 4, 4, 2, unweighted mean | -35.375 |
| Three chunk means added, no division | -106.125 |
- Divide by the total sample count once. Weight a short last chunk by its size.
- With DDP,
no_sync()skips the all-reduce on the non-final micro-batches. - Token losses: sum them and divide by the total non-padding tokens of the effective batch.
- Batch norm still sees only the micro-batch: eight values with variance 5.25 give 1.25 in chunks of 4.
Sources[3] Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour[5] Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift[6] Fixing Gradient Accumulation[7] torch.nn.parallel.DistributedDataParallel
Check yourself
Check: batch of 512 on a small card
Your card holds 64 samples. You want an effective batch of 512 on one process. How do you run it, and which layer in a ResNet still behaves differently from a true batch of 512?
Answer
Run 8 micro-batches of 64, add the gradients (each divided by 8, or the total divided by 512 once), then step once. Batch normalisation still computes its statistics over 64 samples at a time, so the loss it optimises is not exactly that of a batch of 512.
Compare
Mixed precision
| Piece | Why it exists |
|---|---|
| fp32 master weights | In fp16, 1.0 + 0.0001 rounds back to 1.0. 100 updates stay at 1.0, against 1.0100 kept in higher precision |
| Loss scaling | A gradient of 1e-8 is 0 at scale 1, and 1.001e-08 at scale 1,024 |
| Dynamic scale | Overflow gives infinity (2.0 x 65,536). Halve on overflow, double after a clean run |
| bf16 | fp32’s range, less precision. Often trained without loss scaling |
- Unscale before clipping. Keep the scale fixed while an effective batch accumulates.
Sources[8] Mixed Precision Training[9] Automatic Mixed Precision package - torch.amp[10] Automatic Mixed Precision examples
Diagram
Data parallelism
Worked example
What an all-reduce costs
tring=n2(n−1)BS+2(n−1)α,tcentral=B2(n−1)S14 GB of gradients, 50 GB/s (assumed):
| Devices | 2 | 8 | 64 | 1,024 |
|---|---|---|---|---|
| Ring (s) | 0.280 | 0.490 | 0.551 | 0.559 |
| Central (s) | 0.56 | 3.92 | 35.28 | 572.88 |
- The ring cost is nearly flat in n. A step that computes for 0.3 s and waits 0.56 s is communication-bound.
Compare
ZeRO stages and FSDP
| Stage | Sharded | 7B on 8 devices | PyTorch FSDP |
|---|---|---|---|
| 0 | Nothing | 112.0 GB | NO_SHARD |
| 1 | Optimizer states | 38.5 GB | none |
| 2 | + gradients | 26.2 GB | SHARD_GRAD_OP |
| 3 | + weights | 14.0 GB | FULL_SHARD |
- Stage 3 costs about 50% more communication in the paper. Stages 1 and 2 keep the volume of plain data parallelism.
HYBRID_SHARDshards inside a node and replicates across nodes.- PyTorch 2.15 also ships FSDP2 (
fully_shard, per-parameter DTensor sharding) and suggests migrating from FSDP1.
Sources[1] ZeRO: Memory Optimizations Toward Training Trillion Parameter Models[12] FullyShardedDataParallel[13] torch.distributed.fsdp.fully_shard (FSDP2)
Math
Tensor and pipeline parallelism
bubble=m+p−1p−1- Tensor parallelism splits matrices inside a layer, so it talks in every layer: keep it inside a server.
- Pipeline parallelism splits layers into stages. The bubble is the idle share.
- 8 stages: 0.875 with 1 microbatch, 0.304 with 16, 0.099 with 64. For 10%, 63 microbatches.
- More stages need more microbatches, which means a bigger batch.
Sources[14] GPipe: Easy Scaling with Micro-Batch Pipeline Parallelism[15] Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM[16] Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism
Check yourself
Check: which strategy
A 13B model needs 208 GB of state with mixed-precision Adam. You have 16 devices of 80 GB in one server with fast links and no pipeline. What is the first thing to try, and why not tensor parallelism first?
Answer
Shard the state with ZeRO stage 2 or 3 or FSDP: 208 GB over 16 devices is 13 GB each at stage 3, leaving room for activations, and it keeps the plain data-parallel programming model. Tensor parallelism changes the model code and communicates in every layer, so reach for it when a single layer or its activations will not fit.
Worked example
Activation checkpointing
k+⌈kn⌉ units,k∗≈n| Layers | No checkpointing | Best k | Peak units |
|---|---|---|---|
| 16 | 16 | 4 | 8 |
| 100 | 100 | 10 | 20 |
| 1,000 | 1,000 | 28 | 64 |
- Price: one more forward pass, about a third more compute if backward costs twice forward.
- Chen et al. report 48 GB to 7 GB for a 1,000-layer ResNet at about 30% more time.
Sources[17] Training Deep Nets with Sublinear Memory Cost[18] torch.utils.checkpoint
Worked example
Loader and failures
| Loader workers (compute 0.25 s, load 0.9 s) | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| Step time (s) | 0.9 | 0.45 | 0.3 | 0.25 |
| Accelerator busy | 28% | 56% | 83% | 100% |
- Checkpoint interval about 2wM: write 3 min, failure every 360 min gives 46.5 min and 12.9% of time lost.
- Sharded training needs sharded checkpoints that can reshard on load.
- Reproducible experiments, not bit-identical runs.
Sources[19] torch.utils.data (DataLoader)[20] Distributed Checkpoint - torch.distributed.checkpoint[21] Reproducibility
Check yourself
Check: low utilisation
Accelerator utilisation is 40% and the step time is the same when you halve the model. What does that suggest, and what do you measure first?
Answer
The accelerator is waiting for something that does not depend on model size, usually data loading or communication. Measure the time a step spends waiting for a batch, and the time in all-reduce that is not overlapped with the backward pass, before buying hardware.
Compare
Scaling laws
| Kaplan et al. 2020 | Hoffmann et al. 2022 | |
|---|---|---|
| Finding | Loss is a power law in size, data and compute | Scale model size and tokens in equal proportion |
| Advice | Very large models, modest data, stop early | Chinchilla: 70B on 1.4T tokens beats Gopher 280B at the same compute |
| Tokens per parameter | n/a | 20 for Chinchilla, 1.07 for Gopher (derived from the paper’s table) |
- 20 tokens per parameter is the ratio of one result, not a law.
- Compute-optimal is optimal for training cost, not for serving cost.
Sources[4] Scaling Laws for Neural Language Models[22] Training Compute-Optimal Large Language Models
Math
Cost with 6ND
C≈6ND,days=G⋅P⋅u⋅86,400C- 7B parameters on 1012 tokens: 4.2×1022 FLOPs.
- 1,024 devices at 300 TFLOP/s peak and 40% utilisation (assumed): 3.96 days. 256 devices: 15.82 days.
- The paper’s Gopher budget is 5.76×1023: 6ND is 12.5% low for Gopher (5.04×1023) and 2.1% high for Chinchilla (5.88×1023).
Sources[4] Scaling Laws for Neural Language Models[22] Training Compute-Optimal Large Language Models
Check yourself
Check: an estimate
A 1B-parameter model trains on 200 billion tokens on 64 devices at 100 TFLOP/s peak and 50% utilisation. About how many days?
Answer
C = 6 x 1e9 x 2e11 = 1.2e21 FLOPs. Rate = 64 x 1e14 x 0.5 = 3.2e15 FLOP/s. Time = 3.75e5 s, about 4.34 days. State the assumptions, because utilisation moves the answer by large factors.
Code
Homework: the training-at-scale calculator
Python
def state_bytes_per_param(stage, dp, weight_bytes=2, grad_bytes=2, optimizer_bytes=12): ...
def accumulated_gradient(w, b, xs, ys, micro_size): ...
def fp16_gradient(grad, scale): ...
def ring_allreduce_seconds(size_bytes, n, bandwidth, latency=0.0): ...
def bubble_fraction(stages, microbatches): ...
def best_checkpoint_count(n_layers): ...
def training_days(flops, gpus, peak_flops_per_gpu, utilisation): ...- Also: fit check, scaled learning rate, dynamic loss scale, loader workers, checkpoint interval, compute-optimal split.
Summary
Recap
- 16 bytes per parameter with mixed-precision Adam, before activations. Check that the sum fits.
- Linear scaling with warmup, accumulation divided once and weighted, mixed precision with master weights and loss scaling.
- DDP while it fits, ZeRO or FSDP when state does not, tensor inside a server, pipeline across servers with enough microbatches.
- Checkpoint activations for a third more compute, feed the accelerator, checkpoint on a computed interval.
- Compute is about 6ND. Scale model and data together, and say your assumptions.
References
References & Sources (1 of 5)
ZeRO: Memory Optimizations Toward Training Trillion Parameter Models (opens in a new tab)
Samyam Rajbhandari, Jeff Rasley, Olatunji Ruwase, Yuxiong He2019arXiv:1910.02054 (v3, May 2020)Preprint
https://arxiv.org/abs/1910.02054
Used for Model-state accounting of 2 + 2 + K bytes per parameter with K = 12 for mixed-precision Adam, the GPT-2 1.5B example (3 GB of weights, at least 24 GB of state, about 60 GB of activations), the three partitioning stages and their stated effects, and the limit of basic data parallelism near 1.4B parameters on 32 GB GPUs (sections 1 and 3).
Adam: A Method for Stochastic Optimization (opens in a new tab)
Diederik P. Kingma, Jimmy Ba2015ICLR 2015 (arXiv:1412.6980)Paper
https://arxiv.org/abs/1412.6980
Used for Adam keeps first and second moment estimates per parameter.
Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour (opens in a new tab)
Priya Goyal, Piotr Dollar, Ross Girshick, Pieter Noordhuis, et al.2017arXiv:1706.02677Preprint
https://arxiv.org/abs/1706.02677
Used for The linear scaling rule, gradual warmup over 5 epochs, stable error from batch 64 to 8,192, divergence beyond 64k, the role of the per-worker batch in batch norm, and gradient accumulation used to simulate large batches.
Scaling Laws for Neural Language Models (opens in a new tab)
Jared Kaplan, Sam McCandlish, Tom Henighan, Tom B. Brown, et al.2020arXiv:2001.08361Preprint
https://arxiv.org/abs/2001.08361
Used for Power-law scaling of loss with size, data and compute, the critical batch size, the C approximately 6NBS estimate and the forward cost of about 2N per token.
Sergey Ioffe, Christian Szegedy2015ICML 2015 (arXiv:1502.03167)Paper
https://arxiv.org/abs/1502.03167
Used for Batch normalisation computes statistics over the mini-batch.
References
References & Sources (2 of 5)
Fixing Gradient Accumulation (opens in a new tab)
Hugging Face2024Article
https://huggingface.co/blog/gradient_accumulation
Used for The correct accumulated loss for token-level tasks is the total loss divided by the total number of non-padding tokens, not an average of per-batch losses.
torch.nn.parallel.DistributedDataParallel (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/generated/torch.nn.parallel.DistributedDataParallel.html
Used for The no_sync() context manager that accumulates gradients locally and synchronises on the first backward pass outside it.
Mixed Precision Training (opens in a new tab)
Paulius Micikevicius, Sharan Narang, Jonah Alben, Gregory Diamos, et al.2018ICLR 2018 (arXiv:1710.03740)Paper
https://arxiv.org/abs/1710.03740
Used for The three techniques (fp32 master weights, loss scaling, fp16 arithmetic with fp32 accumulation), the fp16 maximum of 65,504, and the warning that overflow damages the weights (abstract and loss-scaling section).
Automatic Mixed Precision package - torch.amp (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/amp.html
Used for Gradient scaling against underflow, unscaling before the optimizer step, GradScaler default values, and the note on bf16-pretrained models overflowing the fp16 range.
Automatic Mixed Precision examples (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/notes/amp_examples.html
Used for Unscaling before gradient clipping, and keeping the scale constant while gradients accumulate over an effective batch.
References
References & Sources (3 of 5)
Distributed Data Parallel (developer notes) (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/notes/ddp.html
Used for DDP broadcasts the initial state, buckets gradients, starts an asynchronous all-reduce per ready bucket, averages gradients, and needs the same bucket order on every process.
FullyShardedDataParallel (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/fsdp.html
Used for FSDP shards parameters across data-parallel workers, is inspired by ZeRO stage 3, and the FULL_SHARD, SHARD_GRAD_OP, NO_SHARD and HYBRID_SHARD strategies.
torch.distributed.fsdp.fully_shard (FSDP2) (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/distributed.fsdp.fully_shard.html
Used for FSDP2 fully_shard with per-parameter DTensor sharding, the suggestion to migrate from FSDP1, and the reshard_after_forward behaviour.
GPipe: Easy Scaling with Micro-Batch Pipeline Parallelism (opens in a new tab)
Yanping Huang, Youlong Cheng, Ankur Bapna, Orhan Firat, et al.2018arXiv:1811.06965Preprint
https://arxiv.org/abs/1811.06965
Used for Micro-batch pipeline parallelism and the bubble overhead of order (K - 1) / (M + K - 1).
Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM (opens in a new tab)
Deepak Narayanan, Mohammad Shoeybi, Jared Casper, Patrick LeGresley, et al.2021SC '21 (arXiv:2104.04473)Paper
https://arxiv.org/abs/2104.04473
Used for Bubble time fraction (p - 1) / m, pipeline flush costing up to 50% of time, tensor parallelism within a server, up to 2 times lower throughput for a poor mix, and the interleaved schedule.
References
References & Sources (4 of 5)
Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, et al.2019arXiv:1909.08053Preprint
https://arxiv.org/abs/1909.08053
Used for Intra-layer model parallelism with a few communication operations in native PyTorch, up to 8.3B parameters on 512 GPUs (abstract).
Training Deep Nets with Sublinear Memory Cost (opens in a new tab)
Tianqi Chen, Bing Xu, Chiyuan Zhang, Carlos Guestrin2016arXiv:1604.06174Preprint
https://arxiv.org/abs/1604.06174
Used for O(sqrt n) memory at the cost of one extra forward pass, and 48 GB to 7 GB with about 30% more running time for a 1,000-layer residual network (abstract).
torch.utils.checkpoint (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/checkpoint.html
Used for Activation checkpointing trades compute for memory by recomputing in the backward pass, random-state handling, and the recommendation of the non-reentrant implementation.
torch.utils.data (DataLoader) (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/data.html
Used for Single and multi-process loading, num_workers, pin_memory, and the prefetch_factor default.
Distributed Checkpoint - torch.distributed.checkpoint (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/distributed.checkpoint.html
Used for Sharded save and load from multiple ranks and load-time resharding.
References
References & Sources (5 of 5)
Reproducibility (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/notes/randomness.html
Used for Reproducibility is not guaranteed across releases or platforms, deterministic algorithms can be slower, and seeding DataLoader workers.
Training Compute-Optimal Large Language Models (opens in a new tab)
Jordan Hoffmann, Sebastian Borgeaud, Arthur Mensch, Elena Buchatskaya, et al.2022arXiv:2203.15556Preprint
https://arxiv.org/abs/2203.15556
Used for Equal scaling of model size and tokens, the Chinchilla and Gopher comparison, Table 1 sizes and token counts, and FLOPs approximately 6ND.
Keys: ← → move, Home End first and last, F full screen.