AlgoViz

Parallel training, memory and recovery

hard 6 min

Each device needs some combination of weights, gradients, optimizer state, activations and temporary communication buffers.

Video lesson · Chapter 1 of 4

Four machines, one training step

0:00 / 3:18

Theory

Read or listen first. About 2 min.

What it is

Each device needs some combination of weights, gradients, optimizer state, activations and temporary communication buffers. Data parallel workers process different examples and aggregate gradients. Sharding can partition model state across workers. Tensor parallelism splits operations within a layer, pipeline parallelism partitions layers, and expert parallelism dispatches tokens to the devices hosting selected experts.

Why it exists

Choose a partition by measuring the dominant constraint. Sharding a large optimizer state can trade memory for all-gathers. Splitting a single layer can place a collective on the critical path of every layer. A pipeline can leave devices idle while its first or last microbatch travels. A distributed checkpoint must represent one consistent training step across all shards.

Fit a training step across four accelerators

Microbatch loader → Sharded state (microbatches). Sharded state → Gradient exchange (layer gradients). Gradient exchange → Sharded state (updated shards). Gradient exchange → Commit manifest (consistent step)
Microbatch loader → Sharded state (microbatches). Sharded state → Gradient exchange (layer gradients). Gradient exchange → Sharded state (updated shards). Gradient exchange → Commit manifest (consistent step)

Inside this chapter

Chapter sources
Sharding and collectives
Full sharding keeps partitions of persistent state and temporarily materializes parameters for computation. Peak memory includes activations and communication buffers even if a simple division gives a small steady-state number.

With mixed precision and an Adam-style optimiser, persistent state is often around 16 bytes per parameter: 16-bit weights and gradients plus 32-bit master weights and two moment estimates. Full sharding splits all of that across ranks and reassembles each layer's weights just before use, then frees them. The steady-state division is easy; the peak is what fails, because gathered layers, activations, prefetch buffers and allocator fragmentation sit on top of the shard.

Example. Sharding 80 GiB of persistent state over four balanced ranks gives 20 GiB per rank before gathered weights and temporary allocations.

Another example. A 5-billion-parameter model at about 16 bytes per parameter needs roughly 80 GB of persistent state. Over 8 ranks that is about 10 GB each before any activations.

Fully sharded step for one layer

Steady state is the shard; peak is the shard plus gathered weights, activations and communication buffers.
Pipeline and expert imbalance
Microbatches help overlap stages, yet the slowest stage limits steady-state throughput. An expert router sending too many tokens to one expert creates an uneven workload and extra cross-device traffic.

Any synchronised step, whether a pipeline stage boundary or a gradient all-reduce, runs at the pace of its slowest participant. In pipelines, uneven layer splits create a slow stage; in expert parallelism, a router that sends many tokens to one expert overloads the device that hosts it and adds cross-device traffic. Per-worker timing and per-expert token counts reveal it; averages hide it.

Example. Three workers finish in 12 ms and a fourth takes 30 ms. A synchronized step waits for the fourth even though mean utilization looks acceptable.

A synchronised step waits for the slowest worker

WorkerCompute timeWaitingBusy share of step
112 ms18 ms40%
212 ms18 ms40%
312 ms18 ms40%
430 ms0 ms100%
Step30 msmean compute 16.5 ms45% overall
The mean looks fine; the step time is set by worker 4.
Failure recovery
Commit a checkpoint manifest only when all required shards and training metadata have been written. On restart, restore one coherent step and verify the data cursor. Mixing shards from adjacent steps can silently corrupt the resumed run.

Writing a sharded checkpoint takes time and can be interrupted, leaving some shards from the new step and some from the old. Loading such a mix produces a model whose layers disagree, often with no immediate error. The fix is a commit protocol: write every shard plus optimiser and data-loader state, verify them, then write a small manifest that marks the step complete. On restart, load the newest step with a manifest and confirm the data cursor matches it.

