Repository navigation
[decoder] Keep tok_embeddings and lm_head tied through _parallelize - #6144
Conversation
[ghstack-poisoned]
|
@claude review this pr |
|
Claude finished @anshul-si's task in 2m 33s —— View job Approve (please fill in the empty human-written summary before merging): review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The fix re-ties the weights in the layer that unties them, closes a real silent-training bug when the tied FSDP shard is padded, and keeps every in-repo caller correct. A maintainer still needs to review, since this touches models/common/decoder.py.
What this PR does. Module._spmd_distribute_state registers a new nn.Parameter in each module. On main this unties tok_embeddings.weight and lm_head.weight before fully_shard runs, so FSDP2 builds two FSDPParams for one weight. The PR adds Decoder._parallelize, which calls super() and then re-points tok_embeddings.weight at lm_head.weight. It also adds a __post_init__ check that a tied config gives both modules the same weight sharding.
Example.
Qwen3 0.6B (vocab 151936), FSDP 6 -> the tied shard is padded on some ranks
main: [tok_embeddings, norm, lm_head] -> 3 FSDPParams. Lazy init pads a private copy
for the embedding's FSDPParam. The optimizer updates lm_head's copy, so on the
padded ranks the embedding rows never train.
this PR: tok_embeddings.weight is lm_head.weight going into fully_shard -> 2 FSDPParams.
One copy gets all-gathered and updated.
Must fix
- PR description -- the "Summary (human-written)" section is empty. Per
CONTRIBUTING.mdand.claude/CLAUDE.md, the author fills it in by hand. Add a few sentences of your own before merging.
Details
- Callsites checked.
Decoder._parallelizeis the only_parallelizeoverride on a model. The overrides inquantization/{mxfp8,nvfp4}/linear.pyanddist_moe/mxfp8.pyare on leaf modules.BaseModel.parallelize,MultimodalModel.parallelizeandGraphTrainerModel.parallelizeall go throughself._parallelize. - PP.
config/validation.py:49rejects tying together with PP > 1, sotok_embeddings/lm_headare neverNonein the new override. - SimpleFSDP.
data_parallelgivestok_embeddingsandlm_headseparate parameters even though it now starts from one shared parameter._prepare_spmd_parameter_for_fsdpdoesn't mutate its input, andlinear_param_shard_placementsskips unstackedlm_head, so no placement changes. The re-tie ininit_statesis still needed, as the PR says. - Converters.
LMHeadFP32OutputConvertercopies all fields, includingsharding_config, so the new layout check still passes. LoRA already rejectslm_headas a target when weights are tied. - Layout check. In-repo tied flavors use
token_embedding_sharding_configandlm_head_sharding_config. Both declaredense_param_placement(tp=spmd.S(0))forweight, so the check passes. A real mismatch would otherwise be silently wrong:VocabParallelEmbedding._lookup_vocab_shardassumes a vocab-sharded weight. So the check guards a real contract. - Numerics. The changes are explained in the description: padded shards (main is wrong), the bf16-level change in the tied gradient with
lm_headin forward, and an fp32 rounding-level change under deferred GA or HSDP. No golden file changes except possiblyrl_grpo_cuda.txt, which the author reasons should be unchanged (TP 4, FSDP 1, ChunkedLossWrapper).
Not verified: I didn't run the new unit tests or any GPU or RL runs; the bash sandbox didn't allow pytest.
tianyu-l
left a comment
There was a problem hiding this comment.
sounds a real bug! thanks for fixing
Please address inline comments before merging
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
this approach, and what you checked yourself. -->
## Why
`Module._spmd_distribute_state` registers a new `nn.Parameter` in every module it distributes. So `_parallelize` unties `tok_embeddings.weight` and `lm_head.weight` in every decoder with `enable_weight_tying=True` (Qwen3 debugmodel/0.6B/1.7B/4B, Llama 3 1B/3B, Qwen3.5 0.8B/2B/4B) before FSDP sees the model. `Decoder.init_states` ties them again, but only after `to_empty()`. FSDP2 therefore gets two parameters for one weight in the group `[tok_embeddings, norm, lm_head]` (three FSDPParams instead of two). Three problems follow:
- **When FSDP pads the tied weight's shard, the embedding trains on a stale copy.** Padding happens when `(vocab / tp) % (dp_shard * cp) != 0`. At lazy init, `FSDPParam.reset_sharded_param` re-reads the module parameters. The embedding's FSDPParam pads a private copy of `lm_head`'s local shard. Then `lm_head`'s FSDPParam pads a second copy and points the parameter at it. The optimizer updates `lm_head`'s copy, but the embedding keeps all-gathering its own, so the embedding rows on every rank with a padded shard never change. This affects:
| Flavors | Padded at |
| --- | --- |
| Qwen3 0.6B/1.7B/4B (vocab 151936) | FSDP degree 6, 12, 24 (any multiple of 3); also TP 8 x FSDP 32 or 64 |
| Qwen3.5 0.8B/2B/4B (vocab 248320) | FSDP degree 6, 12, 24 (any multiple of 3) |
| Llama 3 1B/3B (vocab 128256) | TP 8 x FSDP 64, TP 4 x FSDP 128 |
- **Without padding, FSDP2 communicates the tied weight twice.** It all-gathers both copies in every unshard. With `lm_head` in the model forward it also reduce-scatters both. Grouping the three modules was meant to avoid exactly this (see the comment in `apply_fsdp_to_decoder`).
- **Sharders that don't re-read parameters train silently wrong.** A sharder that keeps the parameters it was given at wrap time trains the embedding with a weight the optimizer doesn't hold. FlexShard is one: #5842 rejects tied weights and depends on this fix.
**Example.** Tied Qwen3 debugmodel with vocab 2049, FSDP 2, on GPU. Rank 1 holds 1024 rows, padded to 1025. Per rank, after each optimizer step: does each FSDPParam of the tied group all-gather the live parameter?
```
main rank 0 VocabParallelEmbedding FSDPParam: yes Linear FSDPParam: yes
rank 1 VocabParallelEmbedding FSDPParam: no, a private copy Linear FSDPParam: yes
(the copy is unchanged after steps 2 and 3: those 1024 embedding rows never train)
this PR rank 0 VocabParallelEmbedding FSDPParam (shared with lm_head): yes
rank 1 VocabParallelEmbedding FSDPParam (shared with lm_head): yes
```
Tie state at each lifecycle stage (Qwen3 debugmodel, FSDP 2 or TP 2). Is `tok_embeddings.weight is lm_head.weight` true?
```
build _parallelize fully_shard to_empty init_states tied FSDP group
main yes no no no yes VocabParallelEmbedding.weight, RMSNorm.weight, Linear.weight
this PR yes yes yes yes yes VocabParallelEmbedding.weight (shared with lm_head), RMSNorm.weight
```
## What changed
- New `Decoder._parallelize` (7 lines). It calls `super()._parallelize` and then, if `enable_weight_tying` is set, points `tok_embeddings.weight` at `lm_head.weight` again. Like `__init__`, it then shares the RoPE caches again (`_tie_rope_caches`), for code that runs before `init_states`. On llama3 at `tp=2` (with sequence parallel), `cp=2` and `dp_shard=2`, the caches already stay shared through `_parallelize`, so this changes nothing today.
- Every in-repo decoder reaches it through `self._parallelize`: `MultimodalModel`, `KimiK3Model`, the GraphTrainer models and the vLLM generator. No decoder overrides `_parallelize`.
- `Decoder.Config.__post_init__` raises `ValueError` if a tied config gives `tok_embeddings` and `lm_head` different weight shardings (`sharding_config.state_shardings["weight"]`).
- From `_parallelize` on, the embedding uses `lm_head`'s distributed weight, so a mismatch would otherwise be silently wrong.
- Every in-repo tied flavor declares `dense_param_placement(tp=spmd.S(0))` for both (vocab-sharded on TP, Replicate on DP and CP), so their local shards match under TP.
- `Decoder.init_states` keeps its re-tie (comment-only change).
- `to_empty()` changes parameters in place and keeps the tie, so FSDP2 no longer needs it.
- GraphTrainer's SimpleFSDP still does: its `data_parallel` registers new parameters after `_parallelize`, which unties the weights again. Without the re-tie, the embedding would keep the storage that `skip_param_init` never initializes.
- The `enable_weight_tying` docstring now lists `_parallelize` too.
- Two new tests in `tests/unit_tests/cpu/models/llama3/test_weight_tying.py` (see Testing). The `dataclasses` import moved to the top of that file.
## Alternatives considered
- **Keep parameters shared in `Module._parallelize` / `_spmd_distribute_state`.** The recursion shares no state across modules, so this needs alias bookkeeping at the entry point plus a check that every alias got the same layout: about 20 lines, with one consumer. I built all 59 flavors of the 12 in-repo decoder families on meta. The only shared parameter in any of them is `tok_embeddings.weight` / `lm_head.weight`. The HF-backend experiment unties these before `_parallelize`.
- **Re-tie at the start of `Decoder._apply_fsdp`.** That also runs before `fully_shard` and would work for FSDP2, but only for callers that go through `_apply_fsdp`. Re-tying where `_parallelize` breaks the tie covers every caller, including GraphTrainer and the vLLM generator.
- **Delete the re-tie in `init_states`.** It isn't redundant (SimpleFSDP, above).
- **Re-read parameters in each sharder**, as FSDP2's lazy init does. That patches each sharder separately. In FSDP2 it is exactly what breaks under padding, and FSDP2 would still communicate both copies.
## Numerics
These runs predate the rebase onto `4122eafc0` and were made against main `9f70e5597`. The rebase crosses #5802 (`VocabParallelEmbedding`, the TP gather after the final norm); at `4122eafc0` I reran the new tests, the tied-flavor check and the padded-shard GPU probe (see Testing), not the runs below. GPU runs: seed 42, deterministic, 2x GB200, `scripts/loss_compare.py <main> <this PR> --metrics loss,grad_norm --no-seed-checkpoint`. All use flex attention (FA4 isn't installed locally). CPU runs use gloo, Qwen3 debugmodel and ChunkedLossWrapper, and run 4 steps (adapted from the reviewer's script).
| Config | Loss | Steps | Result |
| --- | --- | --- | --- |
| Llama 3 debugmodel (untied), FSDP 2 | ChunkedLossWrapper | 20 | bitwise equal, `--assert-equal` |
| Qwen3 debugmodel_moe (untied), FSDP 2 | ChunkedLossWrapper | 20 | bitwise equal, `--assert-equal` |
| Qwen3 debugmodel (tied), FSDP 2 | ChunkedLossWrapper (recipe default) | 100 | bitwise equal at every step |
| Llama 3 debugmodel + `enable_weight_tying`, FSDP 2 | ChunkedLossWrapper | 100 | bitwise equal at every step |
| Qwen3 debugmodel (tied), TP 2 | ChunkedLossWrapper | 100 | bitwise equal at every step |
| **Padded:** Qwen3 debugmodel (tied), vocab 2049, FSDP 2 (GPU) | ChunkedLossWrapper | 100 | step 1 equal, differs from step 2; main is wrong (Example) |
| **Padded:** Qwen3 debugmodel (tied), CPU, `dp_shard=3` | ChunkedLossWrapper | 4 | step 0 equal; step 1 7.7073 (main) vs 7.7017 (this PR); main's rank 2 gathers a stale embedding copy |
| Unpadded control: same, CPU, `dp_shard=2` | ChunkedLossWrapper | 4 | bitwise equal |
| The three unpadded tied GPU configs | CrossEntropyLoss (`lm_head` in forward) | 100 | first-step loss equal, then small drift (table below) |
**Padded shards: numerics change because main is wrong.** On main, the embedding's rows on the padded ranks stay at their initial values (Example). This PR trains them. In the GPU vocab-2049 run, the mean absolute loss difference is 6.4e-5, 2.3e-4, 9.5e-4 and 1.0e-3 over steps 1-25, 26-50, 51-75 and 76-100 (max 2.9e-3).
**Unpadded shards with ChunkedLossWrapper (used by every in-repo recipe for a tied flavor): bitwise unchanged.** This holds with the default per-microbatch reduction.
- `lm_head` runs in the loss's own backward passes. `fsdp_partial_backwards` reduce-scatters the tied group after the last of them, before the decoder backward computes the embedding's gradient.
- The decoder backward reduce-scatters the group a second time, and the two results are added in fp32 in the sharded `.grad`.
- This is the same on main, where two FSDPParams point at one sharded parameter, and in this PR, where one FSDPParam is reduced twice. All 66 parameter gradients after the first trainer step are bitwise equal.
**Gradient accumulation with deferred reduction, or HSDP: fp32 rounding-level change.** With gradient accumulation plus `fsdp_defer_gradient_reduction=True`, or with HSDP (whose replica all-reduce `TrainingEngine` defers to the last microbatch), both uses' gradients are summed before a single reduction. The tied gradient then changes at fp32 rounding level. At step 0 on CPU the max difference is 3.4e-8 (FSDP 2, GA 2, deferred) and 3.7e-9 (HSDP 2x2, GA 2). No in-repo tied recipe uses either.
**Unpadded shards with `lm_head` in the forward: the tied gradient changes at bf16 level.**
- Both uses of the weight now run in one backward. FSDP2 delays the unsharded gradient's upcast to `reduce_dtype` (`FSDPParam.defers_grad_upcast`), so autograd adds the embedding's and `lm_head`'s bf16 contributions into one bf16 gradient, which is widened and reduce-scattered once.
- On main, each contribution was widened and reduce-scattered on its own, and the two were added in fp32.
- At step 0 only the tied gradient moves: by at most 4.77e-4 (largest entry 0.187, about half a bf16 unit), in 8.8% of its elements. The first-step loss is bitwise equal.
- Over 100 steps the gap is as large as main's own gap between ChunkedLossWrapper and plain cross entropy, and it doesn't grow. Loss is about 2.75 at step 100.
In the table below, each step-range cell is the mean absolute loss difference over that range. The signed mean is this PR minus main; for the reference row it is CrossEntropyLoss minus ChunkedLossWrapper.
| CrossEntropyLoss run | 1-25 | 26-50 | 51-75 | 76-100 | signed mean, 76-100 | max abs diff |
| --- | --- | --- | --- | --- | --- | --- |
| Qwen3 tied, FSDP 2 | 2.7e-5 | 5.9e-4 | 4.9e-4 | 8.0e-4 | -5.6e-4 | 2.0e-3 |
| Llama 3 tied, FSDP 2 | 5.3e-4 | 4.5e-4 | 2.2e-4 | 2.1e-4 | +1.9e-4 | 2.6e-3 |
| Qwen3 tied, TP 2 | 3.5e-5 | 3.5e-4 | 3.0e-4 | 8.2e-4 | -7.5e-4 | 2.2e-3 |
| Reference: main only, Qwen3 tied FSDP 2, ChunkedLossWrapper vs CrossEntropyLoss | 2.7e-5 | 6.7e-4 | 5.5e-4 | 8.4e-4 | -1.7e-4 | 3.5e-3 |
**Golden losses.** No file in `tests/assets/losses/` trains a tied model except `rl_grpo_cuda.txt`.
- `rl_grpo_cuda.txt` is the RL loss guard: tied Qwen3-0.6B, ChunkedLossWrapper, trainer TP 4, FSDP degree 1, so no padding. It should stay the same, but I couldn't run it (it needs 8 GPUs, vLLM and HF weights).
- The `qwen3` goldens use the untied `debugmodel_moe`. The `llama3` and `sft` goldens use the untied Llama 3 debugmodel.
## Performance
Bytes per rank per step for the tied group: all-gather output and reduce-scatter input. Qwen3 debugmodel (vocab 2048, dim 256), FSDP 2, counted by wrapping FSDP2's collectives inside the trainer.
| Loss | All-gather, main -> this PR | Reduce-scatter, main -> this PR |
| --- | --- | --- |
| ChunkedLossWrapper | 4,195,328 -> 2,098,176 (2 calls) | 4,195,328 -> 4,195,328 (2 calls) |
| CrossEntropyLoss | 2,097,664 -> 1,049,088 (1 call) | 4,195,328 -> 2,098,176 (1 call) |
With ChunkedLossWrapper, reduce-scatter bytes don't change. The group is reduced once after the loss's backward and once after the decoder backward (as the untied `[norm, lm_head]` group is), and the tied weight's gradient is in both reductions either way.
## Testing
- **New tests.** Both fail on main (`4122eafc0`) and pass here.
- `test_weights_remain_tied_after_parallelize` builds a tied Llama 3 debugmodel on meta, runs `_parallelize` with TP 2 on a fake process group, and asserts `tok_embeddings.weight is lm_head.weight`. It catches any change that unties the weights between `_parallelize` and FSDP.
- `test_tying_rejects_different_weight_shardings` gives `lm_head` a different weight sharding and expects `ValueError`.
- **All 9 tied flavors** (Llama 3 1B/3B, Qwen3 debugmodel/0.6B/1.7B/4B, Qwen3.5 0.8B/2B/4B), built on meta with a fake process group:
- With TP 2, each is untied after `_parallelize` on main and tied here (rechecked at `4122eafc0`).
- At (tp, dp_shard, cp) = (1, 3, 1), (2, 2, 1) and (2, 1, 2), each passes the new layout check and stays tied after `_parallelize`.
- **Padded-shard probes.** These are the GPU run in the Example (rerun at `4122eafc0`, 3 steps: rank 1's embedding FSDPParam is unchanged after steps 2 and 3 on main) and CPU `dp_shard=3`. On main, the padded rank's embedding FSDPParam holds a private, never-updated copy. Here every FSDPParam all-gathers the live parameter.
- **Lifecycle probes** (main vs this PR in one process, FSDP 2 and TP 2): the tie at each stage and the FSDPParam count (Example). GraphTrainer's `apply_simple_fsdp` unties the weights; `init_states` ties them again, and without that re-tie they stay untied.
- **Unit tests** (at `9f70e5597`). `pytest tests/unit_tests/cpu/{models,distributed,config}` plus `tests/unit_tests/cpu/components/test_chunked_loss_fsdp.py`: 850 passed here. On main the first three suites gave 847 passed; the 3 extra here are the two new tests and `test_chunked_loss_fsdp.py`.
- Both have the same 53 failures and 7 collection errors, all from the local environment: FA4 missing, `transformers` missing, spmd_types 0.2.0 instead of the pinned 0.3.1, and `torch_checkpointing`/`renderers` versions.
- **Lint.** pyrefly 0.45.1 reports the same 12 errors as main. pre-commit passes, except its pyrefly hook, which can't run locally.
- **TP 2 runs** used spmd_types 0.3.1, the pinned version. Main also fails TP 2 locally with 0.2.0.
## Known issues / follow-ups
- **Not run:**
- TP > 1 together with FSDP > 1 (needs 4+ GPUs; the 8-GPU integration test `qwen3_fsdp+tp+cp_no_sp` trains the tied Qwen3 debugmodel that way).
- A real-vocabulary padded run, e.g. Qwen3-0.6B at FSDP 6.
- The RL loss guard.
- The vLLM generator. It also goes through `parallelize`, and its `_fsdp_load_groups` already maps both tied keys to the shared FSDPParam.
- **Follow-up question:** should SimpleFSDP's `data_parallel` (`torchtitan/experiments/graph_trainer/simple_fsdp.py`) keep shared parameters tied? Then the re-tie in `Decoder.init_states`, and its comment naming an experiment, could go.
ghstack-source-id: 9f70984
Pull-Request: #6144
## Summary (human-written) Our goal is to fully replace FSDP2 with FlexShard. This PR is the first step: it adds FlexShard as an experimental, opt-in backend while keeping FSDP2 as the default. This lets us test new FlexShard features and close feature gaps while users on FSDP2 see no change. ## Description torchtitan can shard data-parallel parameters only with FSDP2's `fully_shard`. This PR adds `parallelism.fsdp_backend`, the config of a `ShardingBackend` (`torchtitan/distributed/sharding_backend.py`). A `ShardingBackend` is a `Configurable` that owns the operations that depend on how the parameters are sharded: validating the config, sharding a decoder and clipping grad norms. Callers build it from its config and call it, so no code checks which backend is in use. The default, `FullyShardBackend.Config()`, keeps FSDP2. Setting it to `FlexShardBackend.Config()` shards the model with FlexShard (meta-pytorch/flex_shard) instead. FSDP2's existing `fsdp_*` options stay on `ParallelismConfig` for now, so the FSDP2 path is unchanged. This is the first step of replacing FSDP2. It covers the case where the two backends can be compared bit for bit: decoders with data parallelism over `dp_shard` only. `Decoder._apply_fsdp` calls the backend's `apply_to_decoder`, and `flex_shard` is imported only when it is selected. Later PRs in the stack add the operations they need to `ShardingBackend` rather than checking the backend. `FullyShardBackend.apply_to_decoder` runs what `Decoder._apply_fsdp` ran before: it calls `apply_fsdp_to_decoder`, which calls `fully_shard` on the embedding, on the norm with the output projection, on each transformer block, and finally on the root model for any leftover parameters. `FlexShardBackend.apply_to_decoder` (`torchtitan/distributed/flex_shard_backend.py`) takes the same units from `decoder_sharding_units`, which `apply_fsdp_to_decoder` also uses, and gives FlexShard one bucket for each. Each bucket uses its unit's mesh, shard dims and reshard-after-forward policy, the same param and reduce dtypes, `gradient_divide_factor=1.0` (gradients are summed, as `disable_fsdp_gradient_division` makes FSDP2 do) and `fsdp2_compatible=True`. The leftover root bucket, like FSDP2's root unit, isn't resharded after forward. As a result the two backends issue the same collectives, and training from the same parameters is bitwise identical. To keep the two backends from drifting apart, the grouping moved out of the FSDP2 loop into `decoder_sharding_units` in `fsdp.py`, and the rest of FSDP2's code into `_apply_fully_shard`. `decoder_sharding_units` returns each unit's modules, reshard policy, and stacked-linear and routed-expert placements. `apply_fsdp_to_decoder` now takes every argument but `model` by keyword, so its callers pass `dp_mesh` by name. The FSDP2 path's behavior doesn't change. It now passes each unit to `fully_shard` as a list (`fully_shard([block])`), and FSDP2 gives a one-module list the same per-module hooks as the module itself. The embedding's `set_unshard_in_backward(False)` condition and the EP > 1 per-parameter mesh logic are the same as before. FlexShard parameters and their grads stay plain local shards: nothing on the FlexShard path creates a DTensor. torchtitan relied on FSDP2's DTensor parameters in two places, which now handle plain shards: - **Initialization.** Right after sharding, `_apply_flex_shard` wraps each FlexShard parameter's `param_init` function with flex_shard's `init_from_full` and the layout flex_shard reports for it (`get_flex_shard_global_layouts`). The wrapped function runs the init function on a full-size tensor and keeps this rank's part, so each shard is its slice of one device's initialization. `to_empty()` rebuilds FlexShard's parameters but keeps the modules, so the wrapped functions survive it, and `models/base` doesn't change. FSDP2's DTensor init draws each shard's values separately, so the two backends start from different, equally valid, weights. A module without `param_init` falls back to `reset_parameters()`, which would draw each FlexShard shard as the whole parameter, with the same values on every rank, so such modules are rejected (below). With tied weights, which pytorch#6144 keeps tied through parallelization, flex_shard reports the shared parameter under both names. `lm_head`'s function initializes it, and `tok_embeddings`' `skip_param_init` stays a no-op rather than being wrapped. Wrapped, it would copy an uninitialized full tensor into the shard, which `lm_head`'s function overwrites only because `tok_embeddings` initializes first. - **Grad-norm clipping.** `ParallelismContext` holds the built backend, and `GradientClipper` clips with its `clip_grad_norm_`. `FullyShardBackend`'s calls `dist_utils.clip_grad_norm_`, as `GradientClipper` did before. `FlexShardBackend`'s groups the grads by their bucket's mesh (`flex_shard.get_mesh`) instead of by DTensor mesh. `flex_shard_grad_norm` reduces each group's norm over its mesh in DTensor's order (each grad's local norm, all-reduced, then the norm of those norms), ported from flex_shard's DeepSeek V3 example, so the norm matches FSDP2's bit for bit. Combining the groups' norms, the PP reduction and clipping moved out of `dist_utils.clip_grad_norm_` into `clip_grads_with_mesh_norms_`, which both backends call. FlexShard differs from FSDP2 in one way that affects memory and communication: FSDP2 skips the embedding's backward all-gather, and FlexShard can't yet, so it gathers the embedding again in backward. Anything FlexShard doesn't support yet raises a `ValueError` when the config is validated, after recipes and overrides and before distributed init. `validate_model_training_config` calls the backend's `validate_model`, which checks the model, parallelism and training options. The checks of the loss, checkpointer, optimizers and trainer read configs that `validate_model_training_config` doesn't receive, so `TrainingEngine.Config.__post_init__` calls the backend's `validate_trainer`, for every trainer. Both do nothing for `FullyShardBackend`. FlexShard's checks are temporary: each goes once FlexShard supports the feature. - **Parallelism:** HSDP, tensor, context, expert and pipeline parallelism. - **FSDP2 options:** symmetric-memory communication, CPU offloading, unsharding in the current stream (`fsdp_unshard_in_current_stream`), and deferred gradient reduction (`fsdp_defer_gradient_reduction`), since FlexShard has no `set_is_last_backward`. - **Model:** any model that overrides `_apply_fsdp` (multimodal models, DeepSeek V3 and V4, Flux and the transformers modeling backend); `preserve_dtype_params`; modules without `param_init` that have a `reset_parameters()`; and MXFP8/NVFP4 weights. All are read from the model config, so the `param_init` check also rejects modules that have no parameters to initialize, such as the `RMSNorm(elementwise_affine=False)` QK norms of muse_glimmer and muse_spark. - **Training features:** accelerator graphs, `ChunkedLossWrapper`, checkpointing, EMA, DistMuon, gradient clippers other than `GradientClipper` (only it is known to clip with the backend's `clip_grad_norm_`) and SPMD typechecking. - **Trainers:** any trainer other than `torchtitan.trainer.Trainer`, including GraphTrainer, FaultTolerantTrainer and the RL trainer. `FlexShardBackend.validate_model` then raises an `ImportError` if flex_shard isn't installed, rather than failing when the model is sharded, after distributed init. The multi-GPU unit-test job installs flex_shard at a pinned commit (`d6bb546`), so the new parity test runs in CI. That test, `test_flex_shard_fsdp.py::test_matches_fsdp2`, runs on 4 GPUs. It builds each model with both backends and checks that each FlexShard shard equals its slice of one device's initialization from the same seed. It then copies FSDP2's initial parameters into the FlexShard model and requires bitwise-equal per-microbatch losses, grad norms, gradients and parameters over three AdamW steps. It covers llama3 `debugmodel` with `fsdp_reshard_after_forward` set to default, qwen3 `debugmodel_moe` with always, and llama3 `debugmodel` with tied weights, set up as the tied Llama 3 flavors (1B, 3B) do, with default, each with two microbatches. A CPU test checks that `validate_model_training_config` rejects a model with its own `_apply_fsdp` (DeepSeek V4) instead of letting it silently shard with FSDP2, and a module without `param_init`. The existing `test_fsdp.py` covers the refactored FSDP2 path; its only edit is mechanical: it now expects `fully_shard([block])`. The optimizer and trainer unit tests that stub `clip_grad_norm_` now give their fake parallelism contexts a `FullyShardBackend`. This revision passes the parity test on 2 GB200 GPUs with `world_size` set to 2. An earlier revision also passed it, except the tied case, on 4 GB300 GPUs. On an earlier revision of this PR, based on `4122eafc0`, the FSDP2 path matched its base bit for bit: `scripts/loss_compare.py 4122eaf <that revision> --assert-equal --metrics loss,grad_norm` (seed 42, deterministic, 50 steps, 2 GB200 GPUs, `dp_shard=2`) reports equal loss and grad norm at every step for llama3 `debugmodel` (step-50 loss 2.86823), for llama3 `debugmodel` with two microbatches per step and `fsdp_defer_gradient_reduction=True` (2.83577), and for qwen3 `moe_debug` (3.71935). These runs use flex attention because the environment has no FA4, and skip the seed checkpoint, since both runs of each pair start from seed 42 with the same parallelism. Expert parallelism is the next PR in the stack. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: b9a77fb Pull-Request: pytorch#5842
…er override; agent self-review; rl/transport (#6407) ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Why Since #5667, `@claude review` has reviewed 459 PRs. Of the 380 PRs it approved, 30 then got a formal "request changes" from a maintainer, and about 20 more got substantive inline asks. In nearly all of them the bot either saw the problem and approved anyway, or never asked the questions maintainers ask most ("does the repo already do this?", "who should own this?"). The opposite failure, the bot blocking something a maintainer was fine with, is rare: in the PRs we sampled, 2 of its 81 must-fix items were wrong and about a third were minor (the empty human-written summary was the biggest source). **Example** (#6112, controller sizes the rollout worker pool): ``` before: bot approved 10 times; tianyu-l then blocked: "the controller reads rollouter.rollouts_per_worker to compute a count it hands back to the Rollouter -- violates encapsulation" after: same commit, new skill -> Request changes, must-fix #1: "controller.py:589 -- wrong owner for the worker count ..." ``` There was also no way for a code owner to overrule the bot except dismissing its review in the GitHub UI, and a later `@claude review again` would block again. ## What changed **Review skill** (`.claude/skills/pr-review/`, `review-checklist.md`): - Verdict rules: Approve only when every remaining item is an edit the bot could write itself. Anything the author still owes (a design change, an unexplained golden change, evidence the PR rests on) is Request changes; anything only a maintainer can decide is Needs discussion. A hedge like "a maintainer should decide" can't come with Approve. - Always must-fix: a violated written rule, a silent wrong result, a second definition of an existing concept, a gate finding. - Design gate: new questions for the existing counterpart, in-repo ownership, and the design behind a bug; "ban only what doesn't work on main"; read the numbers behind a claim. The overlapping-PR search is mandatory and reported. - Re-review covers every commit since the last full review, including code taken from the bot's own suggestions. A scoped question gets a `COMMENT`, not a whole-PR verdict. - The bot fact-checks its own proposed fixes, and cites a source for claims about external tools or marks them unverified (never must-fix). - An empty "Summary (human-written)" is a one-line "Before merge" note that never affects the verdict. - Checklist: config ownership direction, general shared wrappers, dead code the PR creates, model variants as flavors, a mechanical pass over every new or changed function. **Code owner override** (`SKILL.md`, `claude-code.yml`, `CONTRIBUTING.md`): a code owner comments `@claude override` (optionally `@claude override 2,3: <reason>`); the bot approves if nothing else is open and doesn't re-raise the overridden items. A code owner's GitHub approval or "LGTM" is not an override, so a teammate can approve without the bot dropping its findings. Dismissing the bot's review still unblocks the PR, but isn't an override: the bot can't tell who dismissed it. **Agent self-review** (`CLAUDE.md`, `pr-description`): an agent preparing a PR runs `pr-review` in branch mode first and records unaddressed items in an optional "Self-review" section. PRs written without an agent are unaffected; a missing section is never a finding. Where each new rule comes from (maintainer asks the bot missed): | Change | PRs | | --- | --- | | No Approve with open design/evidence items or a "maintainer should decide" hedge | #6007, #5837, #5997, #5712, #5511, #5996 | | Author waiver can't clear a must-fix | #6201, #6202, #6203 | | Existing counterpart; one source of truth | #5228, #6169, #5881, #5823, #5824, #6059, #5812 | | Responsibility owner; config ownership direction | #6112, #6332, #5802, #5803, #6325 | | Fix the design behind the bug; a TODO doesn't justify a workaround | #5572, #5689, #5657 | | Fact-check the bot's own suggested fixes | #5740, #5802, #5511, #4819, #5543 | | Re-review covers all new commits; scoped asks don't approve | #5824, #5842 | | Mandatory overlap search | #5885, #6248 | | Ban only what doesn't work on main | #5543 | | Summary placeholder no longer a must-fix | #6119, #6174, #6112, #5868 | **Rules**: `design.md` gets the one-general-wrapper rule (moved from `models.md`, whose glob skipped `torchtitan/rl`), thin adapters, and the consumer owning its values; `config.md` gets ownership direction and "a Config doesn't read runtime state"; `direction.md` calls all-to-all the MoE reference implementation, so a new vendor-specific dispatch path (e.g. #6242) needs a reason the existing backends can't serve. **Area reviewers**: `.ci/` -> huydhn, wwwjn; `torchtitan/rl/transport/` -> d4l3k. **Mechanical, skim**: `torchtitan/rl/transport/` holds data movement between RL actors. - `rl/model_state_dict_transport.py` -> `rl/transport/model_state_dict.py` - `rl/MODEL_STATE_DICT_TRANSPORT.md` -> `rl/transport/MODEL_STATE_DICT_TRANSPORT.md` - `rl/trainer/rdma_microbatch.py` -> `rl/transport/rdma_microbatch.py` - tests: `tests/rl/unit_tests/cpu/test_{model_state_dict_transport,rdma_microbatch}.py` -> `tests/rl/unit_tests/cpu/transport/test_{model_state_dict,rdma_microbatch}.py` - imports, READMEs and `scripts/install_rl_env.sh` updated; no code changes. ## User-facing changes | Before | After | | --- | --- | | Overrule the bot: dismiss its review in the UI, and it blocks again on the next run | `@claude override [items]: <reason>`; the bot approves and doesn't re-raise them | | Empty human-written summary: bot must-fix | One "Before merge" line, no effect on the verdict | | `from torchtitan.rl.model_state_dict_transport import ...` | `from torchtitan.rl.transport.model_state_dict import ...` | | `from torchtitan.rl.trainer.rdma_microbatch import ...` | `from torchtitan.rl.transport.rdma_microbatch import ...` | ## Testing Backtest: the new skill run locally (nothing posted) on each PR at the commit and thread state the bot originally saw. | PR | Bot then | New skill | What the maintainer asked | | --- | --- | --- | --- | | #6112 | Approve | Request changes | worker-count ownership (caught) | | #5837 | Approve | Request changes | apply to `dp_shard` too (caught) | | #5572 | Approve | Request changes | delete the injection design (caught) | | #6201 | Approve after author waived pins | Request changes, waiver ignored | pins broke GPU tests after merge (caught) | | #6007 | Approve | Request changes | fold K3.1 into K3 (caught) | | #5543 | Request changes: "ban it" | Request changes: keep main's path | don't break gpt-oss + DeepEP (fixed) | | #6144, #5905 (controls) | Approve | Approve | -- | | #6137 (control) | Approve | Needs discussion | -- (merge gate on an upstream API) | Code owner override, simulated on #6201: override by a code owner lifts the named item; `@claude override` from the author changes nothing; a code owner's "LGTM" approval followed by "review again" keeps Request changes. Transport move: 83 RL CPU unit tests pass locally (`transport/test_model_state_dict.py`, `test_trainer.py`, `test_engine_loop.py`). `transport/test_rdma_microbatch.py`, `test_generator.py` and `test_batcher_actor.py` fail to collect in my env on `origin/main` too (stale attention-gym / Monarch), so CI is the check for those. ## Known issues / follow-ups - Open PRs that edit the moved files rebase cleanly (git follows the renames), but new imports of the old module paths will break: #6309 (adds a delta transport that should live in `rl/transport/`), #6237, #6176, #6177, #5862, and drafts #6127, #6393, #6163, #5764. - The Actions bot can't read dependency source (e.g. SGLang); follow-up for the workflow. ## Self-review pr-review (branch mode) at ad905a5: Needs discussion. Fixed: branch mode diffs against `origin/main` and skips description findings before a description exists; the "Config doesn't read runtime state" rule no longer contradicts hardware validation; dismissal dropped as an override form (the bot can't tell who dismissed); `test_rdma_microbatch.py` added to the transport area. Not addressed: - One concern per PR -- the five changes ship together at the maintainer's request. - Open PRs touching the moved files -- listed above; the maintainer will coordinate.
## Summary (human-written) Our goal is to fully replace FSDP2 with FlexShard. This PR is the first step: it adds FlexShard as an experimental, opt-in backend while keeping FSDP2 as the default. This lets us test new FlexShard features and close feature gaps while users on FSDP2 see no change. ## Description torchtitan can shard parameters' storage only with FSDP2's `fully_shard`. This PR adds `parallelism.storage`, a `StorageConfig` (`torchtitan/distributed/storage.py`): how parameters are stored, sharded across ranks and gathered for compute. Tensor and expert parallelism also store parameters sharded, but they compute on the shards (`ShardingConfig`). A `StorageConfig` is a dataclass that owns the operations that depend on how the parameters are stored: validating the config, sharding a decoder and clipping grad norms. It holds no state, so callers use the config object itself, with no `build()`, and no code checks which one is in use. The default, `FullyShardConfig()`, keeps FSDP2. Setting it to `FlexShardConfig()` shards the model with FlexShard (meta-pytorch/flex_shard) instead. FSDP2's existing `fsdp_*` options stay on `ParallelismConfig` for now, so the FSDP2 path is unchanged. This is the first step of replacing FSDP2. It covers the case where the two backends can be compared bit for bit: decoders with data parallelism over `dp_shard` only. `ParallelismContext.from_config` keeps the config object itself. `Decoder._apply_fsdp` shards with it (`apply_to_decoder`) and `GradientClipper` clips with it, so grads are always clipped by the storage config that sharded them. `flex_shard` is imported only when it is selected. Later PRs in the stack add the operations they need to `StorageConfig` rather than checking which one is in use. `FullyShardConfig.apply_to_decoder` does what `Decoder._apply_fsdp` did before, through `apply_fsdp_to_decoder`: it calls `fully_shard` on the embedding, on the norm with the output projection, on each transformer block, and finally on the root model for any leftover parameters. `FlexShardConfig.apply_to_decoder` (`torchtitan/distributed/flex_shard_backend.py`) takes the same units from `decoder_sharding_units` and gives FlexShard one bucket for each. Each bucket uses its unit's mesh, shard dims and reshard-after-forward policy, the same param and reduce dtypes, `gradient_divide_factor=1.0` (gradients are summed, as `disable_fsdp_gradient_division` makes FSDP2 do) and `fsdp2_compatible=True`. The leftover root bucket, like FSDP2's root unit, isn't resharded after forward. As a result the two backends issue the same collectives, and training from the same parameters is bitwise identical. To keep the two backends from drifting apart, the grouping moved out of the FSDP2 loop into `decoder_sharding_units` in `fsdp.py`, which returns each unit's modules, reshard policy, and stacked-linear and routed-expert placements. The rest of `apply_fsdp_to_decoder` moved into `FullyShardConfig.apply_to_decoder`, which resolves the meshes and reads the dtypes and `fsdp_*` options from the configs it's given, and `apply_fsdp_to_decoder` is gone. Its embedding check, `_fsdp_unit_holds_only_embedding_weights`, which nothing else used, moved with it as `FullyShardConfig._unit_holds_only_embedding_weights`. `MTPDecoder._apply_fsdp`, which DeepSeek V3 and V4 share, already calls `Decoder._apply_fsdp`, so it shards through the storage config too. The FSDP2 path's behavior doesn't change. It now passes each unit to `fully_shard` as a list (`fully_shard([block])`), and FSDP2 gives a one-module list the same per-module hooks as the module itself. The embedding's `set_unshard_in_backward(False)` condition and the EP > 1 per-parameter mesh logic are the same as before. FlexShard parameters and their grads stay plain local shards: nothing on the FlexShard path creates a DTensor. torchtitan relied on FSDP2's DTensor parameters in two places, which now handle plain shards: - **Initialization.** Right after sharding, `FlexShardConfig.apply_to_decoder` wraps each FlexShard parameter's `param_init` function with flex_shard's `init_from_full` and the layout flex_shard reports for it (`get_flex_shard_global_layouts`). The wrapped function runs the init function on a full-size tensor and keeps this rank's part, so each shard is its slice of one device's initialization. `to_empty()` rebuilds FlexShard's parameters but keeps the modules, so the wrapped functions survive it, and `models/base` doesn't change. FSDP2's DTensor init draws each shard's values separately, so the two backends start from different, equally valid, weights. A module without `param_init` falls back to `reset_parameters()`, which would draw each FlexShard shard as the whole parameter, with the same values on every rank, so such modules are rejected (below). With tied weights, which #6144 keeps tied through parallelization, flex_shard reports the shared parameter under both names. `lm_head`'s function initializes it, and `tok_embeddings`' `skip_param_init` stays a no-op rather than being wrapped. Wrapped, it would copy an uninitialized full tensor into the shard, which `lm_head`'s function overwrites only because `tok_embeddings` initializes first. - **Grad-norm clipping.** `ParallelismContext` holds the storage config, and `GradientClipper` clips with its `clip_grad_norm_`. `FullyShardConfig`'s is `dist_utils.clip_grad_norm_`, moved there unchanged: FSDP2's clipping now lives with FSDP2, and `distributed/utils.py` no longer has the function. Both configs' methods keep its `norm_type` (L2 by default, so callers pass nothing) and `error_if_nonfinite`. `FlexShardConfig`'s groups the grads by their bucket's mesh (`flex_shard.get_mesh`) instead of by DTensor mesh. Its `_grad_norm` reduces each group's norm over its mesh in DTensor's order (each grad's local norm, all-reduced, then the norm of those norms), ported from flex_shard's DeepSeek V3 example, so the norm matches FSDP2's bit for bit. Combining the groups' norms, the PP reduction and clipping are in `StorageConfig._clip_grads_with_mesh_norms_`, which both configs call. FlexShard differs from FSDP2 in one way that affects memory and communication: FSDP2 skips the embedding's backward all-gather, and FlexShard can't yet, so it gathers the embedding again in backward. Anything FlexShard doesn't support yet raises a `ValueError` when the config is validated, after recipes and overrides and before distributed init. `validate_model_training_config` calls the storage config's `validate_model`, which checks the model, parallelism and training options. The checks of the loss, checkpointer, optimizers and trainer read configs that `validate_model_training_config` doesn't receive, so `TrainingEngine.Config.__post_init__` calls the storage config's `validate_trainer`, for every trainer. Both do nothing for `FullyShardConfig`. FlexShard's checks are temporary: each goes once FlexShard supports the feature. - **Parallelism:** HSDP, tensor, context, expert and pipeline parallelism. - **FSDP2 options:** symmetric-memory communication, CPU offloading, unsharding in the current stream (`fsdp_unshard_in_current_stream`), and deferred gradient reduction (`fsdp_defer_gradient_reduction`), since FlexShard has no `set_is_last_backward`. - **Model:** any model that overrides `_apply_fsdp` (multimodal models, DeepSeek V3 and V4, Flux and the transformers modeling backend); `preserve_dtype_params`; modules without `param_init` that have a `reset_parameters()`; and MXFP8/NVFP4 weights. All are read from the model config, so the `param_init` check also rejects modules that have no parameters to initialize, such as the `RMSNorm(elementwise_affine=False)` QK norms of muse_glimmer and muse_spark. - **Training features:** accelerator graphs, `ChunkedLossWrapper`, checkpointing, EMA, DistMuon, gradient clippers other than `GradientClipper` (only it is known to clip with the storage config's `clip_grad_norm_`) and SPMD typechecking. - **Trainers:** any trainer other than `torchtitan.trainer.Trainer`, including GraphTrainer, FaultTolerantTrainer and the RL trainer. `FlexShardConfig.validate_model` then raises an `ImportError` if flex_shard isn't installed, rather than failing when the model is sharded, after distributed init. The multi-GPU unit-test job installs flex_shard at a pinned commit (`d6bb546`), so the new parity test runs in CI. That test, `test_flex_shard_fsdp.py::test_matches_fsdp2`, runs on 4 GPUs. It builds each model with both backends and checks that each FlexShard shard equals its slice of one device's initialization from the same seed. It then copies FSDP2's initial parameters into the FlexShard model and requires bitwise-equal per-microbatch losses, grad norms, gradients and parameters over three AdamW steps, clipping through `GradientClipper`. It covers llama3 `debugmodel` with `fsdp_reshard_after_forward` set to default, qwen3 `debugmodel_moe` with always, and llama3 `debugmodel` with tied weights, set up as the tied Llama 3 flavors (1B, 3B) do, with default, each with two microbatches. A CPU test checks that `validate_model_training_config` rejects a model with its own `_apply_fsdp` (DeepSeek V4) instead of letting it silently shard with FSDP2, and a module without `param_init`. The existing FSDP2 tests cover the moved FSDP2 code, and their edits are mechanical. `test_fsdp.py` now expects `fully_shard([block])`. The tests that called `apply_fsdp_to_decoder` (`test_fsdp.py`, `test_parallelism_context.py`, `test_fsdp_cpu_offload.py` and `test_fsdp_moe_sharding.py`) call `FullyShardConfig().apply_to_decoder` with configs, and patch mesh resolution to return their meshes. The optimizer and trainer unit tests that stub `clip_grad_norm_` now give their fake parallelism contexts a `FullyShardConfig`, and `test_distributed_utils.py`'s test of it moved to `test_storage.py`. This revision passes the parity test on 2 GB200 GPUs with `world_size` set to 2, and `test_fsdp_cpu_offload.py` on GB200; `test_fsdp_moe_sharding.py` needs 4 to 8 GPUs and wasn't rerun. An earlier revision also passed the parity test, except the tied case, on 4 GB300 GPUs. On an earlier revision of this PR, based on `4122eafc0`, the FSDP2 path matched its base bit for bit: `scripts/loss_compare.py 4122eaf <that revision> --assert-equal --metrics loss,grad_norm` (seed 42, deterministic, 50 steps, 2 GB200 GPUs, `dp_shard=2`) reports equal loss and grad norm at every step for llama3 `debugmodel` (step-50 loss 2.86823), for llama3 `debugmodel` with two microbatches per step and `fsdp_defer_gradient_reduction=True` (2.83577), and for qwen3 `moe_debug` (3.71935). These runs use flex attention because the environment has no FA4, and skip the seed checkpoint, since both runs of each pair start from seed 42 with the same parallelism. Expert parallelism is the next PR in the stack. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: 074a693 Pull-Request: #5842
## Summary (human-written) Our goal is to fully replace FSDP2 with FlexShard. This PR is the first step: it adds FlexShard as an experimental, opt-in backend while keeping FSDP2 as the default. This lets us test new FlexShard features and close feature gaps while users on FSDP2 see no change. ## Description torchtitan can shard parameters' storage only with FSDP2's `fully_shard`. This PR adds `parallelism.storage`, a `StorageConfig` (`torchtitan/distributed/storage.py`): how parameters are stored, sharded across ranks and gathered for compute. Tensor and expert parallelism also store parameters sharded, but they compute on the shards (`ShardingConfig`). A `StorageConfig` is a dataclass that owns the operations that depend on how the parameters are stored: validating the config, sharding a decoder and clipping grad norms. It holds no state, so callers use the config object itself, with no `build()`, and no code checks which one is in use. The default, `FullyShardConfig()`, keeps FSDP2. Setting it to `FlexShardConfig()` shards the model with FlexShard (meta-pytorch/flex_shard) instead. FSDP2's existing `fsdp_*` options stay on `ParallelismConfig` for now, so the FSDP2 path is unchanged. This is the first step of replacing FSDP2. It covers the case where the two backends can be compared bit for bit: decoders with data parallelism over `dp_shard` only. `ParallelismContext.from_config` keeps the config object itself. `Decoder._apply_fsdp` shards with it (`apply_to_decoder`) and `GradientClipper` clips with it, so grads are always clipped by the storage config that sharded them. `flex_shard` is imported only when it is selected. Later PRs in the stack add the operations they need to `StorageConfig` rather than checking which one is in use. `FullyShardConfig.apply_to_decoder` does what `Decoder._apply_fsdp` did before, through `apply_fsdp_to_decoder`: it calls `fully_shard` on the embedding, on the norm with the output projection, on each transformer block, and finally on the root model for any leftover parameters. `FlexShardConfig.apply_to_decoder` (`torchtitan/distributed/flex_shard_backend.py`) takes the same units from `decoder_sharding_units` and gives FlexShard one bucket for each. Each bucket uses its unit's mesh, shard dims and reshard-after-forward policy, the same param and reduce dtypes, `gradient_divide_factor=1.0` (gradients are summed, as `disable_fsdp_gradient_division` makes FSDP2 do) and `fsdp2_compatible=True`. The leftover root bucket, like FSDP2's root unit, isn't resharded after forward. As a result the two backends issue the same collectives, and training from the same parameters is bitwise identical. To keep the two backends from drifting apart, the grouping moved out of the FSDP2 loop into `decoder_sharding_units` in `fsdp.py`, which returns each unit's modules, reshard policy, and stacked-linear and routed-expert placements. The rest of `apply_fsdp_to_decoder` moved into `FullyShardConfig.apply_to_decoder`, which resolves the meshes and reads the dtypes and `fsdp_*` options from the configs it's given, and `apply_fsdp_to_decoder` is gone. Its embedding check, `_fsdp_unit_holds_only_embedding_weights`, which nothing else used, moved with it as `FullyShardConfig._unit_holds_only_embedding_weights`. `MTPDecoder._apply_fsdp`, which DeepSeek V3 and V4 share, already calls `Decoder._apply_fsdp`, so it shards through the storage config too. The FSDP2 path's behavior doesn't change. It now passes each unit to `fully_shard` as a list (`fully_shard([block])`), and FSDP2 gives a one-module list the same per-module hooks as the module itself. The embedding's `set_unshard_in_backward(False)` condition and the EP > 1 per-parameter mesh logic are the same as before. FlexShard parameters and their grads stay plain local shards: nothing on the FlexShard path creates a DTensor. torchtitan relied on FSDP2's DTensor parameters in two places, which now handle plain shards: - **Initialization.** Right after sharding, `FlexShardConfig.apply_to_decoder` wraps each FlexShard parameter's `param_init` function with flex_shard's `init_from_full` and the layout flex_shard reports for it (`get_flex_shard_global_layouts`). The wrapped function runs the init function on a full-size tensor and keeps this rank's part, so each shard is its slice of one device's initialization. `to_empty()` rebuilds FlexShard's parameters but keeps the modules, so the wrapped functions survive it, and `models/base` doesn't change. FSDP2's DTensor init draws each shard's values separately, so the two backends start from different, equally valid, weights. A module without `param_init` falls back to `reset_parameters()`, which would draw each FlexShard shard as the whole parameter, with the same values on every rank, so such modules are rejected (below). With tied weights, which #6144 keeps tied through parallelization, flex_shard reports the shared parameter under both names. `lm_head`'s function initializes it, and `tok_embeddings`' `skip_param_init` stays a no-op rather than being wrapped. Wrapped, it would copy an uninitialized full tensor into the shard, which `lm_head`'s function overwrites only because `tok_embeddings` initializes first. - **Grad-norm clipping.** `ParallelismContext` holds the storage config, and `GradientClipper` clips with its `clip_grad_norm_`. `FullyShardConfig`'s is `dist_utils.clip_grad_norm_`, moved there unchanged: FSDP2's clipping now lives with FSDP2, and `distributed/utils.py` no longer has the function. Both configs' methods keep its `norm_type` (L2 by default, so callers pass nothing) and `error_if_nonfinite`. `FlexShardConfig`'s groups the grads by their bucket's mesh (`flex_shard.get_mesh`) instead of by DTensor mesh. Its `_grad_norm` reduces each group's norm over its mesh in DTensor's order (each grad's local norm, all-reduced, then the norm of those norms), ported from flex_shard's DeepSeek V3 example, so the norm matches FSDP2's bit for bit. Combining the groups' norms, the PP reduction and clipping are in `StorageConfig._clip_grads_with_mesh_norms_`, which both configs call. FlexShard differs from FSDP2 in one way that affects memory and communication: FSDP2 skips the embedding's backward all-gather, and FlexShard can't yet, so it gathers the embedding again in backward. Anything FlexShard doesn't support yet raises a `ValueError` when the config is validated, after recipes and overrides and before distributed init. `validate_model_training_config` calls the storage config's `validate_model`, which checks the model, parallelism and training options. The checks of the loss, checkpointer, optimizers and trainer read configs that `validate_model_training_config` doesn't receive, so `TrainingEngine.Config.__post_init__` calls the storage config's `validate_trainer`, for every trainer. Both do nothing for `FullyShardConfig`. FlexShard's checks are temporary: each goes once FlexShard supports the feature. - **Parallelism:** HSDP, tensor, context, expert and pipeline parallelism. - **FSDP2 options:** symmetric-memory communication, CPU offloading, unsharding in the current stream (`fsdp_unshard_in_current_stream`), and deferred gradient reduction (`fsdp_defer_gradient_reduction`), since FlexShard has no `set_is_last_backward`. - **Model:** any model that overrides `_apply_fsdp` (multimodal models, DeepSeek V3 and V4, Flux and the transformers modeling backend); `preserve_dtype_params`; modules without `param_init` that have a `reset_parameters()`; and MXFP8/NVFP4 weights. All are read from the model config, so the `param_init` check also rejects modules that have no parameters to initialize, such as the `RMSNorm(elementwise_affine=False)` QK norms of muse_glimmer and muse_spark. - **Training features:** accelerator graphs, `ChunkedLossWrapper`, checkpointing, EMA, DistMuon, gradient clippers other than `GradientClipper` (only it is known to clip with the storage config's `clip_grad_norm_`) and SPMD typechecking. - **Trainers:** any trainer other than `torchtitan.trainer.Trainer`, including GraphTrainer, FaultTolerantTrainer and the RL trainer. `FlexShardConfig.validate_model` then raises an `ImportError` if flex_shard isn't installed, rather than failing when the model is sharded, after distributed init. The multi-GPU unit-test job installs flex_shard at a pinned commit (`d6bb546`), so the new parity test runs in CI. That test, `test_flex_shard_fsdp.py::test_matches_fsdp2`, runs on 4 GPUs. It builds each model with both backends and checks that each FlexShard shard equals its slice of one device's initialization from the same seed. It then copies FSDP2's initial parameters into the FlexShard model and requires bitwise-equal per-microbatch losses, grad norms, gradients and parameters over three AdamW steps, clipping through `GradientClipper`. It covers llama3 `debugmodel` with `fsdp_reshard_after_forward` set to default, qwen3 `debugmodel_moe` with always, and llama3 `debugmodel` with tied weights, set up as the tied Llama 3 flavors (1B, 3B) do, with default, each with two microbatches. A CPU test checks that `validate_model_training_config` rejects a model with its own `_apply_fsdp` (DeepSeek V4) instead of letting it silently shard with FSDP2, and a module without `param_init`. The existing FSDP2 tests cover the moved FSDP2 code, and their edits are mechanical. `test_fsdp.py` now expects `fully_shard([block])`. The tests that called `apply_fsdp_to_decoder` (`test_fsdp.py`, `test_parallelism_context.py`, `test_fsdp_cpu_offload.py` and `test_fsdp_moe_sharding.py`) call `FullyShardConfig().apply_to_decoder` with configs, and patch mesh resolution to return their meshes. The optimizer and trainer unit tests that stub `clip_grad_norm_` now give their fake parallelism contexts a `FullyShardConfig`, and `test_distributed_utils.py`'s test of it moved to `test_storage.py`. This revision passes the parity test on 2 GB200 GPUs with `world_size` set to 2, and `test_fsdp_cpu_offload.py` on GB200; `test_fsdp_moe_sharding.py` needs 4 to 8 GPUs and wasn't rerun. An earlier revision also passed the parity test, except the tied case, on 4 GB300 GPUs. On an earlier revision of this PR, based on `4122eafc0`, the FSDP2 path matched its base bit for bit: `scripts/loss_compare.py 4122eaf <that revision> --assert-equal --metrics loss,grad_norm` (seed 42, deterministic, 50 steps, 2 GB200 GPUs, `dp_shard=2`) reports equal loss and grad norm at every step for llama3 `debugmodel` (step-50 loss 2.86823), for llama3 `debugmodel` with two microbatches per step and `fsdp_defer_gradient_reduction=True` (2.83577), and for qwen3 `moe_debug` (3.71935). These runs use flex attention because the environment has no FA4, and skip the seed checkpoint, since both runs of each pair start from seed 42 with the same parallelism. Expert parallelism is the next PR in the stack. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: 074a693 Pull-Request: #5842
Stack from ghstack (oldest at bottom):
Summary (human-written)
Why
Module._spmd_distribute_stateregisters a newnn.Parameterin every module it distributes. So_parallelizeuntiestok_embeddings.weightandlm_head.weightin every decoder withenable_weight_tying=True(Qwen3 debugmodel/0.6B/1.7B/4B, Llama 3 1B/3B, Qwen3.5 0.8B/2B/4B) before FSDP sees the model.Decoder.init_statesties them again, but only afterto_empty(). FSDP2 therefore gets two parameters for one weight in the group[tok_embeddings, norm, lm_head](three FSDPParams instead of two). Three problems follow:When FSDP pads the tied weight's shard, the embedding trains on a stale copy. Padding happens when
(vocab / tp) % (dp_shard * cp) != 0. At lazy init,FSDPParam.reset_sharded_paramre-reads the module parameters. The embedding's FSDPParam pads a private copy oflm_head's local shard. Thenlm_head's FSDPParam pads a second copy and points the parameter at it. The optimizer updateslm_head's copy, but the embedding keeps all-gathering its own, so the embedding rows on every rank with a padded shard never change. This affects:Without padding, FSDP2 communicates the tied weight twice. It all-gathers both copies in every unshard. With
lm_headin the model forward it also reduce-scatters both. Grouping the three modules was meant to avoid exactly this (see the comment inapply_fsdp_to_decoder).Sharders that don't re-read parameters train silently wrong. A sharder that keeps the parameters it was given at wrap time trains the embedding with a weight the optimizer doesn't hold. FlexShard is one: Add parallelism.storage to shard decoders with FlexShard #5842 rejects tied weights and depends on this fix.
Example. Tied Qwen3 debugmodel with vocab 2049, FSDP 2, on GPU. Rank 1 holds 1024 rows, padded to 1025. Per rank, after each optimizer step: does each FSDPParam of the tied group all-gather the live parameter?
Tie state at each lifecycle stage (Qwen3 debugmodel, FSDP 2 or TP 2). Is
tok_embeddings.weight is lm_head.weighttrue?What changed
Decoder._parallelize(5 lines). It callssuper()._parallelizeand then, ifenable_weight_tyingis set, pointstok_embeddings.weightatlm_head.weightagain.self._parallelize:MultimodalModel,KimiK3Model, the GraphTrainer models and the vLLM generator. No decoder overrides_parallelize.Decoder.Config.__post_init__raisesValueErrorif a tied config givestok_embeddingsandlm_headdifferent weight shardings (sharding_config.state_shardings["weight"])._parallelizeon, the embedding useslm_head's distributed weight, so a mismatch would otherwise be silently wrong.dense_param_placement(tp=spmd.S(0))for both (vocab-sharded on TP, Replicate on DP and CP), so their local shards match under TP.Decoder.init_stateskeeps its re-tie (comment-only change).to_empty()changes parameters in place and keeps the tie, so FSDP2 no longer needs it.data_parallelregisters new parameters after_parallelize, which unties the weights again. Without the re-tie, the embedding would keep the storage thatskip_param_initnever initializes.enable_weight_tyingdocstring now lists_parallelizetoo.tests/unit_tests/cpu/models/llama3/test_weight_tying.py(see Testing). Thedataclassesimport moved to the top of that file.Alternatives considered
Module._parallelize/_spmd_distribute_state. The recursion shares no state across modules, so this needs alias bookkeeping at the entry point plus a check that every alias got the same layout: about 20 lines, with one consumer. I built all 59 flavors of the 12 in-repo decoder families on meta. The only shared parameter in any of them istok_embeddings.weight/lm_head.weight. The HF-backend experiment unties these before_parallelize.Decoder._apply_fsdp. That also runs beforefully_shardand would work for FSDP2, but only for callers that go through_apply_fsdp. Re-tying where_parallelizebreaks the tie covers every caller, including GraphTrainer and the vLLM generator.init_states. It isn't redundant (SimpleFSDP, above).Numerics
These runs predate the rebase onto
4122eafc0and were made against main9f70e5597. The rebase crosses #5802 (VocabParallelEmbedding, the TP gather after the final norm); at4122eafc0I reran the new tests, the tied-flavor check and the padded-shard GPU probe (see Testing), not the runs below. GPU runs: seed 42, deterministic, 2x GB200,scripts/loss_compare.py <main> <this PR> --metrics loss,grad_norm --no-seed-checkpoint. All use flex attention (FA4 isn't installed locally). CPU runs use gloo, Qwen3 debugmodel and ChunkedLossWrapper, and run 4 steps (adapted from the reviewer's script).--assert-equal--assert-equalenable_weight_tying, FSDP 2dp_shard=3dp_shard=2lm_headin forward)Padded shards: numerics change because main is wrong. On main, the embedding's rows on the padded ranks stay at their initial values (Example). This PR trains them. In the GPU vocab-2049 run, the mean absolute loss difference is 6.4e-5, 2.3e-4, 9.5e-4 and 1.0e-3 over steps 1-25, 26-50, 51-75 and 76-100 (max 2.9e-3).
Unpadded shards with ChunkedLossWrapper (used by every in-repo recipe for a tied flavor): bitwise unchanged. This holds with the default per-microbatch reduction.
lm_headruns in the loss's own backward passes.fsdp_partial_backwardsreduce-scatters the tied group after the last of them, before the decoder backward computes the embedding's gradient..grad.Gradient accumulation with deferred reduction, or HSDP: fp32 rounding-level change. With gradient accumulation plus
fsdp_defer_gradient_reduction=True, or with HSDP (whose replica all-reduceTrainingEnginedefers to the last microbatch), both uses' gradients are summed before a single reduction. The tied gradient then changes at fp32 rounding level. At step 0 on CPU the max difference is 3.4e-8 (FSDP 2, GA 2, deferred) and 3.7e-9 (HSDP 2x2, GA 2). No in-repo tied recipe uses either.Unpadded shards with
lm_headin the forward: the tied gradient changes at bf16 level.reduce_dtype(FSDPParam.defers_grad_upcast), so autograd adds the embedding's andlm_head's bf16 contributions into one bf16 gradient, which is widened and reduce-scattered once.In the table below, each step-range cell is the mean absolute loss difference over that range. The signed mean is this PR minus main; for the reference row it is CrossEntropyLoss minus ChunkedLossWrapper.
Golden losses. No file in
tests/assets/losses/trains a tied model exceptrl_grpo_cuda.txt.rl_grpo_cuda.txtis the RL loss guard: tied Qwen3-0.6B, ChunkedLossWrapper, trainer TP 4, FSDP degree 1, so no padding. It should stay the same, but I couldn't run it (it needs 8 GPUs, vLLM and HF weights).qwen3goldens use the untieddebugmodel_moe. Thellama3andsftgoldens use the untied Llama 3 debugmodel.Performance
Bytes per rank per step for the tied group: all-gather output and reduce-scatter input. Qwen3 debugmodel (vocab 2048, dim 256), FSDP 2, counted by wrapping FSDP2's collectives inside the trainer.
With ChunkedLossWrapper, reduce-scatter bytes don't change. The group is reduced once after the loss's backward and once after the decoder backward (as the untied
[norm, lm_head]group is), and the tied weight's gradient is in both reductions either way.Testing
4122eafc0) and pass here.test_weights_remain_tied_after_parallelizebuilds a tied Llama 3 debugmodel on meta, runs_parallelizewith TP 2 on a fake process group, and assertstok_embeddings.weight is lm_head.weight. It catches any change that unties the weights between_parallelizeand FSDP.test_tying_rejects_different_weight_shardingsgiveslm_heada different weight sharding and expectsValueError._parallelizeon main and tied here (rechecked at4122eafc0)._parallelize.4122eafc0, 3 steps: rank 1's embedding FSDPParam is unchanged after steps 2 and 3 on main) and CPUdp_shard=3. On main, the padded rank's embedding FSDPParam holds a private, never-updated copy. Here every FSDPParam all-gathers the live parameter.apply_simple_fsdpunties the weights;init_statesties them again, and without that re-tie they stay untied.9f70e5597).pytest tests/unit_tests/cpu/{models,distributed,config}plustests/unit_tests/cpu/components/test_chunked_loss_fsdp.py: 850 passed here. On main the first three suites gave 847 passed; the 3 extra here are the two new tests andtest_chunked_loss_fsdp.py.transformersmissing, spmd_types 0.2.0 instead of the pinned 0.3.1, andtorch_checkpointing/renderersversions.Known issues / follow-ups
qwen3_fsdp+tp+cp_no_sptrains the tied Qwen3 debugmodel that way).parallelize, and its_fsdp_load_groupsalready maps both tied keys to the shared FSDPParam.data_parallel(torchtitan/experiments/graph_trainer/simple_fsdp.py) keep shared parameters tied? Then the re-tie inDecoder.init_states, and its comment naming an experiment, could go.