Skip to content

Distributed Training: FSDP, Memory Lifetimes and Communication

13 min reading

Account for replicated and sharded training state, transient peaks and collective timing without treating payload floors as capacity guarantees.

Page details

GenAI · Advanced study · 5 / Depth

Sources · 13 min reading · 28 min with practice

Published · Last edited:

More
20px

Progress is saved in this browser when storage is available.

View guided paths and progress

Know first: High-throughput gateway: tiered caches, balancing, failure and GPU autoscaling. Optional help: GenAI foundations.

Optional background references

Which state lives at the training-memory peak?

Hypothetical scenario. Northwind’s dataset has explicit lineage and splits. Dev starts an adaptation run on a model that already serves successfully, but the backward pass exhausts memory. Maya asks why fitting the weights was insufficient; Priya asks which training state actually caused the peak.

Maya: “The model answers questions here. What changed when training began?”

Dev: “The step needs more than the inference weight allocation.”

Priya: “Inventory persistent and transient state before choosing replication, sharding or recomputation.”

This optional depth chapter assumes adaptation, memory accounting and the distinction between replicas and model partitions. You will follow training-state lifetimes, FSDP sharding and activation checkpointing while separating a memory floor from peak allocation and communication cost.

Inference and training have different memory lifetimes. Training may retain activations for derivatives, store parameter gradients and maintain optimizer state. Precision policy can introduce additional representations of parameters. The weight file alone therefore does not describe a training allocation. Begin with an inventory of persistent and transient state, then choose a distribution strategy for the part that exceeds capacity.

Data parallelism distributes examples while retaining replicas

In a selected replicated data-parallel setup, each worker has a model replica and processes a different local batch. Workers combine gradient information so updates implement the intended global objective. Replicating a model across more workers does not divide its persistent parameter storage on each worker. It can increase aggregate training throughput while leaving an individual worker's model-state problem unresolved.

Define the global batch carefully. If four workers each process two examples per microbatch and accumulate four microbatches before an optimizer step, the selected global count is 4 × 2 × 4 = 32 examples per update. Token counts and scored positions can still differ among examples, so specify the loss normalization rather than assuming equal example counts mean equal objective weighting.

Gradient accumulation postpones the optimizer update while accumulating contributions from several microbatches. It can reduce the activations needed at one time relative to a larger simultaneous batch. It does not by itself shard model parameters or optimizer state. Changes to numerical precision and reduction order can also affect the exact numerical result.

Model training memory as a timeline of live state

Hypothetical scenario. A sharded trainer holds partitioned parameters, gradients and optimizer state but temporarily materializes additional tensors for computation. Dividing persistent bytes by device count cannot establish the peak.

Model training memory as a timeline of live state
ArtifactConcrete evidenceDecision boundary
Persistent stateshard identities and optimizer configMemory floor
Transient statematerialized params, activations, collectivesPeak timeline
Checkpointmodel/optimizer/data progress/configCoherent restart
Temporary live tensors: Persistent shards → Materialize + compute.Temporary live tensors: Persistent shards → Materialize + compute. Persistent shards to Materialize + compute: temporary live tensors; Materialize + compute to Reduce / release: configuration-specific communication.Persistent shardsMaterialize +computeReduce / releasetemporary live tensorsconfiguration-specific communication
Temporary live tensors: Persistent shards → Materialize + compute. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

Record when all-gathers, backward work, gradient reduction and optimizer updates overlap under the actual FSDP configuration. A selected toy device with 4 GB persistent state, 3 GB materialized parameters and 2 GB activations has a simultaneous subtotal of 4 + 3 + 2 = 9 GB before other overhead. If lifetimes do not overlap, summing their maxima overstates that subtotal; if additional buffers overlap, it understates the actual peak. Checkpoint recovery also needs compatible optimizer, data-progress and random-state evidence.

Sharding distributes state and introduces collective work

Fully sharded data parallelism, or FSDP, partitions model state across workers. When a wrapped computation needs a parameter group, workers gather its required representation; after gradient computation, collective operations distribute the resulting gradient information. The grouping and scheduling determine how much is materialized at once and how communication overlaps computation.

