Unit 3 of 12 · about 6 hours · explain, implement

Parameter all-gather before compute and gradient reduce-scatter after backward

Correct ownership is not enough if weights are absent when autograd uses them. This unit makes the parameter and gradient lifecycle explicit before adding scheduling optimizations.

You'll be able to

  • Implement gather-before-use, release-after-use and reduced-gradient ownership in a tiny fully sharded trainer.
  • Match gradients and parameter updates to an unsharded oracle with the same global batch and loss normalization.
  • Explain when backward needs a full weight and when the optimizer needs only a shard.

Covers

Parameter all-gather before computationGradient reduce-scatter after backward
1

Read

In this order, only the parts listed

0 of 2 done

  1. The current FSDP lifecyclePyTorch FSDP2 Tutorial (fully_shard)

    How FSDP2 works and How to use FSDP2 / Model Initialization (page read 2026-10-14)

  2. Build fully sharded trainingCS336 Assignment 2 (Spring 2026) - Sections 6, 7 and 8.3

    Section 7, problem fsdp, printed pp. 38 to 39; Section 8.3, equations (34) to (44), pp. 42 to 43

    Implement and test the CPU Gloo path first. Leave GPU profiling in fsdp_accounting to the peak-memory unit. The handout's FP32 master-weight prescription is its implementation contract, not a theorem forbidding other training formats.

2

Focus on

  • For a sharded linear layer, gather the full compute weight before forward. If released afterward, gather it again before backward computes input gradients. Reducing weight gradients does not replace that second gather.
  • Reduce-scatter combines contributions from all data ranks and gives each owner its reduced gradient slice. For equal local mean losses, divide the summed gradient by the data-parallel degree exactly once.
  • Resharding parameters normally means freeing the gathered representation and re-registering the stored shard. It is not another scatter collective.
  • The assignment shards Linear and Embedding weights and keeps norms replicated. Replicated parameters still need gradient synchronization. Build the optimizer against the parameters it must update.
Common mistakes · 3
  • Freeing a tensor still needed by autograd. The hook schedule and saved-tensor lifetime must agree; swapping storage blindly can corrupt backward.
  • Reducing only sharded weights while silently leaving replicated normalization gradients local.
  • Comparing each rank's local mean loss with the global mean and calling their difference an FSDP error. Reduce the metric separately.
3

Try it yourself

Closed-book, before checking anything

From a blank file, implement a tiny gather-compute-release-backward-reduce-scatter-update cycle on CPU Gloo. Use your DT-3 single-process oracle with identical initial weights, the concatenated global batch and equal local batch sizes. Record each rank's shard ranges and collective order; compare reconstructed gradients and several updates within explicit floating-point tolerances.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Why can a linear layer need its full weight during backward?Answer

    Its input gradient multiplies the output gradient by the weight. Releasing the forward compute weight therefore requires restoring it before that multiplication.

  2. 2.Is parameter resharding a network transfer?Answer

    Not ordinarily. Each rank retains its persistent shard and frees the transient gathered copy. Gradient reduce-scatter is the network operation that produces the owned reduced gradient.

  3. 3.When does a mean of local mean gradients equal the global mean gradient?Answer

    When local losses use the same normalization and each rank has the same number of contributing examples or tokens. Unequal counts require weighting by those counts.

5

Practice

  • CS336 Assignment 2: fsdp

    Section 7; implement get_fsdp, fsdp_on_after_backward and fsdp_gather_full_params in tests/adapters.py; run pytest tests/test_fsdp.py

    Two CPU Gloo ranks. test_fsdp_correctness compares three SGD updates with full-batch training in FP32 and FP16 compute. test_fsdp_gradient_sync checks gradient shape and master dtype, and cross-rank agreement of replicated gradients. The section mini-project adds shard ownership and lifecycle evidence.

You're done when

Your educational FSDP passes the public correctness and gradient tests, and its rank logs explain where each full weight and reduced shard lives.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 9 more in the section
  • CS336 Assignment 2 (Spring 2026) - Sections 6, 7 and 8.3Stanford University · primary

    Complete optimizer_state_sharding and optimizer_state_sharding_accounting (Section 6), fsdp and fsdp_accounting (Section 7) and fsdp_calcs (Section 8.3) with your own code. tests/test_sharded_optimizer.py and tests/test_fsdp.py run on CPU with Gloo. For each variant, predict per-rank state, peak live tensors and collective bytes before testing tiny cases.

  • PyTorch FSDP2 Tutorial (fully_shard)PyTorch · required

    Work through fully_shard per block then root, MixedPrecisionPolicy, reshard_after_forward, explicit prefetch and DTensor state dicts, and check each against the 2.14 API reference. FSDP1 (FullyShardedDataParallel) is the legacy API; record the PyTorch version beside every result.

Also in this section

  • Ultra-Scale Playbook - Zero Redundancy Optimizer (ZeRO)Hugging Face · required

    Read the ZeRO-1, ZeRO-2 and ZeRO-3 progression. Reproduce the memory diagrams for one transformer layer and annotate every all-gather, reduce-scatter and reshard boundary. Its "two times faster" line holds for bytes moved at equal payload in the bandwidth-bound regime.

  • ZeRO: Memory Optimizations Toward Training Trillion Parameter ModelsRajbhandari et al. (SC 2020) · required

    Read the memory analysis (model states with optimizer bytes per parameter) and the stage-by-stage savings and communication analysis. Reproduce its per-device memory for one model and degree.

  • PyTorch FSDP: Experiences on Scaling Fully Sharded Data ParallelZhao et al. (VLDB 2023) · support

    Read the design sections on wrapping granularity, prefetching, rate limiting and hybrid sharding. Its flat parameter describes FSDP1; FSDP2 shards each parameter as a DTensor.

  • TorchTitan - FSDP2 NotesPyTorch · support

    Read docs/fsdp.md for the FSDP1 to FSDP2 changes, dim-0 DTensor shards, reshard_after_forward values and hybrid sharding on a 2D mesh, then torchtitan/distributed/fsdp.py. Pin the commit you read.

  • DeepSpeed ZeRO TutorialDeepSpeed · support

    Use the stage definitions and the zero_optimization configuration as the original vocabulary for the three stages and offload. Running it needs CUDA GPUs.

  • Distributed Training Guide - Chapter 4 FSDPLambda Labs · support

    Read model initialization on the meta device, sharding, reshard policy, CPU offload and sharded checkpoint code in 04-fully-sharded-data-parallel as a practitioner second view. Its scripts need CUDA.

  • TorchFeather - FSDP and Activation CheckpointingTorchFeather · support

    Watch the video segment at 10:49:41 on meshes, DDP and FSDP, then read distributed/activation_checkpoint.py and the FSDP calls in model/parallelize.py. Trace how parallel dimensions select the mesh, FSDP policy, precision and reshard behavior; do not adopt the full framework.

  • How to Scale Your Model - Chapter 5 TrainingGoogle DeepMind · support

    Work the FSDP, model-state sharding, rematerialization and offload calculations in Chapter 5. Translate each JAX-oriented layout into equivalent parameter, activation and collective ownership without implementing JAX.

  • TensorTonic - Account for ZeRO Memory by StageTensorTonic · support

    Solve Account for ZeRO Memory by Stage before the CS336 accounting problems.