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
Read
In this order, only the parts listed
0 of 2 done
- The current FSDP lifecyclePyTorch FSDP2 Tutorial (fully_shard)
How FSDP2 works and How to use FSDP2 / Model Initialization (page read 2026-10-14)
- 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 43Implement and test the CPU Gloo path first. Leave GPU profiling in
fsdp_accountingto the peak-memory unit. The handout's FP32 master-weight prescription is its implementation contract, not a theorem forbidding other training formats.
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.
Try it yourself
Closed-book, before checking anything
Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
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.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.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.
Practice
- CS336 Assignment 2:
fsdpSection 7; implement
get_fsdp,fsdp_on_after_backwardandfsdp_gather_full_paramsintests/adapters.py; runpytest tests/test_fsdp.pyTwo CPU Gloo ranks.
test_fsdp_correctnesscompares three SGD updates with full-batch training in FP32 and FP16 compute.test_fsdp_gradient_syncchecks 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_shardingandoptimizer_state_sharding_accounting(Section 6),fsdpandfsdp_accounting(Section 7) andfsdp_calcs(Section 8.3) with your own code.tests/test_sharded_optimizer.pyandtests/test_fsdp.pyrun 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_shardper 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.mdfor the FSDP1 to FSDP2 changes, dim-0 DTensor shards,reshard_after_forwardvalues and hybrid sharding on a 2D mesh, thentorchtitan/distributed/fsdp.py. Pin the commit you read. - DeepSpeed ZeRO TutorialDeepSpeed · support
Use the stage definitions and the
zero_optimizationconfiguration 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-parallelas 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.pyand the FSDP calls inmodel/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.