The PyTorch FSDP2 tutorial is a primary reference for its sharding and communication model. Its implementation details should be checked against the deployed version. This chapter uses a declared toy accounting model rather than promising that every FSDP configuration has identical storage or timing behavior.

Sharding is not tensor parallelism. Tensor parallelism divides operations within model layers; pipeline parallelism places stages on different workers. A real training system can combine methods, but each adds a different scheduling and communication relationship. Select them because of a measured constraint, not because additional parallelism necessarily improves efficiency.

Calculate a persistent-state floor before adding the peak

Hypothetical scenario. Choose one billion trainable parameters. Assume two bytes per stored model parameter, two bytes per gradient, four bytes for a master parameter copy and two four-byte optimizer moments. This chosen mixed-precision accounting totals 2 + 2 + 4 + 4 + 4 = 16 bytes per parameter.

The selected persistent state is 1,000,000,000 × 16 = 16,000,000,000 bytes. Dividing by 1,073,741,824 gives approximately 14.90 GiB. Four replicated workers each still require that selected persistent state before activations and buffers. Four ideally balanced shards instead store a selected floor of 16,000,000,000 / 4 = 4,000,000,000 bytes, approximately 3.73 GiB per worker.

Now add assumed per-worker allocations: 3 GiB of activations, 1 GiB of simultaneously materialized parameter groups and 0.5 GiB of other working buffers. The illustrative total is 3.73 + 3 + 1 + 0.5 = 8.23 GiB, using rounded components. This selected allocation does not fit an 8 GiB worker even though the persistent shard alone does.

These values are a transparent example, not a framework specification. Actual optimizers can use different state, precision and offloading. Allocator reservations and fragmentation need inspection too. Count logical payload and measured allocation separately, and retain headroom appropriate to the actual workload instead of treating a rounded estimate as a capacity guarantee.

Persistent shards are smaller than the temporary training allocationFour workers retain different state shards. A collective exchange materializes a parameter group for computation. Each worker also needs activation and working memory, so the shard payload is only one part of the training peak.State shard 1State shard 2State shard 3State shard 4Gather needed parameter groupplus activations and working buffers

Activation checkpointing exchanges memory for recomputation

Instead of retaining every intermediate activation, checkpointing keeps selected values and recomputes omitted intermediates during backward processing. This can reduce one part of the peak while adding computation and changing scheduling. It does not make optimizer moments disappear or remove the need for parameter communication.

Choose checkpoints with the actual model graph in mind. A useful reduction depends on which tensors dominate the retained state and how expensive their reconstruction is. Inspect whether the new bottleneck becomes computation, communication or another transient allocation. Combining sharding and checkpointing can help, but their effects are not obtained by adding two unrelated advertised percentages.

A faster memory plan can still be a slower training plan

Choose a hypothetical collective transfer moving 2 GiB through a bottleneck whose effective useful bandwidth is 20 GiB per second. A simple payload-only lower bound is 2 / 20 = 0.1 seconds. If useful local computation takes 0.15 seconds and none of that transfer overlaps, the selected total is at least 0.25 seconds before other overhead.

If the transfer overlaps perfectly with that computation, the simplified bound becomes max(0.1, 0.15) = 0.15 seconds. Actual collective topology, contention, synchronization and launch behavior can prevent perfect overlap. These bounds explain what to measure; they are not benchmark results or evidence of linear speedup.

More workers can reduce shard payload while increasing coordination and changing communication volume. Small parameter groups can introduce many operations; large groups can raise materialization peaks. Measure step time and peak allocation together. A configuration that fits but spends most of its time waiting may be a useful feasibility step without being an efficient final design.

Synchronous workers advance at the pace of their dependencies

Variable-length sequences can create different amounts of useful work even with equal example counts. A slow worker or uneven batch can delay a collective that others need. Record sequence lengths, data-loading waits and communication timing before attributing every stall to the accelerator model.

Loss normalization also matters when scored token counts differ. Averaging each worker's local mean equally is not generally equivalent to a mean over all scored tokens when workers contribute different token counts. Specify the intended objective and scaling. A faster run that changes the training objective is a different experiment, not an uncomplicated speed improvement.

