advanced28 min studyLesson 545 in Engineering

Optimizer-state sharding: assign update ownership explicitly

Calculate persistent state savings while preserving parameter identity, optimizer state, and post-update replica synchronization.

On this page

What you’ll understand

  • Separate parameters, gradients, master weights, and moment storage.
  • Explain how owners update a subset while replicas recover a consistent parameter view.
  • Calculate an ideal stage-one memory budget with explicit precision assumptions.

Replicated data parallelism can keep several copies of every optimizer moment even though every copy follows the same update. Optimizer-state sharding removes that redundancy by assigning state and update responsibility to owners. ZeRO stage one provides the architectural idea; PyTorch 2.9 ZeroRedundancyOptimizer and DeepSpeed v0.18.2 expose particular implementations with their own contracts. The memory arithmetic below is a hypothetical precision layout, not a universal bytes-per-parameter promise for every optimizer or framework configuration.

Inventory state before dividing it

Separate the low-precision model parameters used for compute, the stored gradients, any full-precision master parameter copy, and optimizer moments. Whether these allocations exist, share storage, or change precision depends on the implementation. An illustrative mixed-precision Adam-style layout uses two bytes for the compute parameter, two for its gradient, and twelve for a four-byte master parameter plus two four-byte moments. Activations, communication buffers, allocator reservations, and temporary kernels are not included. A different layout needs a different inventory rather than the same memorized multiplier.

Stage-one reasoning partitions optimizer-owned state while leaving the compute parameters and, in the basic model here, gradients replicated. Each owner receives the intended synchronized gradient for its assigned parameters and advances the associated optimizer state. Updated parameters then become available consistently to all replicas before their next use. PyTorch’s documented ZeroRedundancyOptimizer broadcasts owner-updated parameters; that specific mechanism should not be confused with a claim that every sharded optimizer uses the same communication schedule or splits every tensor into equal pieces.

Mreplicated=16N,Mstage1≈4N+12NWM_{\rm replicated}=16N,\qquad M_{\rm stage1}\approx4N+\frac{12N}{W}
Under the explicitly hypothetical 2-byte compute parameter, 2-byte gradient, and 12-byte optimizer-owned state layout, N is parameter count and W positive balanced owners. Results are bytes per rank, excluding all non-model-state and transient allocations. Padding and imperfect partitioning can alter the approximation.↔ Scroll wide equations horizontally.

Ownership must preserve parameter and optimizer identity

A partition map associates each parameter or parameter slice with the right state, hyperparameter group, and checkpoint identity. The map cannot be reconstructed safely by assuming that rank order equals module traversal order. PyTorch’s pinned ZeroRedundancyOptimizer description uses a sorted-greedy packing of whole parameters, so one large tensor can limit balance; the round-robin scalar map used below is only a teaching model. Tied parameters and parameter groups need deliberate handling so that one logical state is neither duplicated inconsistently nor updated twice.

State sharding is mathematically straightforward for coordinatewise optimizer state only after all global operations are specified. Global gradient clipping requires the norm of the intended full gradient, and any optimizer rule coupling coordinates needs its corresponding distributed operation. Learning-rate schedules, step counters, overflow decisions, and decoupled weight decay must also match the reference update. A state-memory reduction does not authorize different update frequency. Inspect multiple steps, since freshly initialized moments can hide a missing-state restoration bug on the first step.

owner⁡(i)=i mod W\operatorname{owner}(i)=i\bmod W
This illustrative balanced scalar-index map applies to integer parameter indices i≥0 and positive integer owner count W. It is not the actual tensor-packing algorithm of PyTorch ZeroRedundancyOptimizer or a complete checkpoint layout.↔ Scroll wide equations horizontally.

Account for communication and checkpoint reconstruction

After local owners update their state, future computation needs the correct updated parameter values. Communication and any required synchronization therefore move rather than disappear. Checkpoint operations may consolidate or repartition state and can have very different peak memory from steady training; all required ranks must participate according to the API. Construct the optimizer against the wrapper’s supported parameter representation and retain a canonical logical mapping for tests and restoration. A checkpoint containing only one owner’s local state is not automatically a complete training checkpoint.

