Unit 6 of 12 · about 4 hours · implement

FSDP2 on DTensor with mixed parameter and reduction dtypes

Build on Precision formats, autocast and gradient scaling. The new issue is where casts occur across ranks: compute weights, reduction payloads and optimizer shards can have three different roles.

You'll be able to

  • Apply FSDP2 bottom-up on a CPU device mesh and inspect local DTensor shards before and after a step.
  • Choose parameter, reduction and output dtypes separately and account for their storage and communication.
  • Construct the optimizer after sharding and verify global gradient clipping against an unsharded oracle.

Covers

Mixed parameter and reduction dtypesFSDP2 DTensor-native configuration
1

Read

In this order, only the parts listed

0 of 2 done

  1. FSDP2 precision and DTensor optimizerPyTorch FSDP2 Tutorial (fully_shard)

    Enabling Mixed Precision; Gradient Clipping and Optimizer with DTensor; revisit Model Initialization's DTensor inspection (page read 2026-10-14)

  2. MixedPrecisionPolicy in PyTorch 2.14PyTorch FSDP2 Tutorial (fully_shard)

    MixedPrecisionPolicy: param_dtype, reduce_dtype, output_dtype and cast_forward_inputs; fully_shard user contract

2

Focus on

  • Start with FP32 and a 1D CPU mesh on Gloo. Shard blocks before the root, use model(x) so hooks run, then construct AdamW from the sharded parameters. Inspect global shapes and to_local() separately.
  • For original FP32 parameters, MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32) gathers BF16 weights, computes in BF16 and reduces gradients in FP32. The optimizer updates original FP32 shards; it does not need another FP32 master copy.
  • If reduce_dtype=None and param_dtype is set, the reduction payload uses the compute dtype, and the stored gradient shard is cast back to the original parameter dtype. output_dtype changes floating-point outputs at the module boundary, not the optimizer's state dtype.
  • Use torch.nn.utils.clip_grad_norm_ on the DTensor parameters, not on each rank's local shards separately. A global norm must combine the disjoint gradient contributions without counting replicated copies twice.
Common mistakes · 3
  • Inspecting the weight in a post-forward hook registered after FSDP's hook and expecting the compute dtype. It may already have been resharded to the original dtype; inspect inside forward or after FSDP's pre-hook.
  • Calling model.forward(x) directly. It bypasses the pre-forward gather and reads whatever is registered: after resharding it fails with a mixed Tensor and DTensor error, and while full weights are still retained it can silently run, so a passing call proves nothing.
  • Clipping each local shard to the same maximum norm. That implements different scaling from clipping the reconstructed global gradient.
3

Try it yourself

Closed-book, before checking anything

Adapt the tutorial to two CPU Gloo processes with init_device_mesh('cpu', (2,)) and a tiny two-linear-layer model. First match several FP32 AdamW updates and a clipped gradient norm to the single-process global-batch oracle. Then use BF16 parameter compute and FP32 reduction; inspect the full compute weight during a forward pre-hook, the FP32 shard and gradient after backward, and FP32 Adam moments after the update. Compare mixed precision to an oracle with matching casts, not to a bitwise FP32 target.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.Which dtype determines parameter all-gather bytes?Answer

    The unsharded parameter dtype, selected by param_dtype when set. The stored optimizer shard can remain FP32.

  2. 2.Does FP32 reduction recover precision lost during BF16 compute?Answer

    No. It limits additional rounding during reduction, but cannot recover information already lost in low-precision computations.

  3. 3.Why initialize the optimizer after fully_shard?Answer

    It must reference the DTensor parameters that the sharded optimizer step will update, with the correct ownership and shape semantics.

  4. 4.What should happen when a correct mixed-precision run is compared with FP32?Answer

    Small numerical differences can occur. Validate against a same-policy oracle with explicit tolerances, and report any FP32 comparison as a precision comparison rather than bitwise equivalence.

You're done when

Your dtype and placement logs agree with the selected policy, and FP32 updates and global clipping match the oracle before you introduce low-precision compute.

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_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

  • 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.

  • 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.