Example. A failed worker leaves three of four shards at step 901. Restore all four from committed step 900.

Only committed steps are restorable

The manifest is written last. Without it, a step does not exist as far as recovery is concerned.
Data, tensor and pipeline parallelism
Data parallelism splits examples across workers, tensor parallelism splits the matrices inside a layer, and pipeline parallelism assigns groups of layers to different devices. Large runs combine them.

Each axis trades memory for communication in a different place. Tensor parallelism talks inside every layer, so it is kept within a server; pipelines talk only at stage boundaries, so they tolerate slower links but waste time filling and draining; data parallelism talks once per step. Choosing the layout is mostly about matching these patterns to the network.

Example. A run uses tensor parallelism within each 8-GPU server, pipeline stages across servers, and data parallelism across copies of that arrangement.

What each axis splits and what it costs

AxisWhat is splitMain communicationTypical limit
Dataexamples in the batchgradient all-reduce each stepevery worker needs the full model unless sharded
Tensormatrices within a layerfrequent exchanges inside each layerneeds very fast links, usually one server
Pipelineconsecutive layersactivations between stagesidle bubbles and stage imbalance
Expertexperts of MoE layerstoken dispatch and returnrouting skew
Place the most communication-heavy axis on the fastest links.
Activation checkpointing
Instead of storing every intermediate activation for the backward pass, store only some and recompute the rest when needed. It trades extra compute for a large cut in activation memory.

Activations, not weights, often dominate memory for long sequences, because they scale with batch times sequence length times width per layer. Checkpointing every block is the common default; checkpointing selectively, only the most memory-hungry parts, recovers some speed. Profile peak memory before and after to confirm it moved the real bottleneck.

Example. Saving only each block's input and recomputing the inside during backward lets a longer sequence fit, at the price of roughly one extra forward pass.

Store a little, recompute the rest
  1. 1Forward passkeep only block inputs
  2. 2Discard internalsattention and MLP intermediates freed
  3. 3Backward reaches blockneeds those intermediates
  4. 4Recompute block forwardfrom the saved input
  5. 5Compute gradientsthen free again

Peak activation memory falls sharply; step time rises by the recomputation cost.

How it works

Step through the idea, or press Play.

Step 1 of 4

Microbatch loader. Dispatch different samples

Understand it

Worked example

Fit a training step across four accelerators

  1. 1

    Dispatch different samples

    Four workers receive input slices according to the data-parallel plan.

  2. 2

    Materialize the current layer

    Each worker contributes its partition and holds transient buffers needed for computation.

  3. 3

    Synchronize one optimizer step

    Measure collective time and identify an imbalanced expert or slow link before increasing the batch.

  4. 4

    Step 900 is recoverable

    Publish only after all shards and optimizer metadata are present. Ignore the incomplete later generation after restart.

Follow the handoffs

Choose a partition by measuring the dominant constraint. Sharding a large optimizer state can trade memory for all-gathers. Splitting a single layer can place a collective on the critical path of every layer. A pipeline can leave devices idle while its first or last microbatch travels. A distributed checkpoint must represent one consistent training step across all shards.

Why 80 GiB over four 24 GiB devices can still fail

Item per rankIllustrative sizeRunning total
Persistent shard (80 / 4)20 GiB20 GiB
Gathered weights for the current layer2 GiB22 GiB
Activations for the microbatch3 GiB25 GiB
Communication buffers and fragmentation1 GiB26 GiB, over 24
Illustrative values. Smaller microbatches, activation checkpointing or more ranks bring the peak back under the limit.

Summary

The whole topic in one minute.

The steady-state partition alone does not bound the peak during a training step.

Choose a partition by measuring the dominant constraint. Sharding a large optimizer state can trade memory for all-gathers. Splitting a single layer can place a collective on the critical path of every layer. A pipeline can leave devices idle while its first or last microbatch travels. A distributed checkpoint must represent one consistent training step across all shards.

Sources