Slides · ML systems and interviews

Training at scale: memory arithmetic, parallelism, mixed precision and scaling laws

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:

  1. Do the memory arithmetic and say whether a model fits.
  2. Scale batch and learning rate, accumulate gradients, use mixed precision.
  3. Choose DDP, ZeRO or FSDP, tensor or pipeline parallelism.
  4. Checkpoint activations, find loader bottlenecks, plan for failures.
  5. Estimate compute and cost, and read the scaling laws.

Diagram

Where the memory goes

Diagram: Memory holds weights, gradients, optimizer states and activations.

Device memory

Weights

Gradients

Optimizer states

Activations

Shard (ZeRO, FSDP)

Recompute (checkpointing)

Diagram summary: Memory holds weights, gradients, optimizer states and activations. Sharding splits the first three across devices, and checkpointing recomputes the activations.

Source1 ZeRO: Memory Optimizations Toward Training Trillion Parameter Models

Math

16 bytes per parameter

(2+2+K) Ψ=16 Ψ bytes,K=12(2+2+K)\,\Psi=16\,\Psi\ \text{bytes},\qquad 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.

Sources1 ZeRO: Memory Optimizations Toward Training Trillion Parameter Models2 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η−η) tTwarm (t<Twarm),ηt=kη (t≥Twarm)\eta_t=\eta+(k\eta-\eta)\,\frac{t}{T_{\text{warm}}}\ (t<T_{\text{warm}}),\qquad \eta_t=k\eta\ (t\ge T_{\text{warm}})
Step01,0002,5005,000
Rate (0.1 at batch 256, batch 8,192)0.10.721.653.2
  • Linear scaling rule: batch times kk, rate times kk, 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.

Sources3 Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour4 Scaling Laws for Neural Language Models

Worked example

Gradient accumulation

Ten points, one line, full-batch gradient (−28.885, −8.29)(-28.885,\,-8.29).

How the micro-batches are combinedFirst 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.

Sources3 Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour5 Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift6 Fixing Gradient Accumulation7 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

PieceWhy it exists
fp32 master weightsIn fp16, 1.0 + 0.0001 rounds back to 1.0. 100 updates stay at 1.0, against 1.0100 kept in higher precision
Loss scalingA gradient of 1e-8 is 0 at scale 1, and 1.001e-08 at scale 1,024
Dynamic scaleOverflow gives infinity (2.0 x 65,536). Halve on overflow, double after a clean run
bf16fp32’s range, less precision. Often trained without loss scaling
  • Unscale before clipping. Keep the scale fixed while an effective batch accumulates.

Sources8 Mixed Precision Training9 Automatic Mixed Precision package - torch.amp10 Automatic Mixed Precision examples

Diagram

Data parallelism

Diagram: Each device runs the full model on its slice of the batch, gradients are averaged with an all-reduce, and every device applies the same...

Global batch

Device 0
full model copy

Device 1
full model copy

Device 2
full model copy

All-reduce:
average gradients

Same update
on every device

Diagram summary: Each device runs the full model on its slice of the batch, gradients are averaged with an all-reduce, and every device applies the same update. Memory per device does not shrink.

Source11 Distributed Data Parallel (developer notes)

Worked example

What an all-reduce costs

tring=2(n−1)nSB+2(n−1)α,tcentral=2(n−1)SBt_{\text{ring}}=\frac{2(n-1)}{n}\frac{S}{B}+2(n-1)\alpha,\qquad t_{\text{central}}=\frac{2(n-1)S}{B}

14 GB of gradients, 50 GB/s (assumed):

Devices28641,024
Ring (s)0.2800.4900.5510.559
Central (s)0.563.9235.28572.88
  • The ring cost is nearly flat in nn. A step that computes for 0.3 s and waits 0.56 s is communication-bound.

Compare

ZeRO stages and FSDP

StageSharded7B on 8 devicesPyTorch FSDP
0Nothing112.0 GBNO_SHARD
1Optimizer states38.5 GBnone
2+ gradients26.2 GBSHARD_GRAD_OP
3+ weights14.0 GBFULL_SHARD
  • Stage 3 costs about 50% more communication in the paper. Stages 1 and 2 keep the volume of plain data parallelism.
  • HYBRID_SHARD shards inside a node and replicates across nodes.
  • PyTorch 2.15 also ships FSDP2 (fully_shard, per-parameter DTensor sharding) and suggests migrating from FSDP1.

Sources1 ZeRO: Memory Optimizations Toward Training Trillion Parameter Models12 FullyShardedDataParallel13 torch.distributed.fsdp.fully_shard (FSDP2)

Math

Tensor and pipeline parallelism