In the wild: a documented sharding implementation

The PyTorch FSDP2 tutorial describes distributed parameter handling and the collectives used around computation. It is a concrete implementation of state sharding rather than a claim that Northwind or the author ran a large training cluster. Use the primary documentation to check version-specific behavior and the toy ledger to identify which allocations still need measurement.

Hypothetical scenario. A team sizes workers using persistent shards only. The job fails during the first large parameter gather while other allocations remain live. The corrective action is to inspect materialization and activation lifetimes, adjust grouping or batch shape, and rerun the complete peak measurement. Adding workers without examining the peak might preserve the same failure.

A checkpoint must describe the state needed to resume

Saving model weights alone can be enough for some inference exports but is not a complete training-resume contract. Resuming the same optimization process can require optimizer and scheduler state, random-state information, data position and the configuration needed to interpret shards. Decide which continuity claim the checkpoint is intended to support.

Check artifact completeness and compatible loading before an extended run depends on recovery. A checkpoint's storage layout can differ from its in-memory training layout. Changing worker count or parallelism may require a supported resharding process. Preserve an evaluated inference export separately from a training-resume artifact rather than using one ambiguous label for both.

Use distribution when its resource trade is justified

State sharding is useful when persistent model state is a limiting allocation and communication capacity can support the needed exchanges. A small adapter workload may be dominated by frozen-base storage or activations instead. Offloading can move pressure to host memory and transfer paths; it does not eliminate the work. Profile the actual trainable set before choosing the design.

The decision should include failure recovery, data availability and operational effort alongside accelerator count. Distributed training has more participants that must agree on state and progress. A smaller model, shorter input or narrower adaptation objective may meet the task with a simpler operating burden.

For an adapter-only run, recompute the ledger with the actual frozen and trainable components. Applying the full-parameter optimizer formula to every frozen parameter overstates one allocation, while ignoring the frozen base understates another. Keep the accounting explicit enough that a different precision or optimizer policy can replace a component without changing the rest of the argument.

Test the persistent state boundary

Recovery keeps the original contract: compatible full state.Recovery keeps the original contract: compatible full state. Checkpoint artifacts to Restart configuration: compatible full state; Restart configuration to Resumed data progress: avoid silent skip / duplicate training data.Checkpoint artifactsRestartconfigurationResumed dataprogresscompatible full stateavoid silent skip / duplicate training data
Recovery keeps the original contract: compatible full state. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

The persistent floor fits but training runs out of memory during backward. Which model should change?

Reveal the design reasoning

The lifetime/overlap model. Inspect materialized parameters, activations, communication buffers and prefetch configuration at the peak. Do not infer fit from shard bytes alone.

Decision: Validate peak lifetime and communication cost with the selected training topology.

Find the allocation and coordination assumptions

Four-way sharding gives a 3.73 GiB persistent floor. Is an 8 GiB worker sufficient?

Not from that floor alone. The example adds 3 GiB of activations, 1 GiB of materialized parameters and 0.5 GiB of buffers, reaching about 8.23 GiB. Inspect the actual peak and allocator behavior rather than approving capacity from the shard payload.

Does gradient accumulation divide optimizer state across workers?

No. It combines microbatch contributions before an update and can change activation pressure. Sharding is the separate choice that distributes persistent state. Account for both mechanisms without treating them as interchangeable.

A 2 GiB transfer at 20 GiB/s overlaps 0.15 seconds of compute. Is the step guaranteed to take 0.15 seconds?

No. That is a simplified perfect-overlap bound. Topology, synchronization and other allocations can add delay. With no overlap the selected payload-plus-compute bound is 0.25 seconds, before additional overhead.

Northwind decision log

  1. Separate persistent training state from activation and materialization peaks.
  2. Compare sharding choices using both allocation and collective timing.
  3. Specify the global objective and test a complete training-resume artifact.

Go deeper: what the backward pass needs

Northwind can inspect whether an adaptation run is feasible without inferring quality from successful execution. Page 53 returns to behavior: use evaluation and labeling prerequisites to examine which harms, refusals and contextual mistakes the resulting system should be tested against.