Unit 10 of 12 · about 4 hours · implement
Full, local and sharded state dictionaries and optimizer state
A shard's tensor values are not a checkpoint contract without its global identity and placement. The optimizer's moments and parameter mapping must survive the same transition as the weights.
You'll be able to
- Distinguish full logical state, layout-bound local state and metadata-bearing sharded state dictionaries.
- Save and load model and optimizer state with named-parameter contracts instead of assuming rank-local optimizer IDs are portable.
- Prove same-world-size checkpoint restore by comparing the next optimizer update, not just loaded weights.
Covers
Read
In this order, only the parts listed
0 of 3 done
- FSDP2 state dictionariesPyTorch FSDP2 Tutorial (fully_shard)
State Dicts with DTensor APIs and State Dict with DCP APIs (page read 2026-10-14)
Use the sharded or DCP path for routine restore. For manual consolidation, every rank gathers, but only the designated writer should call
torch.save; the example's final save line is outside its rank-zero branch. - Current model and optimizer state contractPyTorch FSDP2 Tutorial (fully_shard)
get_state_dict,set_state_dictandStateDictOptions;state_dict_saver.saveandstate_dict_loader.loadUse these current APIs, not the earlier FSDP1
load_sharded_optimizer_state_dictexample on the same page. - Legacy format vocabularyPyTorch FSDP2 Tutorial (fully_shard)
FSDP1
StateDictType,FullStateDictConfig,LocalStateDictConfig,ShardedStateDictConfigandFullyShardedDataParallel.optim_state_dictRead for full/local/sharded terminology only. FSDP1 is deprecated; do not implement its state-dict context manager in a new FSDP2 trainer.
Focus on
- A full dictionary contains full logical tensors under model names. Legacy local dictionaries preserve rank-local flat layout and are tied to that partition. A sharded dictionary carries global tensor identities and layouts so a loader can locate each slice.
- FSDP2's
model.state_dict()retains parameter names and DTensor layouts without gathering all parameters.to_local()alone discards the information needed to identify a shard globally. - Use
get_state_dictandset_state_dictfor the model/optimizer pair. Their optimizer mapping uses canonical fully qualified parameter names rather than assuming numeric optimizer IDs mean the same thing after rebuilding. - Checkpoint after an optimizer step with initialized moments and cleared gradients. DCP requires allocated destination state and consistent keys across participating ranks. Weights alone are insufficient for training resume; the complete RNG, sampler and scheduler contract belongs to DT-9.
Common mistakes · 3
- Saving only rank zero's local shard and calling it a full model.
- Treating
state_dict()as an immutable snapshot while continuing to mutate the underlying tensors. Save synchronously here, or explicitly clone the reference branch. - Checking loaded weights but ignoring optimizer moments and counters. The first resumed update can diverge even if the forward initially matches.
Try it yourself
Closed-book, before checking anything
get_state_dict to save model and optimizer with DCP, rebuild the same sharded model and optimizer, load into the destination dictionaries, then apply set_state_dict. Compare reconstructed weights, moment tensors, step counters and the next fixed-batch update with an uninterrupted branch. Inspect local tensor sizes and placements so successful restore cannot hide full-state replication.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.What is missing from a saved
to_local()tensor?AnswerIts global shape, shard placement, mesh and global parameter identity unless stored separately. Raw values alone do not identify where the shard belongs.
2.Does an FSDP2 sharded
model.state_dict()require full-parameter all-gathers?AnswerNo. It exposes DTensor state in its sharded representation. Requesting full tensors or a full-state option does require consolidation work.
3.Why compare the next update after restore?Answer
It exercises parameter mapping, optimizer moments, counters and hyperparameters together. A weight-only comparison cannot detect missing or misassigned optimizer history.
You're done when
The restored next update matches the uninterrupted branch within stated tolerances, optimizer state is mapped correctly, and each rank still owns only its intended shards.
Only when you can do this without notes.
Leads to
Notes
Resources · 1 for this unit, 10 more in the section
- 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
- 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. - 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.