Training at scale: memory arithmetic, parallelism, mixed precision and scaling laws
- Production
- 2 h
- Lesson 2 of 3 in ML systems and interviews
- Last verified
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
Before you start
- Completed:Training deep networks: normalisation, regularisation, AdamW and debuggingDeep learning and transformers
- Completed:Transformers, large language models, sampling and fine-tuningDeep learning and transformers
- Completed:ML system design: framing, budgets, two-stage retrieval, serving, rollout and monitoring
You will be able to
- Account for training memory (weights, gradients, optimizer states, activations), compute the 16-bytes-per-parameter budget for mixed-precision Adam, and say whether a model fits on one device.
- Scale batch size and learning rate with the linear scaling rule and warmup, use gradient accumulation without changing the gradient, and explain mixed precision with loss scaling and master weights.
- Choose between data parallelism (all-reduce, DDP), ZeRO/FSDP sharding stages, tensor parallelism and pipeline parallelism, and estimate communication time and the pipeline bubble.
- Trade compute for memory with activation checkpointing, find data-loading bottlenecks, and plan checkpoints, failure recovery and reproducibility for long runs.
- Estimate training compute with FLOPs of about 6ND, turn it into days on a cluster, and explain what scaling laws and compute-optimal training say about model and data size.
Concept
The previous lesson designed a system around a trained model. This lesson is about how a large model gets trained at all. A model that needs 112 GB just to hold its training state cannot run on an 80 GB accelerator, however good the code is, so training at scale is first an accounting problem and then a communication problem. Every technique here trades one resource for another: memory for compute, memory for network traffic, speed for numerical risk.
| Question | Tool in this lesson |
|---|---|
| Where does the memory go? | Weights, gradients, optimizer states, activations |
| How big a batch, at what learning rate? | Linear scaling rule, warmup, gradient accumulation |
| Can I use fewer bits? | fp16 or bf16 with loss scaling and fp32 master weights |
| How do I use many devices? | Data parallelism, ZeRO and FSDP sharding, tensor and pipeline parallelism |
| How do I fit more per device? | Activation checkpointing |
| Why is my accelerator idle? | Data loading, communication, pipeline bubbles |
| How do I survive a 3-week run? | Checkpoints, resumption, reproducibility |
| What will it cost? | FLOPs of about 6ND, scaling laws, compute-optimal training |
Why It Matters
Most teams never pre-train a large model, but every team that fine-tunes one meets these numbers: the out-of-memory error, the question “why not just use a bigger batch”, and the cloud bill. The ZeRO paper opens with the problem: basic data parallelism does not reduce memory per device and runs out of memory for models with more than 1.4 billion parameters on 32 GB GPUs (Rajbhandari et al.). Interviews for applied roles use these topics because they test whether you can reason with numbers (common industry pattern): “how much memory does it take to fine-tune a 7B model with Adam?” has a one-line answer, and the follow-up decides the interview.
Mental Model
Think of training as a budget with four line items and a network. Each device has a fixed amount of memory. The four line items are the weights, the gradients, the optimizer states and the activations. Every technique either shrinks one line item (lower precision, sharding, checkpointing), or moves work across devices (parallelism), and the price is always compute or communication.
The memory budget
Training holds four things. Weights are the parameters. Gradients have one value per parameter. Optimizer states are extra tensors the optimizer keeps per parameter: plain SGD keeps none, momentum keeps one, Adam keeps two, a first moment and a second moment (Kingma and Ba). Activations are the intermediate values of the forward pass that backpropagation needs again, so they depend on batch size and sequence length, not on the parameter count alone.
For mixed-precision training with Adam the ZeRO paper counts it like this: 2 bytes per parameter for fp16 weights, 2 for fp16 gradients, and for the optimizer states, which are an fp32 copy of the weights, an fp32 first moment and an fp32 second moment (4 + 4 + 4 bytes) (Rajbhandari et al., section 3.1):
| Symbol | Meaning |
|---|---|
| Number of parameters | |
| Bytes of optimizer state per parameter (12 for mixed-precision Adam) | |
| 16 | Bytes of model state per parameter in total |
The paper’s own example is a GPT-2 model with 1.5 billion parameters: 3 GB of fp16 weights, but at least 24 GB of model state, and about 60 GB of activations at a sequence length of 1,000 and a batch of 32 without checkpointing (their figure). The numbers in this lesson come from one script, shown in the Code section. It gives 24 GB for 1.5 billion parameters, 112 GB for 7 billion (14 GB weights, 14 GB gradients, 84 GB optimizer states) and 1,120 GB for 70 billion. Keeping everything in fp32 does not help: fp32 weights and gradients with Adam’s two fp32 moments also total 16 bytes (4 + 4 + 8).
Three consequences matter in practice:
- Optimizer states dominate. Three quarters of the 16 bytes are optimizer state, so the cheapest memory wins come from sharding or avoiding them (a plain SGD optimizer, or freezing weights as LoRA does, see the fine-tuning lesson).
- Activations are separate. The 16 bytes per parameter is before activations, buffers and fragmentation, which the ZeRO paper calls residual states. A model can fit its state and still run out of memory at a larger batch.
- Fit is a yes-or-no question about the sum. For a 7B model on 8 devices of 80 GB each, with an assumed 20 GB of activations and 4 GB of overhead, the script finds that plain replication does not fit and the sharded variants do. The assumptions are the inputs; change them and the answer changes.
Batch size and learning rate
More devices usually means a larger global batch, because each device keeps its own share. A larger batch makes each gradient less noisy and uses the hardware better, but it also means fewer updates per epoch, so something has to compensate.
The linear scaling rule from Goyal et al.: when the minibatch size is multiplied by , multiply the learning rate by , and keep every other hyperparameter unchanged (Goyal et al.). The informal reason is that small steps with a small batch move about as far as one step with the large batch at times the rate, as long as the gradient barely changes across those steps. The paper names two cases where that condition fails. In early training the network changes quickly, so they add gradual warmup: start at the small rate and raise it by a constant amount each iteration until it reaches the scaled rate (5 epochs in their ImageNet runs). And the batch cannot grow without limit: in their experiments the error stayed stable from batch 64 to 8,192 and rose after that, and training diverged beyond 64k with the linear rule.
| Symbol | Meaning |
|---|---|
| Reference learning rate for the reference batch | |
| Batch multiplier (new batch divided by reference batch) | |
| Number of warmup steps |
In the script, a reference rate of 0.1 at batch 256 and a batch of 8,192 give and a target of 3.2, reached after a warmup of 5,000 steps: 0.1 at step 0, 0.72 at step 1,000, 1.65 at step 2,500, and 3.2 from step 5,000 (the numbers are an illustration of the formula, not the paper’s schedule). Without warmup the first step would use 3.2 straight away.
Large batches and generalisation. The paper’s headline is that careful scaling and warmup matched small-batch accuracy up to 8,192 images on ImageNet with ResNet-50 (trained in one hour on 256 GPUs, about 90% scaling efficiency). That result is for one task and one family of models; the rule is a starting point, not a guarantee. Kaplan et al. give a more general view: there is a critical batch size at which training is a roughly optimal compromise between time and compute efficiency, and it depends on the loss reached (Kaplan et al.). Below it, a bigger batch buys nearly linear speedup. Above it, you pay for more data per step with little reduction in the number of steps. Adaptive optimizers such as Adam are often tuned differently (a common alternative is a square-root rule, which is common practice and not a result from the sources above), so treat the learning rate as something to re-tune at a new batch size.
Gradient accumulation
When the batch you want does not fit in memory, run several micro-batches, add their gradients, and step the optimizer once. Memory depends on the micro-batch, the effective batch is the sum. The gradient is the same because the loss is a mean over samples:
| Symbol | Meaning |
|---|---|
| Samples in the effective batch | |
| Samples in micro-batch | |
| Mean gradient of micro-batch |
The script checks this on a line fitted to 10 points: the full-batch gradient is and micro-batches of 1, 2, 5 and 10 give the same numbers. Three mistakes are common. Forgetting to divide: summing three chunk means without dividing gives for the first component, three times too large. Weighting chunks equally when the last one is short: for chunks of 4, 4 and 2 an unweighted mean of chunk means gives , the weighted version gives . Layers that look across the batch: batch normalisation computes its statistics over whatever batch it sees (Ioffe and Szegedy). Accumulation does not change those statistics to match the big batch. Goyal et al. note that the per-worker batch size that BN sees is part of the loss being optimised, so changing it changes the loss. A tiny illustration: eight values with variance 5.25 have an average micro-batch variance of 1.25 in chunks of 4, 0.25 in chunks of 2, and 0 in chunks of 1. Layer norm and RMS norm work per sample, so they are not affected.
Token-level losses need a different normaliser. For a causal language model the loss is a sum over tokens, and micro-batches hold different numbers of real tokens once padding is excluded. Averaging each micro-batch’s mean token loss weights every micro-batch equally, which is not the mean over all tokens. Hugging Face found exactly this mismatch in their Trainer: the correct loss is the total loss across all micro-batches in an accumulation step divided by the total number of non-padding tokens in them, which is not the same as the average of the per-micro-batch loss values (Hugging Face). So sum the token losses in each micro-batch and divide by the token count of the whole effective batch, the same idea as dividing by the total sample count above with tokens as the unit.
Two practical rules. With data parallelism, the effective batch is micro-batch times accumulation steps times the number of processes, and the optimizer should step once per effective batch. And when using DDP, skip the gradient all-reduce on the non-final micro-batches: PyTorch’s no_sync() context manager disables gradient synchronisation, accumulates the gradients locally, and synchronises them in the first forward-backward pass outside the context, with the forward pass inside it (PyTorch, DistributedDataParallel). Otherwise you pay the communication on every micro-batch.
Mixed precision
Mixed precision runs most arithmetic in 16-bit floats and keeps a few things in 32 bits. It saves memory and moves less data. The risk is numerical: a 16-bit float has less range or less precision than a 32-bit one. Micikevicius et al. introduced three techniques that let fp16 training match fp32 accuracy on a wide range of models: an fp32 master copy of the weights, loss scaling, and fp16 arithmetic with accumulation in fp32 (Micikevicius et al.).
Why master weights. In fp16 the spacing between neighbouring numbers near 1.0 is about 0.001. The script rounds to fp16 and gets 1.0 back. A weight at 1.0 updated 100 times by 0.0001 stays at 1.0 in half precision, but reaches 1.0100 when the running sum is kept in higher precision. That is the master copy: small updates accumulate in fp32 and a rounded fp16 copy is used for the forward and backward passes.
Why loss scaling. fp16 has a narrow range. Its largest value is 65,504 (the script rounds 65,520 to infinity), and very small gradients flush to zero. PyTorch’s documentation describes the fix: multiply the loss by a scale factor so the gradients are larger, run backward, and unscale the gradients before the optimizer step so the scale does not interfere with the learning rate (PyTorch, torch.amp). In the script a gradient of becomes 0 at scale 1, but comes back as at scale 1,024 and at 65,536. Too large a scale overflows instead: a gradient of 2.0 times 65,536 exceeds 65,504 and becomes infinity, while at scale 8,192 it survives. Overflow gives infinities or NaN in the gradients, and Micikevicius et al. warn that an update from them irreversibly damages the weights.
That is why the scale is dynamic. PyTorch’s GradScaler defaults are an initial scale of 65,536, growth factor 2, back-off factor 0.5 and a growth interval of 2,000 steps. The logic, as modelled in the script: on a step with infinities, skip the update and halve the scale; after a run of clean steps, double it. A trace with a growth interval of 3 goes 65,536, 32,768 (after an overflow), 32,768, 32,768, 65,536 (three clean steps), and so on. Clipping must see unscaled gradients, so call the unscale step before clip_grad_norm_, and with accumulation keep the scale constant until the effective batch is complete (PyTorch, AMP examples).
bf16 versus fp16. bfloat16 keeps float32’s 8 exponent bits and shortens the fraction to 7 bits (format definition, common practice). It therefore has fp32’s range but less precision than fp16, which is why many teams train in bf16 without loss scaling (common practice). The script emulates the format: survives as , 70,000 is representable (as 70,144), and rounds to 1.0. The trade-off is precision, so master weights and fp32 accumulation still matter. A PyTorch note also warns that a model pre-trained in bf16 may overflow the fp16 range, so it may not run safely in fp16 (PyTorch, torch.amp).
Data parallelism and communication
In data parallelism every device holds a full copy of the model, runs forward and backward on its own slice of the batch, and the gradients are averaged across devices before the optimizer step. All copies start identical and apply the same averaged gradient, so they stay identical. PyTorch’s DistributedDataParallel (DDP) does this: its constructor broadcasts the state from rank 0, it groups gradients into buckets, and when all gradients of a bucket are ready it starts an asynchronous all-reduce that computes their mean, overlapping communication with the rest of the backward pass (PyTorch, DDP notes). All processes must reduce the buckets in the same order, or results are wrong or the run hangs.
Data parallelism is simple and scales well while the model fits on one device. It does not reduce memory per device at all, which is the limit the ZeRO paper starts from.
What an all-reduce costs. In a ring all-reduce over devices each device sends and receives about times the data size, so for large the time approaches for data size and link bandwidth , almost independent of . A naive design where one device collects everything and sends the sum back moves through one link. This is the standard cost model for bandwidth-optimal all-reduce and the formulas are derived here, not taken from the sources above:
| Symbol | Meaning |
|---|---|
| Bytes reduced (for DDP, the gradient size) | |
| Bandwidth per link in bytes per second | |
| Number of devices | |
| Latency per step in seconds |
With the gradients of a 7B model in half precision ( GB) and an assumed 50 GB/s link, the script gives a ring time of 0.28 s for 2 devices, 0.490 s for 8, 0.551 s for 64 and 0.559 s for 1,024, while the central design takes 0.56 s, 3.92 s, 35.28 s and 572.88 s. Adding an assumed 5 microseconds per step lifts the 1,024-device ring to 0.570 s. So the ring cost is flat in , which is why data parallelism scales so far, but a step that computes in 0.3 s and waits 0.56 s for gradients is communication-bound. Overlap with the backward pass, faster links and fewer bytes (lower precision) are the levers. Real clusters have layered networks (fast links inside a server, slower between servers), so where each kind of traffic runs matters; Narayanan et al. report that a poor combination of tensor and pipeline parallelism cost up to 2 times in throughput even with fast links between servers (Narayanan et al.).
Sharding: ZeRO and FSDP
Data parallelism wastes memory: every device stores the same 16 bytes per parameter. ZeRO (Zero Redundancy Optimizer) keeps the data-parallel programming model but partitions the model state across the data-parallel devices, three stages, each adding to the one before (Rajbhandari et al.):
| Stage | What is partitioned | Memory per parameter (mixed-precision Adam) | Paper’s stated effect |
|---|---|---|---|
| 0 (plain DP) | Nothing | bytes | Baseline |
| 1 | Optimizer states | 4 times less memory, same communication as DP | |
| 2 | + gradients | 8 times less memory, same communication as DP | |
| 3 | + parameters | Memory falls linearly with ; about 50% more communication |
The paper’s example is 7.5 billion parameters on 64 devices with . The script’s function gives 120 GB for plain replication, 31.4 GB for stage 1, 16.6 GB for stage 2 and 1.9 GB for stage 3. For a 7B model on 8 devices it gives 112, 38.5, 26.2 and 14.0 GB. The “4 times” and “8 times” in the paper are limits for large (at , stage 1 gives 112 / 38.5, about 2.9 times). The paper also shows the cost of stage 3: parameters must be gathered before use, which is the extra 50% communication.
PyTorch’s FSDP (FullyShardedDataParallel) is inspired by ZeRO stage 3 and by earlier work, and shards module parameters across data-parallel workers (PyTorch, FSDP). Its sharding strategies are:
FULL_SHARD: parameters, gradients and optimizer states are sharded. Parameters are all-gathered before the forward and again before the backward and resharded after; gradients are reduce-scattered. This corresponds to ZeRO-3.SHARD_GRAD_OP: gradients and optimizer states are sharded, and the parameters stay gathered between forward and backward. This corresponds to ZeRO-2, and the documentation’s own name for the hybrid variant,_HYBRID_SHARD_ZERO2, is defined asSHARD_GRAD_OPwithin a node.NO_SHARD: replicated like DDP.HYBRID_SHARD: full sharding inside a node, replication across nodes, so the expensive gathers stay on the fast links.
PyTorch 2.15 also ships FSDP2, fully_shard, which represents sharded parameters as DTensors split along dimension 0 (per-parameter sharding) and whose documentation suggests that FSDP1 users consider migrating (PyTorch, FSDP2). Its reshard_after_forward option, when true, frees the gathered parameters after the forward pass and gathers them again in the backward pass, which is the FULL_SHARD behaviour. The ideas in this section carry over to either API.
The practical rule of thumb: use DDP while the model state plus activations fit, and move to sharding when they do not. Sharding trades memory for communication, and it also complicates checkpoints (see below).
Tensor and pipeline parallelism
Sharding keeps each layer whole on every device at the moment it computes. For models whose individual layers or activations are too large, split the model itself.
Tensor (intra-layer) parallelism splits the matrices inside a layer across devices, so each device computes part of every layer and devices exchange partial results inside each layer. Megatron-LM showed this needs only a few communication operations, implementable in native PyTorch, and trained transformers up to 8.3 billion parameters on 512 GPUs (Shoeybi et al.). Because it communicates inside every layer, it is effective within one multi-GPU server with fast links, and pipeline parallelism is used for larger models (Narayanan et al.).
Pipeline (inter-layer) parallelism puts consecutive groups of layers on different devices (stages) and sends activations between them. To keep the stages busy, the batch is split into microbatches that flow through like items on an assembly line (Huang et al., GPipe). The cost is the bubble: at the start the later stages wait for work and at the end the earlier stages wait for the last backward passes. With stages and microbatches in a simple schedule, the idle share of the whole step is
| Symbol | Meaning |
|---|---|
| Pipeline stages | |
| Microbatches per batch |
GPipe states the bubble as and Narayanan et al. give as the idle time relative to ideal compute time (the same quantity divided by a different base). In the script, 4 stages give a bubble of 0.75 with 1 microbatch, 0.429 with 4, 0.158 with 16 and 0.045 with 64, and 8 stages give 0.875, 0.636, 0.304 and 0.099. To keep the bubble at or below 10%, 2 stages need 9 microbatches, 4 need 27, 8 need 63 and 16 need 135. So more stages need more microbatches, which means a bigger batch, which is limited by the critical batch size above. GPipe reports that in their experiments the overhead was negligible when , partly because recomputation can be scheduled earlier; the plain formula gives 0.179 at 8 stages and 32 microbatches, so treat it as the idealised estimate, and real schedules differ. Narayanan et al. report that as much as 50% of the time can be spent flushing the pipeline, and an interleaved schedule that divides the bubble by the number of model chunks per device costs that many times more communication.
Choosing a parallelism strategy
The order follows complexity and communication cost: simplest first, and keep the chattiest parallelism on the fastest links (common practice, consistent with the Megatron findings above). Large runs combine them: Narayanan et al. combine tensor, pipeline and data parallelism and show that a poor combination of tensor and pipeline parallelism can cost up to 2 times in throughput, even with fast links between servers. In an interview, say which link each choice uses.
Activation checkpointing
Activations are the line item that grows with batch size and sequence length. Activation checkpointing (also called gradient checkpointing or rematerialisation) keeps only some activations and recomputes the rest during the backward pass. PyTorch describes it as trading compute for memory: tensors computed in the checkpointed function are not kept alive, and are recomputed by re-running the function in the backward pass (PyTorch, torch.utils.checkpoint). Chen et al. give an algorithm that needs memory for an -layer network at the cost of one extra forward pass per minibatch, and report cutting memory for a 1,000-layer residual network from 48 GB to 7 GB with about 30% more running time on ImageNet (Chen et al.).
The idea in numbers: cut the network into segments and keep only the boundaries. During the backward pass of one segment you hold that segment’s layers of activations, so the peak is
(a simplified model derived here, in units of one layer’s activations). The script finds, for 100 layers, a peak of 100 units without checkpointing and 20 with ; for 1,000 layers 64 units with . The extra compute is one more forward pass. If a backward pass costs twice a forward pass (implied by the rule below, in which 2N is forward and 4N is backward), the forward is of the step, so about a third more compute, in line with the roughly 30% Chen et al. report for their case. Selective schemes recompute only the cheap, memory-heavy operations to pay less (common practice).
Two cautions from the PyTorch documentation: recomputing a layer that uses randomness, such as dropout, can give different values unless the random state is saved and restored, which it does by default at a moderate speed cost; and the newer non-reentrant implementation is the recommended one.
Data loading and throughput
A fast accelerator that waits for data is wasted money. Loading and preprocessing run on the CPU while the accelerator computes, so the goal is to keep the next batch ready. PyTorch’s DataLoader loads in the main process by default, which can block computation. Setting num_workers to a positive number loads in separate processes, and pin_memory=True puts fetched tensors in page-locked memory, which makes host-to-GPU copies faster (PyTorch, torch.utils.data). The prefetch_factor default is 2 batches per worker when num_workers is above 0, and None when it is 0.
A simple model, derived here, covers most diagnosis. If one worker needs seconds to prepare a batch and workers run in parallel, a batch is ready every seconds, so a step takes where is compute time. With s and s the script gives step times of 0.9, 0.45, 0.3 and 0.25 s for 1, 2, 3 and 4 workers: the accelerator is busy 28%, 56%, 83% and 100% of the time, and extra workers beyond 4 change nothing. The symptoms of a loader bottleneck are low accelerator utilisation, step time that falls when you add workers, and a step time that does not depend on the model. Profile before tuning (common practice). The same reasoning applies to storage and network reads, and to communication: if the step time barely changes when you make the model smaller, something else is the bottleneck.
Checkpoints, failures and reproducibility
A run on many devices for weeks will see failures. A checkpoint saves enough state to resume exactly: weights, optimizer states, the learning-rate schedule position and step count, the data-loader position and random states (common practice). Saving too rarely loses work; saving too often wastes time. The first-order approximation usually named after Young (1974), derived here from the two costs below, says that with checkpoint write time , interval and mean time between failures (all in the same unit), the lost share of time is about
The first term is time spent writing, the second assumes a failure on average redoes half an interval. With an assumed write of 3 minutes and a failure every 360 minutes, the script gives a best interval of 46.5 minutes and 12.9% of time lost; checkpointing every 5 minutes loses 60.7% and every 240 minutes loses 34.6%. The curve is flat near its minimum (13.3% at 60 minutes) and steep away from it, so the exact value matters less than being in the right region. It assumes the write time is much smaller than the time between failures, and it ignores that a failure also costs restart time (common practice).
With sharded training each rank holds only a piece, so checkpoints are sharded too. PyTorch’s Distributed Checkpoint saves and loads from multiple ranks in parallel, writes at least one file per rank, and supports load-time resharding so a checkpoint saved on one cluster layout can be loaded on another (PyTorch, Distributed Checkpoint). That is what lets you resume on fewer or more devices after a failure.
Reproducibility has limits. PyTorch states that completely reproducible results are not guaranteed across releases, commits or platforms, or between CPU and GPU, even with identical seeds. You can seed the generators, ask for deterministic algorithms (often slower), and seed the DataLoader workers with a generator and worker_init_fn (PyTorch, Reproducibility). At scale there is another source: summing floating-point numbers in a different order, which happens when the number of devices changes, gives slightly different results (common practice). So aim for repeatable experiments (same config, code version, seed, data order logged) rather than bit-identical runs, and compare runs over several seeds before believing a small difference.
Scaling laws and compute-optimal training
Before spending a cluster, a team asks: for a fixed compute budget, how large a model and how much data? Scaling laws are empirical fits that answer it. Kaplan et al. found for language models that the loss follows a power law in model size, dataset size and training compute, that architectural details like width or depth matter little within a broad range, and that larger models are more sample-efficient (Kaplan et al.). They concluded the most compute-efficient training uses very large models on a modest amount of data and stops well before convergence.
Hoffmann et al. re-examined this by training over 400 models from 70 million to over 16 billion parameters on 5 to 500 billion tokens. Their conclusion: for compute-optimal training, model size and training tokens should be scaled in equal proportion, so every doubling of model size should come with a doubling of tokens (Hoffmann et al.). They tested it with Chinchilla, a 70B model trained on 1.4 trillion tokens with the same compute budget as Gopher (280B parameters, 300 billion tokens). Chinchilla outperformed Gopher and several larger models on many downstream tasks, and reached 67.5% average accuracy on MMLU, more than 7 points above Gopher. A smaller model also costs less to run for inference, which the authors point out.
From their table (Table 1) the ratio of tokens to parameters is for Chinchilla and about 1.07 for Gopher (arithmetic derived here). “20 tokens per parameter” is therefore the ratio of that one result, a rule of thumb that circulates widely, not a law of nature: the fitted frontier depends on the data, the architecture and the training setup, and the paper itself fits the frontier three different ways. Also, compute-optimal is optimal for the training budget. A model that will serve billions of requests may be better trained smaller and longer than the optimum, since inference cost then dominates (common practice).
Estimating cost
The workhorse estimate: training takes about six floating-point operations per parameter per token. Kaplan et al. define (non-embedding parameters , batch size , steps, so plays the role of the total tokens) and Hoffmann et al. use with tokens. The factor has a source: a forward pass costs roughly operations per token (a multiply and an add for each weight) per Kaplan et al., so the remaining 4 of the 6 belong to the backward pass, about twice the forward (derived here).
| Symbol | Meaning |
|---|---|
| Parameters (non-embedding, in the scaling-law papers) | |
| Training tokens | |
| Number of devices | |
| Peak FLOP/s of one device | |
| Utilisation, the fraction of peak you actually achieve |
The rule is approximate: it ignores the attention term that grows with context length and it counts only the non-embedding parameters. The script applies it to the two models above: Chinchilla is FLOPs and Gopher is FLOPs. Hoffmann et al. give 5.76e23 FLOPs for Gopher’s training budget and say Chinchilla used the same budget, so against that figure the rule is 12.5% low for Gopher (5.04e23) and 2.1% high for Chinchilla (5.88e23). Their own FLOP counts for models up to 6.8B parameters, compared with in their appendix, give ratios between 0.99 and 1.10. That is fine for planning and not for billing.
For the cluster, take a 7B model on tokens: FLOPs. With an assumed peak of 300 TFLOP/s per device (a round number for illustration, not the specification of any particular chip) and an assumed 40% utilisation, 1,024 devices need 3.96 days and 256 devices need 15.82 days. Both assumptions move the answer by large factors, so state them, and expect real utilisation to come from measurement. Given a budget, the script’s compute_optimal function inverts the rule with : for FLOPs it returns parameters and tokens, and at the paper’s Gopher budget of it returns parameters and tokens, close to the 67B parameters and 1.5 trillion tokens that the paper’s own projection (its Table 3) gives for that budget.
Inference is cheaper per token: a forward pass is about operations, so FLOPs per token for a 7B model (derived from the same rule). Fine-tuning with LoRA changes the memory arithmetic, not the forward cost: the frozen weights are still read each step.
Code
This standard-library script produced every number in the lesson that is computed here. The first part is the helper code from homework/solution.py (without docstrings); the rest is the experiments. It has no random numbers, so the output is the same on every run and every Python version (written with Python 3.14.6, run with python3 -I, about 0.02 seconds). The half-precision rounding uses the struct module’s e format, which follows IEEE half precision. Sizes use 1 GB = bytes. The bandwidths, utilisation, failure rate and peak speed in sections 5, 9 and 10 are assumptions, not measurements of any real system.
import math
import struct
def state_bytes_per_param(stage, dp, weight_bytes=2, grad_bytes=2, optimizer_bytes=12):
if stage not in (0, 1, 2, 3):
raise ValueError("stage must be 0, 1, 2 or 3")
if not isinstance(dp, int) or isinstance(dp, bool) or dp < 1:
raise ValueError("dp must be a whole number >= 1")
if weight_bytes < 0 or grad_bytes < 0 or optimizer_bytes < 0:
raise ValueError("byte counts must not be negative")
w, g, o = float(weight_bytes), float(grad_bytes), float(optimizer_bytes)
if stage == 0:
return w + g + o
if stage == 1:
return w + g + o / dp
if stage == 2:
return w + (g + o) / dp
return (w + g + o) / dp
def model_state_gb(params, dp, stage, weight_bytes=2, grad_bytes=2, optimizer_bytes=12):
if params < 0:
raise ValueError("params must not be negative")
per = state_bytes_per_param(stage, dp, weight_bytes, grad_bytes, optimizer_bytes)
return params * per / 1e9
def fits_on_gpu(params, dp, stage, gpu_gb, activation_gb=0.0, overhead_gb=0.0, **bytes_kw):
if gpu_gb < 0 or activation_gb < 0 or overhead_gb < 0:
raise ValueError("memory sizes must not be negative")
total = model_state_gb(params, dp, stage, **bytes_kw) + activation_gb + overhead_gb
return total <= gpu_gb
def scaled_lr(base_lr, base_batch, batch, step, warmup_steps):
if base_lr <= 0 or base_batch <= 0 or batch <= 0:
raise ValueError("base_lr, base_batch and batch must be positive")
if step < 0 or warmup_steps < 0:
raise ValueError("step and warmup_steps must not be negative")
target = base_lr * (batch / base_batch)
if warmup_steps == 0 or step >= warmup_steps:
return target
return base_lr + (target - base_lr) * (step / warmup_steps)
def mse_gradient(w, b, xs, ys):
if len(xs) != len(ys) or len(xs) == 0:
raise ValueError("xs and ys must have the same non-zero length")
n = len(xs)
dw = db = 0.0
for x, y in zip(xs, ys):
err = w * x + b - y
dw += 2.0 * err * x
db += 2.0 * err
return dw / n, db / n
def accumulated_gradient(w, b, xs, ys, micro_size):
if not isinstance(micro_size, int) or isinstance(micro_size, bool) or micro_size < 1:
raise ValueError("micro_size must be a whole number >= 1")
if len(xs) != len(ys) or len(xs) == 0:
raise ValueError("xs and ys must have the same non-zero length")
total_w = total_b = 0.0
for start in range(0, len(xs), micro_size):
cx = xs[start:start + micro_size]
cy = ys[start:start + micro_size]
gw, gb = mse_gradient(w, b, cx, cy)
total_w += gw * len(cx)
total_b += gb * len(cx)
n = len(xs)
return total_w / n, total_b / n
def micro_batch_variance_mean(values, micro_size):
if len(values) == 0:
raise ValueError("values must not be empty")
if not isinstance(micro_size, int) or isinstance(micro_size, bool) or micro_size < 1:
raise ValueError("micro_size must be a whole number >= 1")
variances = []
for start in range(0, len(values), micro_size):
chunk = values[start:start + micro_size]
m = sum(chunk) / len(chunk)
variances.append(sum((v - m) ** 2 for v in chunk) / len(chunk))
return sum(variances) / len(variances)
def to_fp16(x):
try:
return struct.unpack("<e", struct.pack("<e", x))[0]
except OverflowError:
return math.inf if x > 0 else -math.inf
def fp16_gradient(grad, scale):
if scale <= 0:
raise ValueError("scale must be positive")
scaled = to_fp16(grad * scale)
if math.isinf(scaled) or math.isnan(scaled):
return scaled
return scaled / scale
def next_loss_scale(scale, found_inf, good_steps, growth_factor=2.0, backoff_factor=0.5,
growth_interval=2000):
if found_inf:
return scale * backoff_factor, 0
good_steps += 1
if good_steps >= growth_interval:
return scale * growth_factor, 0
return scale, good_steps
def ring_allreduce_seconds(size_bytes, n, bandwidth, latency=0.0):
if not isinstance(n, int) or isinstance(n, bool) or n < 1:
raise ValueError("n must be a whole number >= 1")
if bandwidth <= 0 or size_bytes < 0 or latency < 0:
raise ValueError("bandwidth must be positive, size and latency not negative")
if n == 1:
return 0.0
return 2.0 * (n - 1) / n * size_bytes / bandwidth + 2.0 * (n - 1) * latency
def central_allreduce_seconds(size_bytes, n, bandwidth):
if not isinstance(n, int) or isinstance(n, bool) or n < 1:
raise ValueError("n must be a whole number >= 1")
if bandwidth <= 0 or size_bytes < 0:
raise ValueError("bandwidth must be positive, size not negative")
return 2.0 * (n - 1) * size_bytes / bandwidth
def bubble_fraction(stages, microbatches):
for v in (stages, microbatches):
if not isinstance(v, int) or isinstance(v, bool) or v < 1:
raise ValueError("stages and microbatches must be whole numbers >= 1")
return (stages - 1) / (microbatches + stages - 1)
def microbatches_for_bubble(stages, target):
if not 0 < target < 1:
raise ValueError("target must be between 0 and 1")
if not isinstance(stages, int) or isinstance(stages, bool) or stages < 1:
raise ValueError("stages must be a whole number >= 1")
m = 1
while (stages - 1) > target * (m + stages - 1) + 1e-12:
m += 1
return m
def activation_units(n_layers, k):
if not isinstance(n_layers, int) or isinstance(n_layers, bool) or n_layers < 1:
raise ValueError("n_layers must be a whole number >= 1")
if not isinstance(k, int) or isinstance(k, bool) or not 1 <= k <= n_layers:
raise ValueError("k must be a whole number between 1 and n_layers")
return k + -(-n_layers // k)
def best_checkpoint_count(n_layers):
best_k = 1
best = activation_units(n_layers, 1)
for k in range(2, n_layers + 1):
u = activation_units(n_layers, k)
if u < best:
best, best_k = u, k
return best_k
def recompute_overhead(forward=1.0, backward=2.0):
if forward < 0 or backward < 0 or forward + backward <= 0:
raise ValueError("costs must not be negative and must not both be zero")
return forward / (forward + backward)
def loader_step_time(compute_s, load_s, workers):
if not isinstance(workers, int) or isinstance(workers, bool) or workers < 1:
raise ValueError("workers must be a whole number >= 1")
if compute_s < 0 or load_s < 0:
raise ValueError("times must not be negative")
return max(compute_s, load_s / workers)
def min_workers(compute_s, load_s):
if compute_s <= 0 or load_s < 0:
raise ValueError("compute_s must be positive and load_s not negative")
w = 1
while load_s / w > compute_s + 1e-12:
w += 1
return w
def wasted_fraction(interval, write, mtbf):
if interval <= 0 or write <= 0 or mtbf <= 0:
raise ValueError("interval, write and mtbf must be positive")
return write / interval + interval / (2.0 * mtbf)
def best_interval(write, mtbf):
if write <= 0 or mtbf <= 0:
raise ValueError("write and mtbf must be positive")
return math.sqrt(2.0 * write * mtbf)
def training_flops(params, tokens):
if params < 0 or tokens < 0:
raise ValueError("params and tokens must not be negative")
return 6.0 * params * tokens
def training_days(flops, gpus, peak_flops_per_gpu, utilisation):
if not isinstance(gpus, int) or isinstance(gpus, bool) or gpus < 1:
raise ValueError("gpus must be a whole number >= 1")
if peak_flops_per_gpu <= 0 or not 0 < utilisation <= 1 or flops < 0:
raise ValueError("bad peak, utilisation or flops")
return flops / (gpus * peak_flops_per_gpu * utilisation) / 86400.0
def compute_optimal(flops, tokens_per_param=20.0):
if flops < 0 or tokens_per_param <= 0:
raise ValueError("flops must not be negative and tokens_per_param must be positive")
n = math.sqrt(flops / (6.0 * tokens_per_param))
return n, tokens_per_param * n
print("== 1. Memory: where the bytes go")
for name, p in (("1.5B", 1.5e9), ("7B", 7e9), ("70B", 70e9)):
w = p * 2 / 1e9
g = p * 2 / 1e9
o = p * 12 / 1e9
print(f"{name}: weights {w:.0f} GB, gradients {g:.0f} GB, Adam states and fp32 copy {o:.0f} GB, total {model_state_gb(p, 1, 0):.0f} GB")
print("bytes per parameter, mixed-precision Adam:", state_bytes_per_param(0, 1))
print("7B model state per device, 8 devices:")
for stage in (0, 1, 2, 3):
print(f" stage {stage}: {state_bytes_per_param(stage, 8):.2f} bytes per parameter, {model_state_gb(7e9, 8, stage):.1f} GB")
print("7.5B model on 64 devices:", [round(model_state_gb(7.5e9, 64, s), 1) for s in (0, 1, 2, 3)], "GB")
print("fits on an 80 GB device with 20 GB of activations and 4 GB overhead, 7B, 8 devices:",
[fits_on_gpu(7e9, 8, s, 80, 20, 4) for s in (0, 1, 2, 3)])
print("fp32 weights and gradients plus Adam (4+4+8):", state_bytes_per_param(0, 1, 4, 4, 8), "bytes per parameter")
print("\n== 2. Batch size and learning rate")
base_lr, base_batch, batch, warm = 0.1, 256, 8192, 5000
print(f"k = {batch // base_batch}, target rate {scaled_lr(base_lr, base_batch, batch, warm, warm):.2f}")
for step in (0, 1000, 2500, 4999, 5000, 9000):
print(f" step {step:>5}: lr {scaled_lr(base_lr, base_batch, batch, step, warm):.4f}")
print("no warmup, step 0:", scaled_lr(base_lr, base_batch, batch, 0, 0))
print("\n== 3. Gradient accumulation")
xs = [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]
ys = [1.2, 1.9, 3.1, 3.8, 5.3, 5.9, 7.2, 7.8, 9.1, 9.9]
full = mse_gradient(0.5, 0.0, xs, ys)
print(f"full batch of 10: dw {full[0]:.6f} db {full[1]:.6f}")
for micro in (1, 2, 5, 10):
a = accumulated_gradient(0.5, 0.0, xs, ys, micro)
print(f"micro-batches of {micro:>2}: dw {a[0]:.6f} db {a[1]:.6f}")
micro = 4
a = accumulated_gradient(0.5, 0.0, xs, ys, micro)
chunks = [(xs[i:i + micro], ys[i:i + micro]) for i in range(0, len(xs), micro)]
sizes = [len(cx) for cx, cy in chunks]
print(f"micro-batches of {micro} (sizes {sizes}): dw {a[0]:.6f} db {a[1]:.6f}")
chunk_means = [mse_gradient(0.5, 0.0, cx, cy)[0] for cx, cy in chunks]
print(f"unweighted mean of {len(chunks)} chunk means: dw {sum(chunk_means) / len(chunks):.6f}")
print(f"sum of {len(chunks)} chunk means, no division: dw {sum(chunk_means):.6f}")
vals = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]
m = sum(vals) / len(vals)
fullvar = sum((v - m) ** 2 for v in vals) / len(vals)
print(f"variance of 8 values {fullvar:.4f}; mean of per-micro-batch variances: size 4 {micro_batch_variance_mean(vals, 4):.4f}, size 2 {micro_batch_variance_mean(vals, 2):.4f}, size 1 {micro_batch_variance_mean(vals, 1):.4f}")
print("\n== 4. Mixed precision")
print("half precision largest value:", to_fp16(65504.0), " 65520 rounds to:", to_fp16(65520.0))
print("1.0 + 0.0001 in half precision:", to_fp16(1.0 + 0.0001))
w16 = w_wide = 1.0
for _ in range(100):
w16 = to_fp16(w16 + 0.0001)
w_wide = w_wide + 0.0001
print(f"100 updates of 0.0001: half-precision weight {w16}, higher-precision master weight {w_wide:.4f}")
for grad in (1e-8, 3e-8, 1e-5):
row = ", ".join(f"scale {s:>5}: {fp16_gradient(grad, s):.3e}" for s in (1, 1024, 65536))
print(f"gradient {grad:.0e} -> {row}")
print("gradient 2.0 at scale 65536:", fp16_gradient(2.0, 65536), " at scale 8192:", fp16_gradient(2.0, 8192))
scale, good = 65536.0, 0
trace = []
for found_inf in (False, True, False, False, False, False, False, True, False):
scale, good = next_loss_scale(scale, found_inf, good, growth_interval=3)
trace.append(f"{'inf' if found_inf else 'ok '}->{scale:g}")
print("loss scale trace (growth interval 3):", " ".join(trace))
def to_bf16(x):
bits = struct.unpack("<I", struct.pack("<f", x))[0]
bits += 0x7FFF + ((bits >> 16) & 1)
return struct.unpack("<f", struct.pack("<I", (bits & 0xFFFF0000) & 0xFFFFFFFF))[0]
print("bfloat16 (emulated): 1e-8 ->", f"{to_bf16(1e-8):.3e}", " 70000 ->", to_bf16(70000.0), " 1.0001 ->", to_bf16(1.0001))
print("\n== 5. Communication")
grad_bytes = 7e9 * 2
bw = 50e9
print(f"gradients of a 7B model in half precision: {grad_bytes / 1e9:.0f} GB, link {bw / 1e9:.0f} GB/s per device (assumed)")
for n in (2, 8, 64, 1024):
print(f" {n:>4} devices: ring {ring_allreduce_seconds(grad_bytes, n, bw):.3f} s, central {central_allreduce_seconds(grad_bytes, n, bw):.2f} s")
print(f" 1024 devices with 5 microseconds per step: ring {ring_allreduce_seconds(grad_bytes, 1024, bw, 5e-6):.4f} s")
print(" 1 device:", ring_allreduce_seconds(grad_bytes, 1, bw))
print("\n== 6. Pipeline bubble")
for p in (4, 8):
print(f" stages {p}: " + ", ".join(f"m={m} bubble {bubble_fraction(p, m):.3f}" for m in (1, 4, 16, 32, 64)))
print(" microbatches for a 10% bubble:", {p: microbatches_for_bubble(p, 0.10) for p in (2, 4, 8, 16)})
print(" idealised bubble at m = 4p, p = 8:", round(bubble_fraction(8, 32), 3))
print(" bubble relative to ideal compute (p-1)/m, p=8, m=32:", round(7 / 32, 3))
print("\n== 7. Activation checkpointing")
for n in (16, 100, 1000):
k = best_checkpoint_count(n)
print(f" {n:>4} layers: no checkpointing {n} units, best k {k} -> {activation_units(n, k)} units")
print(f" extra compute with backward = 2 x forward: {recompute_overhead():.3f}; with backward = 1 x forward: {recompute_overhead(1, 1):.3f}")
print("\n== 8. Data loading")
for w in (1, 2, 3, 4, 8):
st = loader_step_time(0.25, 0.9, w)
print(f" {w} workers: step {st:.3f} s, accelerator busy {0.25 / st:.0%}")
print(" fewest workers:", min_workers(0.25, 0.9))
print("\n== 9. Checkpoint interval")
write, mtbf = 3.0, 360.0
for interval in (5, 10, 30, 60, 120, 240):
print(f" every {interval:>3} min: wasted {wasted_fraction(interval, write, mtbf):.3f}")
bi = best_interval(write, mtbf)
print(f" best interval {bi:.1f} min, wasted {wasted_fraction(bi, write, mtbf):.3f}")
print("\n== 10. Compute and scaling")
print(f" 7B params on 1T tokens: {training_flops(7e9, 1e12):.2e} FLOPs")
print(f" on 1024 devices at 300 TFLOP/s peak and 40% utilisation: {training_days(training_flops(7e9, 1e12), 1024, 3e14, 0.4):.2f} days")
print(f" on 256 devices: {training_days(training_flops(7e9, 1e12), 256, 3e14, 0.4):.2f} days")
c_chin = training_flops(70e9, 1.4e12)
c_goph = training_flops(280e9, 300e9)
c_paper = 5.76e23
print(f" Chinchilla 70B x 1.4T tokens: {c_chin:.2e} FLOPs; Gopher 280B x 300B tokens: {c_goph:.2e} FLOPs")
print(f" against the paper's 5.76e+23 for Gopher: 6ND is {c_goph / c_paper - 1:+.1%} for Gopher and {c_chin / c_paper - 1:+.1%} for Chinchilla")
n, d = compute_optimal(c_chin)
print(f" compute_optimal({c_chin:.2e}): N {n:.3e}, D {d:.3e}, tokens per parameter {d / n:.0f}")
n2, d2 = compute_optimal(c_paper)
print(f" at the paper's Gopher budget {c_paper:.2e}: N {n2:.3e}, D {d2:.3e}")
print(f" tokens per parameter: Chinchilla {1.4e12 / 70e9:.0f}, Gopher {300e9 / 280e9:.2f}")
print(f" inference of a 7B model, 2N per token: {2 * 7e9:.1e} FLOPs per token")What to look for: section 1 (bytes per parameter and what each ZeRO stage leaves on a device), section 2 (the rate ramp), section 3 (accumulation matches the full batch, and the three ways to get it wrong), section 4 (how small gradients vanish and how scaling rescues them), section 5 (ring against central all-reduce as devices grow), section 6 (the bubble against stages and microbatches), section 7 (checkpointing’s memory against its extra compute), section 8 (workers against accelerator use), section 9 (the checkpoint interval), section 10 (the compute estimate and the compute-optimal split).
Output of the script as run for this lesson:
== 1. Memory: where the bytes go
1.5B: weights 3 GB, gradients 3 GB, Adam states and fp32 copy 18 GB, total 24 GB
7B: weights 14 GB, gradients 14 GB, Adam states and fp32 copy 84 GB, total 112 GB
70B: weights 140 GB, gradients 140 GB, Adam states and fp32 copy 840 GB, total 1120 GB
bytes per parameter, mixed-precision Adam: 16.0
7B model state per device, 8 devices:
stage 0: 16.00 bytes per parameter, 112.0 GB
stage 1: 5.50 bytes per parameter, 38.5 GB
stage 2: 3.75 bytes per parameter, 26.2 GB
stage 3: 2.00 bytes per parameter, 14.0 GB
7.5B model on 64 devices: [120.0, 31.4, 16.6, 1.9] GB
fits on an 80 GB device with 20 GB of activations and 4 GB overhead, 7B, 8 devices: [False, True, True, True]
fp32 weights and gradients plus Adam (4+4+8): 16.0 bytes per parameter
== 2. Batch size and learning rate
k = 32, target rate 3.20
step 0: lr 0.1000
step 1000: lr 0.7200
step 2500: lr 1.6500
step 4999: lr 3.1994
step 5000: lr 3.2000
step 9000: lr 3.2000
no warmup, step 0: 3.2
== 3. Gradient accumulation
full batch of 10: dw -28.885000 db -8.290000
micro-batches of 1: dw -28.885000 db -8.290000
micro-batches of 2: dw -28.885000 db -8.290000
micro-batches of 5: dw -28.885000 db -8.290000
micro-batches of 10: dw -28.885000 db -8.290000
micro-batches of 4 (sizes [4, 4, 2]): dw -28.885000 db -8.290000
unweighted mean of 3 chunk means: dw -35.375000
sum of 3 chunk means, no division: dw -106.125000
variance of 8 values 5.2500; mean of per-micro-batch variances: size 4 1.2500, size 2 0.2500, size 1 0.0000
== 4. Mixed precision
half precision largest value: 65504.0 65520 rounds to: inf
1.0 + 0.0001 in half precision: 1.0
100 updates of 0.0001: half-precision weight 1.0, higher-precision master weight 1.0100
gradient 1e-08 -> scale 1: 0.000e+00, scale 1024: 1.001e-08, scale 65536: 9.997e-09
gradient 3e-08 -> scale 1: 5.960e-08, scale 1024: 2.998e-08, scale 65536: 3.001e-08
gradient 1e-05 -> scale 1: 1.001e-05, scale 1024: 9.999e-06, scale 65536: 9.999e-06
gradient 2.0 at scale 65536: inf at scale 8192: 2.0
loss scale trace (growth interval 3): ok ->65536 inf->32768 ok ->32768 ok ->32768 ok ->65536 ok ->65536 ok ->65536 inf->32768 ok ->32768
bfloat16 (emulated): 1e-8 -> 1.001e-08 70000 -> 70144.0 1.0001 -> 1.0
== 5. Communication
gradients of a 7B model in half precision: 14 GB, link 50 GB/s per device (assumed)
2 devices: ring 0.280 s, central 0.56 s
8 devices: ring 0.490 s, central 3.92 s
64 devices: ring 0.551 s, central 35.28 s
1024 devices: ring 0.559 s, central 572.88 s
1024 devices with 5 microseconds per step: ring 0.5697 s
1 device: 0.0
== 6. Pipeline bubble
stages 4: m=1 bubble 0.750, m=4 bubble 0.429, m=16 bubble 0.158, m=32 bubble 0.086, m=64 bubble 0.045
stages 8: m=1 bubble 0.875, m=4 bubble 0.636, m=16 bubble 0.304, m=32 bubble 0.179, m=64 bubble 0.099
microbatches for a 10% bubble: {2: 9, 4: 27, 8: 63, 16: 135}
idealised bubble at m = 4p, p = 8: 0.179
bubble relative to ideal compute (p-1)/m, p=8, m=32: 0.219
== 7. Activation checkpointing
16 layers: no checkpointing 16 units, best k 4 -> 8 units
100 layers: no checkpointing 100 units, best k 10 -> 20 units
1000 layers: no checkpointing 1000 units, best k 28 -> 64 units
extra compute with backward = 2 x forward: 0.333; with backward = 1 x forward: 0.500
== 8. Data loading
1 workers: step 0.900 s, accelerator busy 28%
2 workers: step 0.450 s, accelerator busy 56%
3 workers: step 0.300 s, accelerator busy 83%
4 workers: step 0.250 s, accelerator busy 100%
8 workers: step 0.250 s, accelerator busy 100%
fewest workers: 4
== 9. Checkpoint interval
every 5 min: wasted 0.607
every 10 min: wasted 0.314
every 30 min: wasted 0.142
every 60 min: wasted 0.133
every 120 min: wasted 0.192
every 240 min: wasted 0.346
best interval 46.5 min, wasted 0.129
== 10. Compute and scaling
7B params on 1T tokens: 4.20e+22 FLOPs
on 1024 devices at 300 TFLOP/s peak and 40% utilisation: 3.96 days
on 256 devices: 15.82 days
Chinchilla 70B x 1.4T tokens: 5.88e+23 FLOPs; Gopher 280B x 300B tokens: 5.04e+23 FLOPs
against the paper's 5.76e+23 for Gopher: 6ND is -12.5% for Gopher and +2.1% for Chinchilla
compute_optimal(5.88e+23): N 7.000e+10, D 1.400e+12, tokens per parameter 20
at the paper's Gopher budget 5.76e+23: N 6.928e+10, D 1.386e+12
tokens per parameter: Chinchilla 20, Gopher 1.07
inference of a 7B model, 2N per token: 1.4e+10 FLOPs per tokenReal-World Application
A sound recipe for a new training job: write the memory budget first (16 bytes per parameter with mixed-precision Adam, plus an activation estimate at your batch and sequence length) and decide the smallest number of devices that holds it. Use data parallelism while the state fits, sharded data parallelism (FSDP or ZeRO) when it does not, and add tensor or pipeline parallelism only for the largest models. Train in bf16 where your hardware supports it, keep fp32 master weights, and use dynamic loss scaling if you train in fp16. Scale the learning rate with the batch, add warmup, and re-tune. Turn on activation checkpointing when activations are the limit and accept about a third more compute. Measure accelerator utilisation before adding hardware: fix the data loader and communication overlap first. Checkpoint on a schedule you computed from write time and failure rate, test a resume before the long run, and log the config, code version, seed and data order. Finally, estimate cost with and say the assumptions out loud.
Interview Perspective
Expect “how much memory does it take to train a 7B model with Adam?”, “DDP versus FSDP”, “why does mixed precision need loss scaling and master weights?”, “what is gradient accumulation and what can go wrong?”, “what is the pipeline bubble?”, “how would you estimate the cost of training this model?”, and “how do you scale the learning rate with the batch size?”. A strong answer gives the number with its assumptions (16 bytes per parameter, before activations), names the communication cost of each option, and says what breaks (overflow, a short last micro-batch, BN statistics, the bubble). A weak answer names a library and stops.
Provenance: Common industry pattern. These are standard distributed-training topics for applied ML and ML infrastructure roles, not a verified list for any named company.
Practice Questions
- Basic (Common industry pattern): List what a training step keeps in memory and compute the model-state memory of a 3B-parameter model trained with mixed-precision Adam.
- Basic (Common industry pattern): What does gradient accumulation do, and why does it give the same gradient as a larger batch?
- Intermediate (Common industry pattern): Why does fp16 training need loss scaling and an fp32 master copy of the weights? What does bf16 change?
- Intermediate (Common industry pattern): Compare DDP, ZeRO stages 1 to 3 and FSDP. What do you save, and what do you pay in communication?
- Intermediate (Generated practice): You double the global batch from 1,024 to 2,048 on the same model. What do you change in the learning-rate schedule and what do you watch for?
- Intermediate (Generated practice): A pipeline has 8 stages. How many microbatches keep the bubble under 10%, and why can you not just use more?
- Advanced (Common industry pattern): Training is out of memory at batch 8 with plenty of spare compute. Give three fixes in order and the cost of each.
- Advanced (Generated practice): Accelerator utilisation is 40%. List the places you would look, and one measurement for each.
- Product-Company (Generated practice): You have a fixed budget of FLOPs. How do you choose model size and token count, and what would change your answer if the model will be served to millions of users?
Activity
Run the script, then change four things. In section 1, change the model to 13B parameters and 16 devices and find which ZeRO stages fit an 80 GB device with 30 GB of activations. In section 3, set micro = 3 and predict, before running, whether the unweighted mean of chunk means is larger or smaller in size than the true gradient, then check it against the printed values. In section 6, find the number of microbatches that keeps a 6-stage pipeline under a 5% bubble using the function, then check it by hand with . In section 9, change the mean time between failures from 360 to 60 minutes and describe how the best checkpoint interval and the lost share move. Then write the memory budget, the parallelism choice and the cost estimate for fine-tuning a 7B model on 8 devices in five sentences.
Homework
Build the training-at-scale calculator with the standard library only: bytes per parameter by ZeRO stage, model-state memory and a fit check, the linear-scaling learning rate with warmup, a gradient-accumulation routine that equals the full-batch gradient, micro-batch variance, half-precision rounding with loss-scaled gradients and a dynamic loss scale, ring and central all-reduce times, the pipeline bubble, activation-checkpointing units, data-loader step time, the checkpoint interval, and the compute and days estimate. The code is in homework/; run the tests until they pass.
Quick Revision
- Memory per parameter with mixed-precision Adam: 2 (weights) + 2 (gradients) + 12 (fp32 copy and two moments) = 16 bytes, before activations. 1.5B parameters: 24 GB. 7B: 112 GB. 70B: 1,120 GB.
- ZeRO partitions optimizer states (stage 1), then gradients (stage 2), then weights (stage 3). 7B on 8 devices: 112, 38.5, 26.2 and 14.0 GB per device. FSDP
FULL_SHARDis the stage-3 analogue; sharding costs communication. - Linear scaling: batch times , learning rate times , with gradual warmup. In the ImageNet study the rule held to 8,192 and degraded after. Beyond the critical batch size, more data per step buys little.
- Gradient accumulation: sum gradients over micro-batches, divide by the total sample count once, weight a short last chunk by its size. For token losses divide by the total non-padding tokens of the effective batch. Batch norm statistics still come from the micro-batch.
- Mixed precision: fp32 master weights (small updates survive: 1.0100 against 1.0), loss scaling (a gradient of is lost at scale 1 and kept at 1,024), dynamic scale (halve on overflow, double after a clean run). bf16 has fp32’s range and less precision.
- DDP averages gradients with bucketed all-reduce overlapped with backward. Ring all-reduce time is about whatever is (0.49 s at 8 devices, 0.559 s at 1,024 for 14 GB at 50 GB/s). Tensor parallelism inside a server, pipeline across servers.
- Pipeline bubble : 8 stages need 63 microbatches for 10%. More stages need a bigger batch.
- Checkpointing activations: peak about units, best near (100 layers: 100 to 20 units), for about one extra forward pass (a third more compute if backward is twice forward).
- Loader: step time . Checkpoint interval about . Reproducibility means repeatable experiments, not bit-identical runs.
- Compute (7B on 1T tokens: FLOPs, 3.96 days on 1,024 devices under stated assumptions). Compute-optimal training scales model and tokens together; Chinchilla used 20 tokens per parameter, one result and not a law. Against the paper’s 5.76e23 for Gopher, 6ND is 12.5% low for Gopher and 2.1% high for Chinchilla.
Check yourself
- Walk-through: Without notes, compute the training memory for a 13B model with mixed-precision Adam on 16 devices under each ZeRO stage, say which stage fits an 80 GB device with 30 GB of activations, and state the communication cost you accept.
- Variation: The same job, but you must train in fp16 on hardware without bf16 and the global batch is 8 times larger. Say what you add (loss scaling, warmup, a re-tuned rate) and what you monitor.
- Common misconception: “More GPUs always make training faster”, “gradient accumulation is free and exactly the same as a bigger batch for every layer”, and “loss scaling changes the learning rate”.
Resources & Further Reading
Checked sources to go deeper. The essential ones come first in each group.
Official documentation
FullyShardedDataParallel (opens in a new tab)
The sharding strategies as an API, and the limitations to know before you use them.
Distributed Data Parallel (developer notes) (opens in a new tab)
How data parallelism works internally, including bucketing and overlap.
torch.utils.checkpoint (opens in a new tab)
The API for activation checkpointing and its randomness caveats.
Research papers
ZeRO: Memory Optimizations Toward Training Trillion Parameter Models (opens in a new tab)Essential
The clearest accounting of where training memory goes, and the stages of sharding.
Mixed Precision Training (opens in a new tab)Essential
Why fp16 training needs master weights and loss scaling, with the evidence.
Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour (opens in a new tab)Essential
The practical recipe for scaling batch size, including warmup and the batch norm detail.
Training Compute-Optimal Large Language Models (opens in a new tab)
The compute-optimal view and the Chinchilla experiment.
Scaling Laws for Neural Language Models (opens in a new tab)
The original power-law scaling results and the critical batch size.
Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM (opens in a new tab)
How tensor, pipeline and data parallelism combine on a real cluster, with measured trade-offs.
GPipe: Easy Scaling with Micro-Batch Pipeline Parallelism (opens in a new tab)
The pipeline design and the bubble overhead.
Training Deep Nets with Sublinear Memory Cost (opens in a new tab)
The original treatment of recomputation for memory.
Tensor parallelism for transformers.
More for this module: ML systems and interviews resources
Practice
Test what you just read. Quizzes and cards are grouped by module: ML systems and interviews.
Check yourself24 questions on what this lesson set out to teach
Checking answers needs JavaScript. You can still read every question and option below.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.