bubble=p−1m+p−1\text{bubble}=\frac{p-1}{m+p-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.

Sources14 GPipe: Easy Scaling with Micro-Batch Pipeline Parallelism15 Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM16 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+⌈nk⌉ units,k∗≈nk+\left\lceil\frac nk\right\rceil\ \text{units},\qquad k^\ast\approx\sqrt n
LayersNo checkpointingBest kPeak units
161648
1001001020
1,0001,0002864
  • 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.

Sources17 Training Deep Nets with Sublinear Memory Cost18 torch.utils.checkpoint

Worked example

Loader and failures

Loader workers (compute 0.25 s, load 0.9 s)1234
Step time (s)0.90.450.30.25
Accelerator busy28%56%83%100%
  • Checkpoint interval about 2wM\sqrt{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.

Sources19 torch.utils.data (DataLoader)20 Distributed Checkpoint - torch.distributed.checkpoint21 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. 2020Hoffmann et al. 2022
FindingLoss is a power law in size, data and computeScale model size and tokens in equal proportion
AdviceVery large models, modest data, stop earlyChinchilla: 70B on 1.4T tokens beats Gopher 280B at the same compute
Tokens per parametern/a20 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.

Sources4 Scaling Laws for Neural Language Models22 Training Compute-Optimal Large Language Models

Math

Cost with 6ND

C≈6 N D,days=CG⋅P⋅u⋅86,400C\approx 6\,N\,D,\qquad \text{days}=\frac{C}{G\cdot P\cdot u\cdot 86{,}400}
  • 7B parameters on 101210^{12} tokens: 4.2×10224.2\times10^{22} 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×10235.76\times10^{23}: 6ND is 12.5% low for Gopher (5.04×10235.04\times10^{23}) and 2.1% high for Chinchilla (5.88×10235.88\times10^{23}).

Sources4 Scaling Laws for Neural Language Models22 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)

  1. 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

    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).

  2. Adam: A Method for Stochastic Optimization (opens in a new tab)

    Diederik P. Kingma, Jimmy Ba2015ICLR 2015 (arXiv:1412.6980)Paper

    Used for Adam keeps first and second moment estimates per parameter.

  3. 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

    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.

  4. 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

    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.

  5. Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift (opens in a new tab)

    Sergey Ioffe, Christian Szegedy2015ICML 2015 (arXiv:1502.03167)Paper

    Used for Batch normalisation computes statistics over the mini-batch.

References

References & Sources (2 of 5)

  1. Fixing Gradient Accumulation (opens in a new tab)

    Hugging Face2024Article

    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.

  2. torch.nn.parallel.DistributedDataParallel (opens in a new tab)

    PyTorch2026Documentation

    Used for The no_sync() context manager that accumulates gradients locally and synchronises on the first backward pass outside it.

  3. Mixed Precision Training (opens in a new tab)

    Paulius Micikevicius, Sharan Narang, Jonah Alben, Gregory Diamos, et al.2018ICLR 2018 (arXiv:1710.03740)Paper

    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).

  4. Automatic Mixed Precision package - torch.amp (opens in a new tab)

    PyTorch2026Documentation

    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.

  5. Automatic Mixed Precision examples (opens in a new tab)

    PyTorch2026Documentation

    Used for Unscaling before gradient clipping, and keeping the scale constant while gradients accumulate over an effective batch.

References

References & Sources (3 of 5)

  1. Distributed Data Parallel (developer notes) (opens in a new tab)

    PyTorch2026Documentation

    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.

  2. FullyShardedDataParallel (opens in a new tab)

    PyTorch2026Documentation

    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.

  3. torch.distributed.fsdp.fully_shard (FSDP2) (opens in a new tab)

    PyTorch2026Documentation

    Used for FSDP2 fully_shard with per-parameter DTensor sharding, the suggestion to migrate from FSDP1, and the reshard_after_forward behaviour.

  4. 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

    Used for Micro-batch pipeline parallelism and the bubble overhead of order (K - 1) / (M + K - 1).

  5. 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

    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)

  1. Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism (opens in a new tab)

    Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, et al.2019arXiv:1909.08053Preprint

    Used for Intra-layer model parallelism with a few communication operations in native PyTorch, up to 8.3B parameters on 512 GPUs (abstract).

  2. Training Deep Nets with Sublinear Memory Cost (opens in a new tab)

    Tianqi Chen, Bing Xu, Chiyuan Zhang, Carlos Guestrin2016arXiv:1604.06174Preprint

    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).

  3. torch.utils.checkpoint (opens in a new tab)

    PyTorch2026Documentation

    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.

  4. torch.utils.data (DataLoader) (opens in a new tab)

    PyTorch2026Documentation

    Used for Single and multi-process loading, num_workers, pin_memory, and the prefetch_factor default.

  5. Distributed Checkpoint - torch.distributed.checkpoint (opens in a new tab)

    PyTorch2026Documentation

    Used for Sharded save and load from multiple ranks and load-time resharding.

References

References & Sources (5 of 5)

  1. Reproducibility (opens in a new tab)

    PyTorch2026Documentation

    Used for Reproducibility is not guaranteed across releases or platforms, deterministic algorithms can be slower, and seeding DataLoader workers.

  2. Training Compute-Optimal Large Language Models (opens in a new tab)

    Jordan Hoffmann, Sebastian Borgeaud, Arthur Mensch, Elena Buchatskaya, et al.2022arXiv:2203.15556Preprint

    Used for Equal scaling of model size and tokens, the Chinchilla and Gopher comparison, Table 1 sizes and token counts, and FLOPs approximately 6ND.