The modular lab makes one ownership-enumeration pitfall visible. Reset, explicitly set modulus four and additive step one, predict the residues over four Steps, then Step four times to visit 1,2,3,0 from the initial zero. For a fresh comparison Reset and explicitly set modulus four and step two before predicting and stepping: only zero and two are visited. This deterministic orbit is not a sharded optimizer; it illustrates how a stride that is not coprime can fail to enumerate every owner in a proposed toy traversal.

A stage-one inventory reduces persistent state, not every byte

Assume one billion parameters, four perfectly balanced owners, and exactly the illustrative 16-byte replicated layout. Use decimal gigabytes and exclude activations, temporary buffers, and allocator overhead.

  1. A fully replicated worker stores 16×10⁹ bytes, or 16 GB, of the listed model state. The two-byte parameter and two-byte gradient together contribute four GB.

  2. The optimizer-owned twelve GB is divided among four owners, leaving three GB per rank under perfect balance. Adding the unchanged four GB gives seven GB per rank.

  3. The reduction is nine GB per rank for this inventory. It is not a fourfold reduction of all training memory: parameters and gradients remain replicated here, and excluded activations and communication transients can dominate a real peak.

The result

The hypothetical persistent state falls from 16 to seven decimal GB per rank. Validate the actual precision, ownership balance, and transient allocations before sizing hardware.

Explore the model

Interactive lab

Interactive lab · modular

A toy owner traversal must reach every residue

For independent runs use Reset → explicitly set BOTH modulus and step → predict → Step. At m=4,a=1 the orbit visits all four residues; at m=4,a=2 it visits only two. Four Steps advance four additions. This is not PyTorch’s packing algorithm, an optimizer, or a checkpoint simulator.

A toy owner traversal must reach every residueAddition modulo m starts at zero: rₙ = na mod m. Playback advances two additions per second. The orbit has period m/gcd(m,a), including period one for a = 0. This is not a cryptographic security test or a primality algorithm. Current readings: Residue r0: 0; Orbit period · m/gcd(m,a): 12; Distinct residues visited: 1 of 12. All parameters are adjustable with the labeled controls below.Repeated addition modulo 12: the current residue is 0, and the orbit period is 12.01234567891011+ 5mod 12An additive orbitn = 0rₙ = 0Period = 12Cycle starts at 0:0 → 5 → 10 → 3 →8 → 1 → 6 → 11 →4 → 9 → 2 → 7 → 0Exact residues · two additions per second
Additive orbitCurrent residue / next edge
Residue r0
0
Orbit period · m/gcd(m,a)
12
Distinct residues visited
1 of 12
t = 0 s

Addition modulo m starts at zero: rₙ = na mod m. Playback advances two additions per second. The orbit has period m/gcd(m,a), including period one for a = 0. This is not a cryptographic security test or a primality algorithm. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forAn explicit mapping and complete ownership coverage are prerequisites for interpreting state savings.

Check your understanding

Under the stated stage-one model, which state is still replicated?

Try it yourself

Use the same precision inventory for two billion parameters and eight perfectly balanced owners. Calculate replicated and stage-one state per rank in decimal GB. Why might whole-tensor packing exceed the ideal owner share?

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Keep the replicated four bytes per parameter separate from the twelve sharded bytes per parameter.

Compare with the solution

Replicated state is 32 GB. The compute parameters plus gradients occupy eight GB per rank, while optimizer-owned state contributes 24/8=3 GB, giving an ideal eleven GB. Whole-tensor packing may be imbalanced when a large parameter cannot be split by that implementation’s partitioning rule. Padding, actual precision choices, activations, buffers, and allocator state are additional costs. Measure ownership and live allocations rather than interpret eleven GB as a complete guaranteed device-memory requirement.

Take it with you

  • Inventory actual precision and storage before applying a sharding factor.
  • Preserve logical parameter ownership and the exact optimizer update.
  • Budget communication and checkpoint peaks separately from steady optimizer state.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.