Repository navigation
Conversation
…FlexShardConfig() Stacked on #5842, the expert-parallelism PR, the chunked-loss PR, the checkpointing PR and the Hugging Face load PR. <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> `validate_flex_shard_training` rejects `tensor_parallel_degree > 1` and `context_parallel_degree > 1`, so no recipe that uses TP or CP can run with FlexShard. FlexShard's path takes a 1D `dp_shard` mesh (`apply_flex_shard_to_decoder` asserts it). FSDP2 handles TP and CP through the storage mesh and the parameters' SPMD types (`fully_shard(..., dp_mesh_dims=...)`), so FlexShard buckets over `dp_shard` alone would train wrong without an error: - **CP:** each cp rank's grads cover its own tokens. FSDP2 shards over `dp_shard` and `cp` flattened into one axis, so its reduce-scatter sums them. Buckets over `dp_shard` alone would never sum the cp ranks' grads. - **TP:** `Module._parallelize` hands FlexShard each tp rank's plain local shard. - A parameter typed `R` on tp has a grad that's partial over tp: the norm weights under sequence parallelism, Qwen3's QK norms and its router gate. FSDP2 types such a grad `P` and all-reduces it over tp before its reduce-scatter. FlexShard would keep each tp rank's part. - Initialization, grad-norm clipping and Hugging Face loads view each FlexShard parameter as FSDP2's DTensor (`as_fsdp2_dtensor`, #5842). They'd see each tp rank's shard as the whole parameter, so initialization wouldn't match FSDP2's and the grad norm would leave out the other tp ranks' shards. - Checkpoints would save each tp rank's shard as the whole tensor. **Example.** ```python config = llama3_debugmodel(attn_backend="flex") config.parallelism.tensor_parallel_degree = 2 # or CP, with ContextParallelTransform config.training.disable_accelerator_graphs = True config.parallelism.fsdp_backend = FlexShardConfig() ``` How a Llama 3 debug block is laid out with `dp_shard=2, tp=2`, and with `dp_shard=2, cp=2`: | Parameter | FSDP2 (unchanged): DTensor on `(dp_shard, tp)` | FlexShard (this PR) | | --- | --- | --- | | `wqkv.weight` `[768, 256]`, TP splits dim 0 | `(_StridedShard(0, 2), Shard(0))` | the bucket on `dp_shard` splits the tp rank's `[384, 256]` on dim 0; the TP layout places it in rows `[384 * tp_rank, ...)` | | `wo.weight` `[256, 256]`, TP splits dim 1 | `(Shard(0), Shard(1))` | the bucket splits `[256, 128]` on dim 0; the TP layout is on dim 1 | | `attention_norm.weight` `[256]`, sequence parallel: `R` on tp | `(Shard(0), Replicate())`; the grad is `P` on tp and all-reduced over tp before the reduce-scatter | tp is its partial-grad group: the same all-reduce, at the same point, in fp32 | | `attention_norm.weight`, no sequence parallelism: `I` on tp | `(Shard(0), Replicate())`, no all-reduce | nothing declared | | any parameter, with `cp=2` | `Shard(d)` on `dp_shard_cp`, which `fully_shard` flattens from `(dp_shard, cp)` | buckets on the same flattened mesh, the same process group | - **Mesh (`torchtitan/distributed/flex_shard_fsdp.py`, `apply_flex_shard_to_decoder`).** It takes the storage mesh and `dp_mesh_dims` from `resolve_fsdp_mesh`, as `apply_fsdp_to_decoder` does, in place of a 1D `dp_shard` mesh (`Decoder._apply_fsdp` passes them). The buckets shard over the mesh `fully_shard` shards over: `dp_shard`, or with CP, `storage_mesh[("dp_shard", "cp")]._flatten("dp_shard_cp")`. `DeviceMesh` caches a flattened mesh by name, so both backends reduce on one process group. `decoder_fsdp_groups` gets the storage mesh too, so routed experts without EP shard over `dp_shard * cp` as in FSDP2. - **TP declarations (`_declare_tensor_parallelism`, new).** Before `flex_shard()`, it reads each parameter's SPMD type, which is what FSDP2 lays the parameter out by: - A parameter TP splits is typed `V` on tp, with its dim in the `PartitionSpec`. It declares its layout through flex_shard's spmd_types adapter (`spmd_types_to_global_layout`), and FlexShard composes it with the bucket's split, as for the EP layout (checkpointing PR). - A parameter typed `R` on tp declares the tp group as its partial-grad group (`set_partial_grad_group`). FlexShard all-reduces its unsharded grad over that group before the reduce-scatter, in the grad's dtype. Like FSDP2 (`may_reduce_grad_outside_dp`), it keeps these grads out of the deferred upcast, so with bf16 parameters the sum runs in fp32. The group is the storage mesh's tp group, the one FSDP2's redistribute uses. - Routed experts are skipped. MoE models need `ep >= tp`, so they're typed on the sparse mesh, whose `ep` axis can span the same ranks as `tp`, and keep the EP layout. - **DTensor view (`as_fsdp2_dtensor`).** Under TP, a dense parameter's view is on FSDP2's mesh: `(dp_shard, tp)`, or `(dp_shard_cp, tp)` with CP (`DeviceMesh._concatenate`, as `fully_shard` builds it). On tp it's `Shard(d)` for the dim the TP layout splits (`get_outer_layout`), else `Replicate()`. On the first axis it's `_StridedShard(d, tp)` when the bucket splits the same dim. The global shape is the full one. As for routed experts (expert-parallelism PR), a module-level map gives the mesh, keyed by the buckets' mesh, because `to_empty()` replaces the parameters. Initialization, `clip_grad_norm_` and HF loads already go through the view, so they need no change. With CP alone, FSDP2's DTensors are on the flattened mesh, which is the bucket's mesh, so the view doesn't change. - **Validation (`validate_flex_shard_training`).** It no longer rejects TP or CP, with or without sequence parallelism, alone, together or with EP. The `fsdp_backend` docstring (`torchtitan/config/parallelism.py`) says so. - **Tests:** see Testing. - **Derive the TP layouts and partial-grad groups from each module's `_sharding_config`**, as the FlexShard fork does. It reads other modules' private config. The parameters' own SPMD types are what FSDP2 reads, so both backends follow one source. - **Compute the TP layout by hand**, like the EP layout. TP-split parameters are typed `V` on tp with the dim in their `PartitionSpec`, not `S(d)`, so that means parsing PartitionSpecs. flex_shard's adapter does it, and raises for types it can't express. - **Keep rejecting TP and CP together**, as the fork first did. The code is the same as for either alone, and the combination is tested on 4 GPUs. - **Record each parameter's TP placement on it for the view.** `to_empty()` replaces FlexShard's parameters before initialization. FlexShard keeps the declared layout through `to_empty()`, so the view reads it. | Before | After | | --- | --- | | `fsdp_backend=FlexShardConfig()` with `tensor_parallel_degree > 1` or `context_parallel_degree > 1` raises `ValueError` | accepted for decoders that use `Decoder._apply_fsdp` (Llama 3, Qwen3, GPT-OSS), with or without sequence parallelism, and with EP; training is bitwise identical to FSDP2 | | | HSDP, pipeline parallelism and SPMD type checking still raise, and models with their own `_apply_fsdp` (DeepSeek V3/V4, Kimi, multimodal models) are still rejected | All runs: seed 42, deterministic, accelerator graphs off (FlexShard rejects them), flex attention (FA4 isn't installed on the test machine; CP converts it to `AllGatherKVFlexInnerAttention`, and GPT-OSS's sliding-window layers to `AllGatherKVSlidingWindowFlexInnerAttention`), the recipes' `ChunkedLossWrapper`, torch `2.16.0a0+gita66bab0`, flex_shard `d6bb546` (the commit CI pins), spmd_types 0.3.1 (the pin; the test machine's 0.2.0 breaks TP and CP under either backend). Every run is at `4aa9fed1c`, an earlier version of this commit whose non-test code differs from it only in comments, on an earlier version of the HF-load PR that also differs only in comments. **FlexShard matches FSDP2.** On 2 GPUs: `scripts/loss_compare.py <this commit> <this commit> --baseline-config <FSDP2> --test-config <FlexShard> --assert-equal --metrics loss,grad_norm`. On 4 GPUs: one torchrun training job per backend on MAST, TensorBoard scalars compared exactly. | Config | GPUs | Result | | --- | --- | --- | | Llama 3 debug, `tp=2`, sequence parallel | 2x GB200 | loss and grad_norm bitwise identical, 50 steps (step-50 loss 2.94190); also from a seed checkpoint, 20 steps | | Llama 3 debug, `tp=2`, no sequence parallelism | 2x GB200 | same, 50 steps (2.94192) | | Llama 3 debug, `cp=2` | 2x GB200 | same, 50 steps (2.94029); also from a seed checkpoint, 20 steps | | Qwen3 MoE debug, `tp=2, ep=2`, sequence parallel | 2x GB200 | same, 50 steps (3.73420); also from a seed checkpoint, 20 steps | | Qwen3 MoE debug, `tp=2, ep=2`, no sequence parallelism | 2x GB200 | same, 50 steps (3.73244) | | Qwen3 MoE debug, `cp=2` (routed experts on `dp_shard_cp`) | 2x GB200 | same, 50 steps (3.72928); also from a seed checkpoint, 20 steps | | GPT-OSS debug, `tp=2, ep=2` (TP also splits the attention sinks and biases) | 2x GB200 | same, 50 steps (3.04097) | | GPT-OSS debug, `cp=2` | 2x GB200 | same, 50 steps (3.05864) | | Llama 3 debug, `dp_shard=2, tp=2` | 4x GB300 | loss, max loss and grad_norm bitwise identical, 20 steps | | Llama 3 debug, `dp_shard=2, cp=2` | 4x GB300 | same | | Llama 3 debug, `cp=2, tp=2` | 4x GB300 | same | | Qwen3 MoE debug, `dp_shard=2, tp=2, ep=2` (`edp_shard=2`) | 4x GB300 | loss, max loss, grad_norm and load-balance loss bitwise identical, 20 steps | | Qwen3 MoE debug, `dp_shard=2, cp=2` | 4x GB300 | same | On 2 GPUs, TP or CP leaves `dp_shard=1`. The TP runs then check the TP all-reduces and layouts but not the reduce-scatters, which the 4-GPU runs add. The 50-step runs skip the seed checkpoint, so FlexShard initializes through its DTensor views. The 20-step runs use `loss_compare`'s seed checkpoint, made on 1 GPU from the same model without TP or CP (`--seed-config`), so FlexShard loads a full-tensor DCP checkpoint into TP- or CP-sharded parameters. Peak memory, FlexShard vs FSDP2: Llama 3 within 0.04 GiB (0.50 vs 0.54 GiB at `tp=2`), Qwen3 MoE 3.22 vs 3.81 GiB at `tp=2, ep=2` and 3.74 vs 3.87 GiB at `cp=2`. **FSDP2 is unchanged.** `scripts/loss_compare.py <HF-load PR> <this commit> --baseline-config <FSDP2> --assert-equal --metrics loss,grad_norm --no-seed-checkpoint --steps 50`, in a scratch clone, 2x GB200: | Config | Result | | --- | --- | | Llama 3 debug, `tp=2`, sequence parallel | loss and grad_norm bitwise identical, 50 steps | | Llama 3 debug, `tp=2`, no sequence parallelism | same | | Llama 3 debug, `cp=2` | same | | Qwen3 MoE debug, `tp=2, ep=2` | same | | Qwen3 MoE debug, `cp=2` | same | FSDP2's code doesn't change: `Decoder._apply_fsdp` only passes one more argument on the FlexShard branch. Run on 2x GB200 with torch `2.16.0a0+gita66bab0`, flex_shard `d6bb546` and spmd_types 0.3.1, and on 4x GB300 (MAST) with another torch `2.16.0a0` build, the same flex_shard and spmd_types. At this commit: the 2-rank run of the test file, the CP with EP check, and the reverts as caught by the TP-without-sequence-parallelism and CP tests. The rest ran at `4aa9fed1c` (see Numerics), whose test file also ran Llama 3 in those two tests. - **New tests in `tests/unit_tests/gpu/distributed/test_flex_shard_fsdp.py`.** Each builds both backends through `model.parallelize` and requires bitwise-equal initialization, per-microbatch losses, clipped grad norms, local grads and AdamW-updated parameters over 3 steps, with 1 microbatch and with 2 and deferred gradient reduction, as the existing parity tests do. | Test | Models | Layout at 4 ranks (CI) | | --- | --- | --- | | `test_matches_fsdp2_with_tensor_parallelism` | Llama 3 debug, Qwen3 MoE debug (`ep=2`), sequence parallel, `ChunkedLossWrapper` | `dp_shard=2, tp=2` (Qwen3's experts: `edp_shard=2`) | | `test_matches_fsdp2_with_tensor_parallelism_without_sequence_parallelism` | Qwen3 MoE debug (`ep=2`), CE loss | `dp_shard=2, tp=2` | | `test_matches_fsdp2_with_context_parallelism` | Qwen3 MoE debug, `ep=1`, CE loss | `dp_shard=2, cp=2` | | `test_matches_fsdp2_with_tensor_and_context_parallelism` | Llama 3 debug, sequence parallel, `ChunkedLossWrapper` | `cp=2, tp=2` | | `test_checkpoints_across_backends_with_tensor_parallelism` | Llama 3 debug, sequence parallel: the checkpointing PR's check (checkpoints equal FSDP2's; each backend resumes from the other's) and the HF-load PR's (FlexShard loads FSDP2's HF export) | `dp_shard=2, tp=2` | The CP test also covers Qwen3's routed experts sharded over `dp_shard * cp` without EP. The checkpoint test also compares the optimizer states, which the checkpoints hold. - **Harness changes (mechanical, all tests).** As the trainer does, the loss is torchtitan's `CrossEntropyLoss` (vocab-parallel under TP) instead of `F.cross_entropy`, inputs are preprocessed inside `activate_spmd()` so CP shards them, the tp and cp ranks of a data-parallel rank share its data, CP models get `ContextParallelTransform` (`AllGatherKVFlexInnerAttention`) and a 128-token block per cp rank, and `_parallelism_context` takes `tp`, `cp` and `sequence_parallel`. - **Each change is guarded.** With each of these reverted, these tests fail: | Reverted | Fails | | --- | --- | | the partial-grad declarations | both TP parity tests, at step 0's grad norm: Llama 3 with sequence parallelism, and Qwen3 (QK norms, router) without it | | the TP layouts | both TP parity tests and the TP checkpoint test, at initialization: the fused QKV weight's init sees the tp rank's shape | | only the TP layouts' offsets (zeroed; the views keep their shapes) | the TP checkpoint test: its chunks differ from FSDP2's | | the TP mesh in `as_fsdp2_dtensor` | both TP parity tests, at initialization | | `_StridedShard` in the view (`Shard` instead) | `test_matches_fsdp2_with_tensor_parallelism` at 4 ranks, at the initialization of `wqkv.weight`. At 2 ranks (`dp_shard=1`) the two can't be told apart | | the flattened CP mesh (buckets on `dp_shard` alone) | the CP parity test, at initialization | - **Results.** - 2 ranks on GB200: 8 of the file's 9 tests pass, with `world_size` set to 2; the TP+CP test needs 4 ranks. At 2 ranks, TP alone leaves `dp_shard=1`, where neither backend reduce-scatters, so for that run the reduce-scatter-count check's floor is 0. - 4 ranks on GB300: the 5 new tests pass (at `4aa9fed1c`, with Llama 3 also in the TP-without-sequence-parallelism and CP tests). Each runs as its own torchrun job that calls the test method directly, because `MultiProcessTestCase` doesn't run on those hosts. - CP with EP, which validation now accepts: Qwen3 MoE debug at `cp=2, ep=2`, with 1 microbatch and with 2, is bitwise equal to FSDP2 under the parity tests' check at 2 ranks on 2x GB200 (a one-off run of `_check_matches_fsdp2`, not added to the file). - **CPU suites:** `cpu/config`, `cpu/components`, `cpu/distributed`, `cpu/models/base`, `cpu/scripts` and `test_trainer.py`, with GPUs hidden and the pinned torch_checkpointing 0.1.1 and spmd_types 0.3.1: 1011 passed. The 4 failures and 2 collection errors are the same on the base in this environment: three subtests of `test_lora_head_only_matches_cross_entropy` (an Inductor CPU flex-attention error), `test_hf_backend_renders_generation_tags`, and the `test_renderer` and `test_validator` collection errors (local dependencies older than the pins or missing). - **Lint:** pre-commit passes on the changed files (flake8, ufmt, pydoclint, codespell, license). pyrefly 0.45.1 reports the same 12 errors as the base. - **SPMD type checking (`debug.spmd_typechecking`) stays rejected.** The fork enables it on a flex_shard change that runs FlexShard's hooks outside the type checker; it needs its own check against FSDP2 under the checker. - **Other models' TP-replicated parameters.** Kimi K3's `tp_unsharded_weight_sharding_config` and DeepSeek V4's compressor also rely on FSDP2 all-reducing `R`-typed grads over tp. `_declare_tensor_parallelism` reads every parameter's type, so it covers them once those models get a FlexShard path, but nothing tests them yet; they're rejected today. - **The TP declarations and the view's mesh map are computed in torchtitan.** They should come from FlexShard, from the parameters' SPMD types, as `fully_shard(..., dp_mesh_dims=...)` does (TODO link, the same issue as the EP layout's). Until then the adapter is imported from `flex_shard.layout_adapters.spmd_types`, which doesn't export it. - **Next PRs in the stack:** DeepSeek V3 multi-token prediction, then pipeline parallelism. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: 9c565c8 Pull-Request: #6014
…FlexShardConfig() Stacked on #5842, the expert-parallelism PR, the chunked-loss PR, the checkpointing PR and the Hugging Face load PR. <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> `validate_flex_shard_training` rejects `tensor_parallel_degree > 1` and `context_parallel_degree > 1`, so no recipe that uses TP or CP can run with FlexShard. FlexShard's path takes a 1D `dp_shard` mesh (`apply_flex_shard_to_decoder` asserts it). FSDP2 handles TP and CP through the storage mesh and the parameters' SPMD types (`fully_shard(..., dp_mesh_dims=...)`), so FlexShard buckets over `dp_shard` alone would train wrong without an error: - **CP:** each cp rank's grads cover its own tokens. FSDP2 shards over `dp_shard` and `cp` flattened into one axis, so its reduce-scatter sums them. Buckets over `dp_shard` alone would never sum the cp ranks' grads. - **TP:** `Module._parallelize` hands FlexShard each tp rank's plain local shard. - A parameter typed `R` on tp has a grad that's partial over tp: the norm weights under sequence parallelism, Qwen3's QK norms and its router gate. FSDP2 types such a grad `P` and all-reduces it over tp before its reduce-scatter. FlexShard would keep each tp rank's part. - Initialization, grad-norm clipping and Hugging Face loads view each FlexShard parameter as FSDP2's DTensor (`as_fsdp2_dtensor`, #5842). They'd see each tp rank's shard as the whole parameter, so initialization wouldn't match FSDP2's and the grad norm would leave out the other tp ranks' shards. - Checkpoints would save each tp rank's shard as the whole tensor. **Example.** ```python config = llama3_debugmodel(attn_backend="flex") config.parallelism.tensor_parallel_degree = 2 # or CP, with ContextParallelTransform config.training.disable_accelerator_graphs = True config.parallelism.fsdp_backend = FlexShardConfig() ``` How a Llama 3 debug block is laid out with `dp_shard=2, tp=2`, and with `dp_shard=2, cp=2`: | Parameter | FSDP2 (unchanged): DTensor on `(dp_shard, tp)` | FlexShard (this PR) | | --- | --- | --- | | `wqkv.weight` `[768, 256]`, TP splits dim 0 | `(_StridedShard(0, 2), Shard(0))` | the bucket on `dp_shard` splits the tp rank's `[384, 256]` on dim 0; the TP layout places it in rows `[384 * tp_rank, ...)` | | `wo.weight` `[256, 256]`, TP splits dim 1 | `(Shard(0), Shard(1))` | the bucket splits `[256, 128]` on dim 0; the TP layout is on dim 1 | | `attention_norm.weight` `[256]`, sequence parallel: `R` on tp | `(Shard(0), Replicate())`; the grad is `P` on tp and all-reduced over tp before the reduce-scatter | tp is its partial-grad group: the same all-reduce, at the same point, in fp32 | | `attention_norm.weight`, no sequence parallelism: `I` on tp | `(Shard(0), Replicate())`, no all-reduce | nothing declared | | any parameter, with `cp=2` | `Shard(d)` on `dp_shard_cp`, which `fully_shard` flattens from `(dp_shard, cp)` | buckets on the same flattened mesh, the same process group | - **Mesh (`torchtitan/distributed/flex_shard_fsdp.py`, `apply_flex_shard_to_decoder`).** It takes the storage mesh and `dp_mesh_dims` from `resolve_fsdp_mesh`, as `apply_fsdp_to_decoder` does, in place of a 1D `dp_shard` mesh (`Decoder._apply_fsdp` passes them). The buckets shard over the mesh `fully_shard` shards over: `dp_shard`, or with CP, `storage_mesh[("dp_shard", "cp")]._flatten("dp_shard_cp")`. `DeviceMesh` caches a flattened mesh by name, so both backends reduce on one process group. `decoder_fsdp_groups` gets the storage mesh too, so routed experts without EP shard over `dp_shard * cp` as in FSDP2. - **TP declarations (`_declare_tensor_parallelism`, new).** Before `flex_shard()`, it reads each parameter's SPMD type, which is what FSDP2 lays the parameter out by: - A parameter TP splits is typed `V` on tp, with its dim in the `PartitionSpec`. It declares its layout through flex_shard's spmd_types adapter (`spmd_types_to_global_layout`), and FlexShard composes it with the bucket's split, as for the EP layout (checkpointing PR). - A parameter typed `R` on tp declares the tp group as its partial-grad group (`set_partial_grad_group`). FlexShard all-reduces its unsharded grad over that group before the reduce-scatter, in the grad's dtype. Like FSDP2 (`may_reduce_grad_outside_dp`), it keeps these grads out of the deferred upcast, so with bf16 parameters the sum runs in fp32. The group is the storage mesh's tp group, the one FSDP2's redistribute uses. - Routed experts are skipped. MoE models need `ep >= tp`, so they're typed on the sparse mesh, whose `ep` axis can span the same ranks as `tp`, and keep the EP layout. - **DTensor view (`as_fsdp2_dtensor`).** Under TP, a dense parameter's view is on FSDP2's mesh: `(dp_shard, tp)`, or `(dp_shard_cp, tp)` with CP (`DeviceMesh._concatenate`, as `fully_shard` builds it). On tp it's `Shard(d)` for the dim the TP layout splits (`get_outer_layout`), else `Replicate()`. On the first axis it's `_StridedShard(d, tp)` when the bucket splits the same dim. The global shape is the full one. As for routed experts (expert-parallelism PR), a module-level map gives the mesh, keyed by the buckets' mesh, because `to_empty()` replaces the parameters. Initialization, `clip_grad_norm_` and HF loads already go through the view, so they need no change. With CP alone, FSDP2's DTensors are on the flattened mesh, which is the bucket's mesh, so the view doesn't change. - **Validation (`validate_flex_shard_training`).** It no longer rejects TP or CP, with or without sequence parallelism, alone, together or with EP. The `fsdp_backend` docstring (`torchtitan/config/parallelism.py`) says so. - **Tests:** see Testing. - **Derive the TP layouts and partial-grad groups from each module's `_sharding_config`**, as the FlexShard fork does. It reads other modules' private config. The parameters' own SPMD types are what FSDP2 reads, so both backends follow one source. - **Compute the TP layout by hand**, like the EP layout. TP-split parameters are typed `V` on tp with the dim in their `PartitionSpec`, not `S(d)`, so that means parsing PartitionSpecs. flex_shard's adapter does it, and raises for types it can't express. - **Keep rejecting TP and CP together**, as the fork first did. The code is the same as for either alone, and the combination is tested on 4 GPUs. - **Record each parameter's TP placement on it for the view.** `to_empty()` replaces FlexShard's parameters before initialization. FlexShard keeps the declared layout through `to_empty()`, so the view reads it. | Before | After | | --- | --- | | `fsdp_backend=FlexShardConfig()` with `tensor_parallel_degree > 1` or `context_parallel_degree > 1` raises `ValueError` | accepted for decoders that use `Decoder._apply_fsdp` (Llama 3, Qwen3, GPT-OSS), with or without sequence parallelism, and with EP; training is bitwise identical to FSDP2 | | | HSDP, pipeline parallelism and SPMD type checking still raise, and models with their own `_apply_fsdp` (DeepSeek V3/V4, Kimi, multimodal models) are still rejected | All runs: seed 42, deterministic, accelerator graphs off (FlexShard rejects them), flex attention (FA4 isn't installed on the test machine; CP converts it to `AllGatherKVFlexInnerAttention`, and GPT-OSS's sliding-window layers to `AllGatherKVSlidingWindowFlexInnerAttention`), the recipes' `ChunkedLossWrapper`, torch `2.16.0a0+gita66bab0`, flex_shard `d6bb546` (the commit CI pins), spmd_types 0.3.1 (the pin; the test machine's 0.2.0 breaks TP and CP under either backend). Every run is at `4aa9fed1c`, an earlier version of this commit whose non-test code differs from it only in comments, on an earlier version of the HF-load PR that also differs only in comments. **FlexShard matches FSDP2.** On 2 GPUs: `scripts/loss_compare.py <this commit> <this commit> --baseline-config <FSDP2> --test-config <FlexShard> --assert-equal --metrics loss,grad_norm`. On 4 GPUs: one torchrun training job per backend on MAST, TensorBoard scalars compared exactly. | Config | GPUs | Result | | --- | --- | --- | | Llama 3 debug, `tp=2`, sequence parallel | 2x GB200 | loss and grad_norm bitwise identical, 50 steps (step-50 loss 2.94190); also from a seed checkpoint, 20 steps | | Llama 3 debug, `tp=2`, no sequence parallelism | 2x GB200 | same, 50 steps (2.94192) | | Llama 3 debug, `cp=2` | 2x GB200 | same, 50 steps (2.94029); also from a seed checkpoint, 20 steps | | Qwen3 MoE debug, `tp=2, ep=2`, sequence parallel | 2x GB200 | same, 50 steps (3.73420); also from a seed checkpoint, 20 steps | | Qwen3 MoE debug, `tp=2, ep=2`, no sequence parallelism | 2x GB200 | same, 50 steps (3.73244) | | Qwen3 MoE debug, `cp=2` (routed experts on `dp_shard_cp`) | 2x GB200 | same, 50 steps (3.72928); also from a seed checkpoint, 20 steps | | GPT-OSS debug, `tp=2, ep=2` (TP also splits the attention sinks and biases) | 2x GB200 | same, 50 steps (3.04097) | | GPT-OSS debug, `cp=2` | 2x GB200 | same, 50 steps (3.05864) | | Llama 3 debug, `dp_shard=2, tp=2` | 4x GB300 | loss, max loss and grad_norm bitwise identical, 20 steps | | Llama 3 debug, `dp_shard=2, cp=2` | 4x GB300 | same | | Llama 3 debug, `cp=2, tp=2` | 4x GB300 | same | | Qwen3 MoE debug, `dp_shard=2, tp=2, ep=2` (`edp_shard=2`) | 4x GB300 | loss, max loss, grad_norm and load-balance loss bitwise identical, 20 steps | | Qwen3 MoE debug, `dp_shard=2, cp=2` | 4x GB300 | same | On 2 GPUs, TP or CP leaves `dp_shard=1`. The TP runs then check the TP all-reduces and layouts but not the reduce-scatters, which the 4-GPU runs add. The 50-step runs skip the seed checkpoint, so FlexShard initializes through its DTensor views. The 20-step runs use `loss_compare`'s seed checkpoint, made on 1 GPU from the same model without TP or CP (`--seed-config`), so FlexShard loads a full-tensor DCP checkpoint into TP- or CP-sharded parameters. Peak memory, FlexShard vs FSDP2: Llama 3 within 0.04 GiB (0.50 vs 0.54 GiB at `tp=2`), Qwen3 MoE 3.22 vs 3.81 GiB at `tp=2, ep=2` and 3.74 vs 3.87 GiB at `cp=2`. **FSDP2 is unchanged.** `scripts/loss_compare.py <HF-load PR> <this commit> --baseline-config <FSDP2> --assert-equal --metrics loss,grad_norm --no-seed-checkpoint --steps 50`, in a scratch clone, 2x GB200: | Config | Result | | --- | --- | | Llama 3 debug, `tp=2`, sequence parallel | loss and grad_norm bitwise identical, 50 steps | | Llama 3 debug, `tp=2`, no sequence parallelism | same | | Llama 3 debug, `cp=2` | same | | Qwen3 MoE debug, `tp=2, ep=2` | same | | Qwen3 MoE debug, `cp=2` | same | FSDP2's code doesn't change: `Decoder._apply_fsdp` only passes one more argument on the FlexShard branch. Run on 2x GB200 with torch `2.16.0a0+gita66bab0`, flex_shard `d6bb546` and spmd_types 0.3.1, and on 4x GB300 (MAST) with another torch `2.16.0a0` build, the same flex_shard and spmd_types. At this commit: the 2-rank run of the test file, the CP with EP check, and the reverts as caught by the TP-without-sequence-parallelism and CP tests. The rest ran at `4aa9fed1c` (see Numerics), whose test file also ran Llama 3 in those two tests. - **New tests in `tests/unit_tests/gpu/distributed/test_flex_shard_fsdp.py`.** Each builds both backends through `model.parallelize` and requires bitwise-equal initialization, per-microbatch losses, clipped grad norms, local grads and AdamW-updated parameters over 3 steps, with 1 microbatch and with 2 and deferred gradient reduction, as the existing parity tests do. | Test | Models | Layout at 4 ranks (CI) | | --- | --- | --- | | `test_matches_fsdp2_with_tensor_parallelism` | Llama 3 debug, Qwen3 MoE debug (`ep=2`), sequence parallel, `ChunkedLossWrapper` | `dp_shard=2, tp=2` (Qwen3's experts: `edp_shard=2`) | | `test_matches_fsdp2_with_tensor_parallelism_without_sequence_parallelism` | Qwen3 MoE debug (`ep=2`), CE loss | `dp_shard=2, tp=2` | | `test_matches_fsdp2_with_context_parallelism` | Qwen3 MoE debug, `ep=1`, CE loss | `dp_shard=2, cp=2` | | `test_matches_fsdp2_with_tensor_and_context_parallelism` | Llama 3 debug, sequence parallel, `ChunkedLossWrapper` | `cp=2, tp=2` | | `test_checkpoints_across_backends_with_tensor_parallelism` | Llama 3 debug, sequence parallel: the checkpointing PR's check (checkpoints equal FSDP2's; each backend resumes from the other's) and the HF-load PR's (FlexShard loads FSDP2's HF export) | `dp_shard=2, tp=2` | The CP test also covers Qwen3's routed experts sharded over `dp_shard * cp` without EP. The checkpoint test also compares the optimizer states, which the checkpoints hold. - **Harness changes (mechanical, all tests).** As the trainer does, the loss is torchtitan's `CrossEntropyLoss` (vocab-parallel under TP) instead of `F.cross_entropy`, inputs are preprocessed inside `activate_spmd()` so CP shards them, the tp and cp ranks of a data-parallel rank share its data, CP models get `ContextParallelTransform` (`AllGatherKVFlexInnerAttention`) and a 128-token block per cp rank, and `_parallelism_context` takes `tp`, `cp` and `sequence_parallel`. - **Each change is guarded.** With each of these reverted, these tests fail: | Reverted | Fails | | --- | --- | | the partial-grad declarations | both TP parity tests, at step 0's grad norm: Llama 3 with sequence parallelism, and Qwen3 (QK norms, router) without it | | the TP layouts | both TP parity tests and the TP checkpoint test, at initialization: the fused QKV weight's init sees the tp rank's shape | | only the TP layouts' offsets (zeroed; the views keep their shapes) | the TP checkpoint test: its chunks differ from FSDP2's | | the TP mesh in `as_fsdp2_dtensor` | both TP parity tests, at initialization | | `_StridedShard` in the view (`Shard` instead) | `test_matches_fsdp2_with_tensor_parallelism` at 4 ranks, at the initialization of `wqkv.weight`. At 2 ranks (`dp_shard=1`) the two can't be told apart | | the flattened CP mesh (buckets on `dp_shard` alone) | the CP parity test, at initialization | - **Results.** - 2 ranks on GB200: 8 of the file's 9 tests pass, with `world_size` set to 2; the TP+CP test needs 4 ranks. At 2 ranks, TP alone leaves `dp_shard=1`, where neither backend reduce-scatters, so for that run the reduce-scatter-count check's floor is 0. - 4 ranks on GB300: the 5 new tests pass (at `4aa9fed1c`, with Llama 3 also in the TP-without-sequence-parallelism and CP tests). Each runs as its own torchrun job that calls the test method directly, because `MultiProcessTestCase` doesn't run on those hosts. - CP with EP, which validation now accepts: Qwen3 MoE debug at `cp=2, ep=2`, with 1 microbatch and with 2, is bitwise equal to FSDP2 under the parity tests' check at 2 ranks on 2x GB200 (a one-off run of `_check_matches_fsdp2`, not added to the file). - **CPU suites:** `cpu/config`, `cpu/components`, `cpu/distributed`, `cpu/models/base`, `cpu/scripts` and `test_trainer.py`, with GPUs hidden and the pinned torch_checkpointing 0.1.1 and spmd_types 0.3.1: 1011 passed. The 4 failures and 2 collection errors are the same on the base in this environment: three subtests of `test_lora_head_only_matches_cross_entropy` (an Inductor CPU flex-attention error), `test_hf_backend_renders_generation_tags`, and the `test_renderer` and `test_validator` collection errors (local dependencies older than the pins or missing). - **Lint:** pre-commit passes on the changed files (flake8, ufmt, pydoclint, codespell, license). pyrefly 0.45.1 reports the same 12 errors as the base. - **SPMD type checking (`debug.spmd_typechecking`) stays rejected.** The fork enables it on a flex_shard change that runs FlexShard's hooks outside the type checker; it needs its own check against FSDP2 under the checker. - **Other models' TP-replicated parameters.** Kimi K3's `tp_unsharded_weight_sharding_config` and DeepSeek V4's compressor also rely on FSDP2 all-reducing `R`-typed grads over tp. `_declare_tensor_parallelism` reads every parameter's type, so it covers them once those models get a FlexShard path, but nothing tests them yet; they're rejected today. - **The TP declarations and the view's mesh map are computed in torchtitan.** They should come from FlexShard, from the parameters' SPMD types, as `fully_shard(..., dp_mesh_dims=...)` does (TODO link, the same issue as the EP layout's). Until then the adapter is imported from `flex_shard.layout_adapters.spmd_types`, which doesn't export it. - **Next PRs in the stack:** DeepSeek V3 multi-token prediction, then pipeline parallelism. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: b79a31f Pull-Request: #6014
…FlexShardConfig() Stacked on #5842, the expert-parallelism PR, the chunked-loss PR, the checkpointing PR and the Hugging Face load PR. ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Description `validate_flex_shard_training` rejects `tensor_parallel_degree > 1` and `context_parallel_degree > 1`, so no recipe that uses TP or CP can run with FlexShard. Deleting the rejections alone would train wrong without an error. FSDP2 handles both through the storage mesh and the parameters' SPMD types (`fully_shard(..., dp_mesh_dims=...)`), while `_apply_flex_shard` asserts a 1D `dp_shard` mesh: - **CP:** each cp rank's grads cover its own tokens. FSDP2 shards over `dp_shard` and `cp` flattened into one axis, so its reduce-scatter sums them. Buckets over `dp_shard` alone would never sum the cp ranks' grads. - **TP:** `Module._parallelize` hands FlexShard each tp rank's plain local shard. A parameter typed `R` on tp has a grad that's partial over tp: the norm weights under sequence parallelism, and Qwen3's QK norms and router gate. FSDP2 types such a grad `P` and all-reduces it over tp before its reduce-scatter; FlexShard would keep each tp rank's part. `init_param` would initialize each tp rank's shard as if it were the whole parameter, and the grad norm would leave out the other tp ranks' shards. This PR deletes both rejections and makes training with TP or CP, also with EP, bitwise identical to FSDP2. As in #5842, nothing on the FlexShard path creates a DTensor. The earlier revision of this PR viewed every parameter under TP as FSDP2's DTensor through `as_fsdp2_dtensor`, which #5842 has since deleted, so initialization and the grad norm are reworked here. **Mesh.** `apply_fsdp_to_decoder` passes `dp_mesh_dims` to `_apply_flex_shard`, whose buckets now shard over the mesh `fully_shard` shards over: `dp_shard`, or under CP, `(dp_shard, cp)` flattened into `dp_shard_cp`, as `fully_shard` flattens it. `DeviceMesh` caches a flattened mesh by name, so both backends reduce on one process group. `_decoder_fsdp_groups` already sizes the routed experts' shards over `dp_shard * cp` without EP, so they need no change. **TP declarations.** Before `flex_shard()`, the new `_declare_tensor_parallelism` reads each dense parameter's SPMD type, which is what FSDP2 lays the parameter out by: - A parameter TP splits (`V` on tp with its dim in the `PartitionSpec`) declares where its shard sits in the full parameter, as its outer layout, through flex_shard's spmd_types adapter (`spmd_types_to_global_layout`), as the expert-parallelism PR declares the EP split by hand. flex_shard composes it with the bucket's split in `get_flex_shard_global_layouts`, which `record_param_layouts` records, so `init_param` initializes the full parameter and keeps this rank's part, with no change to `init_param`. - A parameter typed `R` on tp declares the storage mesh's tp group as its partial-grad group (`set_partial_grad_group`). FlexShard all-reduces its unsharded grad over that group before the reduce-scatter, in the grad's dtype. Like FSDP2 (`may_reduce_grad_outside_dp`), it keeps these grads out of the deferred upcast, so with bf16 parameters the sum runs in fp32. - A parameter typed `I` on tp, e.g. a norm weight without sequence parallelism, declares nothing. - Any other type on tp, or none, raises a `ValueError`. Untyped, a parameter would declare itself whole, and the grad norm would count it once per tp rank. - Routed experts are skipped. MoE models need `ep >= tp`, so they're typed on the sparse mesh and keep their EP layout. `fused_qkv_param_init` needed one fix. For a plain tensor under TP, it assumed the tensor is the tp rank's shard (the RL generator's case) and copied only that shard of the full fused init. `init_param` hands it the full parameter, so it now copies a shard only when the tensor's rows don't match the full fused tensor's. **Grad norm.** FSDP2's dense grads under TP are DTensors on `(dp_shard, tp)`, or `(dp_shard_cp, tp)` with CP. Tracing `get_total_norm(...).full_tensor()` on them shows what DTensor does: each grad's local norm is partial over `dp_shard`, and over tp if TP splits the grad; stacking the norms makes a replicated norm partial over tp too, by dividing it by `tp ** (1 / p)`; the stacked norms are then reduced over `dp_shard`, then tp, each with its own power and root, since no flattened mesh spans tp; then the norm of norms. `_local_shards_norm` now does exactly that on a multi-dim mesh, given which grads are replicated beyond the mesh's first dim. It divides each replicated grad's norm before stacking the norms, the same elementwise division, so that no mask is copied from the host, which would synchronize the stream. `_apply_flex_shard` records `(bucket mesh, tp)` as the dense buckets' grad-norm mesh (`DeviceMesh._concatenate`, as FSDP2 builds it), and the new `is_outer_sharded` tells `clip_grad_norm_` which grads TP splits: those of parameters with an outer layout, which FlexShard keeps through `to_empty()`. A replicated grad is thus counted once, as in FSDP2. On a mesh of one dim, `_local_shards_norm` reduces as before, except that it now skips a mesh of size 1, as DTensor does. The probes (not part of the PR) build the model with FSDP2 on meta over a CPU mesh, with production's meshes, give each parameter a random grad as a DTensor with FSDP2's spec, and compare torchtitan's `clip_grad_norm_` on the DTensor grads against the plain local shards: - 12 random trials each at 4 ranks (gloo) for Llama 3 debug at `dp_shard=2, tp=2` with and without sequence parallelism and at `cp=2, tp=2`, Qwen3 MoE debug at `dp_shard=2, tp=2, ep=2` with and without sequence parallelism and at `dp_shard=2, cp=2`, and at 2 ranks for `tp=2` and `tp=2, ep=2`: the new `_local_shards_norm` is bitwise equal in every trial. Reducing over tp before `dp_shard` differed in 1 of 12 trials for Llama 3, and one all-reduce over each flattened mesh (what the expert-parallelism PR does for routed experts) in 1 of 12 in every 4-rank case with TP. - Per norm, with 2000 replicated grads at `dp_shard=2, tp=2`: with the division, 2001 of 2001 reduced norms equal DTensor's; reducing a replicated norm over `dp_shard` alone matches in only 1248 to 1286 of them, and the total differed in 1 of 5 seeds. **Routed experts under TP.** The expert-parallelism PR reduces routed-expert grads' norm in one all-reduce over torchtitan's loss mesh, flattened from `(dp, cp)`, because DTensor finds it by layout for `(edp_shard, ep)` and uses it. That holds only without TP: with TP, `edp_shard * ep` spans the tp ranks too and the loss mesh doesn't, so DTensor reduces over `edp_shard`, then `ep` (the probe above, Qwen3 MoE at `dp_shard=2, tp=2, ep=2`, which has 4 all-reduces). Under TP, `_apply_flex_shard` now records the sparse mesh itself. A new flattened mesh over those ranks would have the dense `(dp_shard, tp)` mesh's layout: with FSDP2 in the same process, as in the parity test, DTensor would find it and reduce the dense norms in one all-reduce, unlike a production FSDP2 run. **Validation.** `validate_flex_shard_training` no longer rejects TP or CP. **Hugging Face loads under TP.** The Hugging Face load PR's `load_hf_into_local_shards` takes each region of a shard's layout as a box of the parameter, so TP's shards need no change. TP splits the last dim of row-wise parallel weights: each region of a `wo` or `w2` shard holds columns `[c0, c1)` of its rows, and the loader declares the same columns of the Hugging Face rows that hold those rows, as views of the shard. The packed QKV, the rotary permutation and `w13`, which TP splits in a leading dim, load as without TP. **Tests.** The parity test's harness now builds TP and CP models as the trainer does: `_check_matches_fsdp2` takes `tp`, `cp` and `sequence_parallel`; the loss is torchtitan's `CrossEntropyLoss` (vocab-parallel under TP) instead of `F.cross_entropy`, for all cases; inputs are preprocessed inside `activate_spmd()`, so CP shards them; the tp and cp ranks of a data-parallel rank share its data; CP models get `ContextParallelTransform` (`AllGatherKVFlexInnerAttention`) and 128 tokens per cp rank. `_assert_initialized_as_one_device` expects a TP-split shard to be its bucket chunk of the tp rank's chunk of one device's init, with buckets over `dp_shard * cp`. Two methods are new, each over 1 and 2 microbatches, with the default reshard policy: - `test_matches_fsdp2_with_tensor_parallelism`: Llama 3 debug and Qwen3 MoE debug (`ep=2`), sequence parallel, `ChunkedLossWrapper`. At CI's 4 GPUs, `dp_shard=2, tp=2`, and Qwen3's routed experts `edp_shard=2`. - `test_matches_fsdp2_with_context_parallelism`: Llama 3 debug and Qwen3 MoE debug (`ep=1`, so its routed experts shard over `dp_shard_cp`), cross-entropy. At 4 GPUs, `dp_shard=2, cp=2`. Both new methods pass on 2 GB200 GPUs with `world_size` set to 2, where they run `tp=2` or `cp=2` with `dp_shard=1`, and so does `test_matches_fsdp2`. At 2 ranks, TP leaves `dp_shard=1`, where neither backend reduce-scatters, so that run lowers the reduce-scatter count's floor to 0. Nor can 2 ranks tell the bucket's split within a TP shard from a split of the whole parameter, or one order of the grad norm's dims from the other: the 4-rank checks above and below cover those. The tests haven't run at CI's 4 GPUs: this machine has 2, and FlexShard needs CUDA. Without the partial-grad declarations, the TP method fails at step 0's grad norm (Llama 3 debug, one microbatch). Checkpointing needs no change under TP: the TP split that a parameter declares as its outer layout is part of the layouts that the checkpointing PR's state dicts declare to DCP, for the parameters and their AdamW states. `test_checkpoints_match_fsdp2` now takes `tp`, and also runs on the Qwen3 MoE debug model at `tp=2` with sequence parallelism and `ep=2`. FlexShard loads FSDP2's checkpoint, in which TP splits the dense parameters and their AdamW states in dim 0 or 1 and the norm weights are replicated over tp, matches FSDP2's parameters and AdamW states on every rank, and saves it again chunk for chunk and bit for bit, also as a bf16 export. At CI's 4 GPUs it runs `dp_shard=2, tp=2`. Both cases pass on 2 GB200 GPUs with `world_size` set to 2 (`dp_shard=1` at `tp=2`). With TP's split not declared as the outer layout, it fails at the load: DCP reports a size mismatch, saved `[4096, 256]` against current `[2048, 256]`, for `layers.0.attention.qkv_linear.wqkv.weight`. `test_hf_loads_match_fsdp2` now takes `tp` too, and also runs the Hugging Face load PR's parity check on the Llama 3 debug model at `tp=2` with sequence parallelism (at CI's 4 GPUs, `dp_shard=2, tp=2`): FSDP2 exports, both backends load, FlexShard's shards equal their boxes of the export, and 3 steps are bitwise equal. Both cases pass on 2 GB200 GPUs with `world_size` set to 2 (`dp_shard=1` at `tp=2`), and so does the expert-parallelism case. At `tp=2`, only the second tp rank's columns start past 0, so the shard check now gathers mismatches from all ranks before it asserts. Before, the failing rank stopped while the other waited in the training's collectives until the timeout. With the region's column offset dropped from the loader's chunks, the test fails on both ranks and lists that rank's 6 `wo` and 6 `w2` shards. The Hugging Face load PR's `test_hf_load_into_uneven_shards` covers shards that split the last dim at `torch.chunk`'s boundaries. **4-rank layouts.** As for EP, a one-off check builds both backends on meta for every rank of a fake process group and compares, for every parameter: FlexShard's layout with FSDP2's DTensor shard region; `flex_shard_grad_norm_mesh`'s mesh with the layout of FSDP2's grad mesh; `is_outer_sharded` with whether FSDP2 shards the parameter beyond its first mesh dim; and that exactly the parameters typed `R` on tp declare tp as their partial-grad group. All match at every rank of Llama 3 debug at `dp_shard=2, tp=2` with and without sequence parallelism and at `cp=2, tp=2`, and of Qwen3 MoE debug at `dp_shard=2, tp=2, ep=2`; at ranks 0 and 3 of Qwen3 MoE at `dp_shard=2, tp=2, ep=2` without sequence parallelism, at `dp_shard=2, cp=2` and at `dp_shard=2, cp=2, ep=2`; and at ranks 0, 3, 5 and 6 of 8 for Llama 3 at `dp_shard=2, cp=2, tp=2` and Qwen3 MoE at `dp_shard=2, cp=2, tp=2, ep=4`. **FSDP2 path.** FSDP2's code doesn't change, except `fused_qkv_param_init`'s branch for plain tensors, which FSDP2's DTensor parameters don't take. `scripts/loss_compare.py 4f80bce4f <this PR> --assert-equal --metrics loss,grad_norm` (seed 42, deterministic, 50 steps, 2 GB200 GPUs) reports equal loss and grad norm at every step for llama3 `debugmodel` with `tensor_parallel_degree=2` and sequence parallelism (step-50 loss 2.94190), which runs `fused_qkv_param_init` on TP-sharded DTensors. It ran at an earlier version of this commit whose code on the FSDP2 path differs only in comments, uses flex attention because the environment has no FA4, and skips the seed checkpoint, since both runs start from seed 42 with the same parallelism. FlexShard wasn't compared with FSDP2 through the trainer this way: from a seed alone, the two backends start from different weights, and a trainer-level comparison from a shared seed checkpoint wasn't run. FlexShard runs of the same Llama 3 config with `tp=2` and with `cp=2` (accelerator graphs off) train through the trainer for 50 steps, to a step-50 loss of 2.93671 and 2.93681, against FSDP2's 2.94190 and 2.94029 from its own initialization. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: d3b1758 Pull-Request: #6014
…FlexShardConfig() Stacked on #5842, the expert-parallelism PR, the chunked-loss PR, the checkpointing PR and the Hugging Face load PR. ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Description `validate_flex_shard_training` rejects `tensor_parallel_degree > 1` and `context_parallel_degree > 1`, so no recipe that uses TP or CP can run with FlexShard. Deleting the rejections alone would train wrong without an error. FSDP2 handles both through the storage mesh and the parameters' SPMD types (`fully_shard(..., dp_mesh_dims=...)`), while `_apply_flex_shard` asserts a 1D `dp_shard` mesh: - **CP:** each cp rank's grads cover its own tokens. FSDP2 shards over `dp_shard` and `cp` flattened into one axis, so its reduce-scatter sums them. Buckets over `dp_shard` alone would never sum the cp ranks' grads. - **TP:** `Module._parallelize` hands FlexShard each tp rank's plain local shard. A parameter typed `R` on tp has a grad that's partial over tp: the norm weights under sequence parallelism, and Qwen3's QK norms and router gate. FSDP2 types such a grad `P` and all-reduces it over tp before its reduce-scatter; FlexShard would keep each tp rank's part. Initialization would treat each tp rank's shard as if it were the whole parameter, and the grad norm would leave out the other tp ranks' shards. This PR deletes both rejections and makes training with TP or CP, also with EP, bitwise identical to FSDP2. As in #5842, nothing on the FlexShard path creates a DTensor. The earlier revision of this PR viewed every parameter under TP as FSDP2's DTensor through `as_fsdp2_dtensor`, which #5842 has since deleted, so initialization and the grad norm are reworked here. **Mesh.** `apply_fsdp_to_decoder` passes `dp_mesh_dims` to `_apply_flex_shard`, whose buckets now shard over the mesh `fully_shard` shards over: `dp_shard`, or under CP, `(dp_shard, cp)` flattened into `dp_shard_cp`, as `fully_shard` flattens it. `DeviceMesh` caches a flattened mesh by name, so both backends reduce on one process group. `_decoder_fsdp_groups` already sizes the routed experts' shards over `dp_shard * cp` without EP, so they need no change. **TP declarations.** Before `flex_shard()`, the new `_declare_tensor_parallelism` reads each dense parameter's SPMD type, which is what FSDP2 lays the parameter out by: - A parameter TP splits (`V` on tp with its dim in the `PartitionSpec`) declares where its shard sits in the full parameter, as its outer layout, through flex_shard's spmd_types adapter (`spmd_types_to_global_layout`), as the expert-parallelism PR declares the EP split by hand. flex_shard composes it with the bucket's split in `get_flex_shard_global_layouts`, whose layouts the wrapped `param_init` functions use, so each initializes the full parameter and keeps this rank's part, with no change to the wrapping. - A parameter typed `R` on tp declares the storage mesh's tp group as its partial-grad group (`set_partial_grad_group`). FlexShard all-reduces its unsharded grad over that group before the reduce-scatter, in the grad's dtype. Like FSDP2 (`may_reduce_grad_outside_dp`), it keeps these grads out of the deferred upcast, so with bf16 parameters the sum runs in fp32. - A parameter typed `I` on tp, e.g. a norm weight without sequence parallelism, declares nothing. - Any other type on tp, or none, raises a `ValueError`. Untyped, a parameter would declare itself whole, and the grad norm would count it once per tp rank. - Routed experts are skipped. MoE models need `ep >= tp`, so they're typed on the sparse mesh and keep their EP layout. `fused_qkv_param_init` needed one fix. For a plain tensor under TP, it assumed the tensor is the tp rank's shard (the RL generator's case) and copied only that shard of the full fused init. The wrapped `param_init` hands it the full parameter, so it now copies a shard only when the tensor's rows don't match the full fused tensor's. **Grad norm.** FSDP2's dense grads under TP are DTensors on `(dp_shard, tp)`, or `(dp_shard_cp, tp)` with CP. Tracing `get_total_norm(...).full_tensor()` on them shows what DTensor does: each grad's local norm is partial over `dp_shard`, and over tp if TP splits the grad; stacking the norms makes a replicated norm partial over tp too, by dividing it by `tp ** (1 / p)`; the stacked norms are then reduced over `dp_shard`, then tp, each with its own power and root, since no flattened mesh spans tp; then the norm of norms. `flex_shard_grad_norm` now does exactly that on a multi-dim mesh, given which grads are replicated beyond the mesh's first dim. It divides each replicated grad's norm before stacking the norms, the same elementwise division, so that no mask is copied from the host, which would synchronize the stream. `_apply_flex_shard` records `(bucket mesh, tp)` as the dense buckets' grad-norm mesh (`DeviceMesh._concatenate`, as FSDP2 builds it), and the new `is_outer_sharded` tells `flex_shard_grad_norm` which grads TP splits: those of parameters with an outer layout, which FlexShard keeps through `to_empty()`. A replicated grad is thus counted once, as in FSDP2. On a mesh of one dim, `flex_shard_grad_norm` reduces as before, except that it now skips a mesh of size 1, as DTensor does. The probes (not part of the PR) build the model with FSDP2 on meta over a CPU mesh, with production's meshes, give each parameter a random grad as a DTensor with FSDP2's spec, and compare torchtitan's `clip_grad_norm_` on the DTensor grads against the plain local shards: - 12 random trials each at 4 ranks (gloo) for Llama 3 debug at `dp_shard=2, tp=2` with and without sequence parallelism and at `cp=2, tp=2`, Qwen3 MoE debug at `dp_shard=2, tp=2, ep=2` with and without sequence parallelism and at `dp_shard=2, cp=2`, and at 2 ranks for `tp=2` and `tp=2, ep=2`: the reduction `flex_shard_grad_norm` now does is bitwise equal in every trial. Reducing over tp before `dp_shard` differed in 1 of 12 trials for Llama 3, and one all-reduce over each flattened mesh (what the expert-parallelism PR does for routed experts) in 1 of 12 in every 4-rank case with TP. - Per norm, with 2000 replicated grads at `dp_shard=2, tp=2`: with the division, 2001 of 2001 reduced norms equal DTensor's; reducing a replicated norm over `dp_shard` alone matches in only 1248 to 1286 of them, and the total differed in 1 of 5 seeds. **Routed experts under TP.** The expert-parallelism PR reduces routed-expert grads' norm in one all-reduce over torchtitan's loss mesh, flattened from `(dp, cp)`, because DTensor finds it by layout for `(edp_shard, ep)` and uses it. That holds only without TP: with TP, `edp_shard * ep` spans the tp ranks too and the loss mesh doesn't, so DTensor reduces over `edp_shard`, then `ep` (the probe above, Qwen3 MoE at `dp_shard=2, tp=2, ep=2`, which has 4 all-reduces). Under TP, `_apply_flex_shard` now records the sparse mesh itself. A new flattened mesh over those ranks would have the dense `(dp_shard, tp)` mesh's layout: with FSDP2 in the same process, as in the parity test, DTensor would find it and reduce the dense norms in one all-reduce, unlike a production FSDP2 run. **Validation.** `validate_flex_shard_training` no longer rejects TP or CP. **Hugging Face loads under TP.** The Hugging Face load PR's `load_hf_into_local_shards` takes each region of a shard's layout as a box of the parameter, so TP's shards need no change. TP splits the last dim of row-wise parallel weights: each region of a `wo` or `w2` shard holds columns `[c0, c1)` of its rows, and the loader declares the same columns of the Hugging Face rows that hold those rows, as views of the shard. The packed QKV, the rotary permutation and `w13`, which TP splits in a leading dim, load as without TP. **Tests.** The parity test's harness now builds TP and CP models as the trainer does: `_check_matches_fsdp2` takes `tp`, `cp` and `sequence_parallel`; the loss is torchtitan's `CrossEntropyLoss` (vocab-parallel under TP) instead of `F.cross_entropy`, for all cases; inputs are preprocessed inside `activate_spmd()`, so CP shards them; the tp and cp ranks of a data-parallel rank share its data; CP models get `ContextParallelTransform` (`AllGatherKVFlexInnerAttention`) and 128 tokens per cp rank. `_assert_initialized_as_one_device` expects a TP-split shard to be its bucket chunk of the tp rank's chunk of one device's init, with buckets over `dp_shard * cp`. Two methods are new, each over 1 and 2 microbatches, with the default reshard policy: - `test_matches_fsdp2_with_tensor_parallelism`: Llama 3 debug and Qwen3 MoE debug (`ep=2`), sequence parallel, `ChunkedLossWrapper`. At CI's 4 GPUs, `dp_shard=2, tp=2`, and Qwen3's routed experts `edp_shard=2`. - `test_matches_fsdp2_with_context_parallelism`: Llama 3 debug and Qwen3 MoE debug (`ep=1`, so its routed experts shard over `dp_shard_cp`), cross-entropy. At 4 GPUs, `dp_shard=2, cp=2`. Both new methods pass on 2 GB200 GPUs with `world_size` set to 2, where they run `tp=2` or `cp=2` with `dp_shard=1`, and so does `test_matches_fsdp2`. At 2 ranks, TP leaves `dp_shard=1`, where neither backend reduce-scatters, so that run lowers the reduce-scatter count's floor to 0. Nor can 2 ranks tell the bucket's split within a TP shard from a split of the whole parameter, or one order of the grad norm's dims from the other: the 4-rank checks above and below cover those. The tests haven't run at CI's 4 GPUs: this machine has 2, and FlexShard needs CUDA. Without the partial-grad declarations, the TP method fails at step 0's grad norm (Llama 3 debug, one microbatch). Checkpointing needs no change under TP: the TP split that a parameter declares as its outer layout is part of the layouts that the checkpointing PR's state dicts declare to DCP, for the parameters and their AdamW states. `test_checkpoints_match_fsdp2` now takes `tp`, and also runs on the Qwen3 MoE debug model at `tp=2` with sequence parallelism and `ep=2`. FlexShard loads FSDP2's checkpoint, in which TP splits the dense parameters and their AdamW states in dim 0 or 1 and the norm weights are replicated over tp, matches FSDP2's parameters and AdamW states on every rank, and saves it again chunk for chunk and bit for bit, also as a bf16 export. At CI's 4 GPUs it runs `dp_shard=2, tp=2`. Both cases pass on 2 GB200 GPUs with `world_size` set to 2 (`dp_shard=1` at `tp=2`). With TP's split not declared as the outer layout, it fails at the load: DCP reports a size mismatch, saved `[4096, 256]` against current `[2048, 256]`, for `layers.0.attention.qkv_linear.wqkv.weight`. `test_hf_loads_match_fsdp2` now takes `tp` too, and also runs the Hugging Face load PR's parity check on the Llama 3 debug model at `tp=2` with sequence parallelism (at CI's 4 GPUs, `dp_shard=2, tp=2`): FSDP2 exports, both backends load, FlexShard's shards equal their boxes of the export, and 3 steps are bitwise equal. Both cases pass on 2 GB200 GPUs with `world_size` set to 2 (`dp_shard=1` at `tp=2`), and so does the expert-parallelism case. At `tp=2`, only the second tp rank's columns start past 0, so the shard check now gathers mismatches from all ranks before it asserts. Before, the failing rank stopped while the other waited in the training's collectives until the timeout. With the region's column offset dropped from the loader's chunks, the test fails on both ranks and lists that rank's 6 `wo` and 6 `w2` shards. The Hugging Face load PR's `test_hf_load_into_uneven_shards` covers shards that split the last dim at `torch.chunk`'s boundaries. **4-rank layouts.** As for EP, a one-off check builds both backends on meta for every rank of a fake process group and compares, for every parameter: FlexShard's layout with FSDP2's DTensor shard region; the mesh `flex_shard_grad_norm` reduces over with the layout of FSDP2's grad mesh; `is_outer_sharded` with whether FSDP2 shards the parameter beyond its first mesh dim; and that exactly the parameters typed `R` on tp declare tp as their partial-grad group. All match at every rank of Llama 3 debug at `dp_shard=2, tp=2` with and without sequence parallelism and at `cp=2, tp=2`, and of Qwen3 MoE debug at `dp_shard=2, tp=2, ep=2`; at ranks 0 and 3 of Qwen3 MoE at `dp_shard=2, tp=2, ep=2` without sequence parallelism, at `dp_shard=2, cp=2` and at `dp_shard=2, cp=2, ep=2`; and at ranks 0, 3, 5 and 6 of 8 for Llama 3 at `dp_shard=2, cp=2, tp=2` and Qwen3 MoE at `dp_shard=2, cp=2, tp=2, ep=4`. **FSDP2 path.** FSDP2's code doesn't change, except `fused_qkv_param_init`'s branch for plain tensors, which FSDP2's DTensor parameters don't take. `scripts/loss_compare.py 4f80bce4f <this PR> --assert-equal --metrics loss,grad_norm` (seed 42, deterministic, 50 steps, 2 GB200 GPUs) reports equal loss and grad norm at every step for llama3 `debugmodel` with `tensor_parallel_degree=2` and sequence parallelism (step-50 loss 2.94190), which runs `fused_qkv_param_init` on TP-sharded DTensors. It ran at an earlier version of this commit whose code on the FSDP2 path differs only in comments, uses flex attention because the environment has no FA4, and skips the seed checkpoint, since both runs start from seed 42 with the same parallelism. FlexShard wasn't compared with FSDP2 through the trainer this way: from a seed alone, the two backends start from different weights, and a trainer-level comparison from a shared seed checkpoint wasn't run. FlexShard runs of the same Llama 3 config with `tp=2` and with `cp=2` (accelerator graphs off) train through the trainer for 50 steps, to a step-50 loss of 2.93671 and 2.93681, against FSDP2's 2.94190 and 2.94029 from its own initialization. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: 8024baa Pull-Request: #6014
[ghstack-poisoned]
…FlexShardConfig() Stacked on #5842, the expert-parallelism PR, the chunked-loss PR, the checkpointing PR and the Hugging Face load PR. ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Description `validate_flex_shard_training` rejects `tensor_parallel_degree > 1` and `context_parallel_degree > 1`, so no recipe that uses TP or CP can run with FlexShard. Deleting the rejections alone would train wrong without an error. FSDP2 handles both through the storage mesh and the parameters' SPMD types (`fully_shard(..., dp_mesh_dims=...)`), while `_apply_flex_shard` asserts a 1D `dp_shard` mesh: - **CP:** each cp rank's grads cover its own tokens. FSDP2 shards over `dp_shard` and `cp` flattened into one axis, so its reduce-scatter sums them. Buckets over `dp_shard` alone would never sum the cp ranks' grads. - **TP:** `Module._parallelize` hands FlexShard each tp rank's plain local shard. A parameter typed `R` on tp has a grad that's partial over tp: the norm weights under sequence parallelism, and Qwen3's QK norms and router gate. FSDP2 types such a grad `P` and all-reduces it over tp before its reduce-scatter; FlexShard would keep each tp rank's part. Initialization would treat each tp rank's shard as if it were the whole parameter, and the grad norm would leave out the other tp ranks' shards. This PR deletes both rejections and makes training with TP or CP, also with EP, bitwise identical to FSDP2. As in #5842, nothing on the FlexShard path creates a DTensor. The earlier revision of this PR viewed every parameter under TP as FSDP2's DTensor through `as_fsdp2_dtensor`, which #5842 has since deleted, so initialization and the grad norm are reworked here. **Mesh.** `apply_fsdp_to_decoder` passes `dp_mesh_dims` to `_apply_flex_shard`, whose buckets now shard over the mesh `fully_shard` shards over: `dp_shard`, or under CP, `(dp_shard, cp)` flattened into `dp_shard_cp`, as `fully_shard` flattens it. `DeviceMesh` caches a flattened mesh by name, so both backends reduce on one process group. The new `flex_shard_bucket_mesh` picks that mesh, for `_apply_flex_shard` and `flex_shard_reduce_meshes`. `_decoder_fsdp_groups` already sizes the routed experts' shards over `dp_shard * cp` without EP, so they need no change. **TP declarations.** Before `flex_shard()`, the new `_declare_tensor_parallelism` reads each dense parameter's SPMD type, which is what FSDP2 lays the parameter out by: - A parameter TP splits (`V` on tp with its dim in the `PartitionSpec`) declares where its shard sits in the full parameter, as its outer layout, through flex_shard's spmd_types adapter (`spmd_types_to_global_layout`), as the expert-parallelism PR declares the EP split by hand. flex_shard composes it with the bucket's split in `get_flex_shard_global_layouts`, whose layouts the wrapped `param_init` functions use, so each initializes the full parameter and keeps this rank's part, with no change to the wrapping. - A parameter typed `R` on tp declares the storage mesh's tp group as its partial-grad group (`set_partial_grad_group`). FlexShard all-reduces its unsharded grad over that group before the reduce-scatter, in the grad's dtype. Like FSDP2 (`may_reduce_grad_outside_dp`), it keeps these grads out of the deferred upcast, so with bf16 parameters the sum runs in fp32. - A parameter typed `I` on tp, e.g. a norm weight without sequence parallelism, declares nothing. - Any other type on tp, or none, raises a `ValueError`. Untyped, a parameter would declare itself whole, and the grad norm would count it once per tp rank. - Routed experts are skipped. MoE models need `ep >= tp`, so they're typed on the sparse mesh and keep their EP layout. `fused_qkv_param_init` needed one fix. For a plain tensor under TP, it assumed the tensor is the tp rank's shard (the RL generator's case) and copied only that shard of the full fused init. The wrapped `param_init` hands it the full parameter, so it now copies a shard only when the tensor's rows don't match the full fused tensor's. **Grad norm.** FSDP2's dense grads under TP are DTensors on `(dp_shard, tp)`, or `(dp_shard_cp, tp)` with CP. Tracing `get_total_norm(...).full_tensor()` on them shows what DTensor does: each grad's local norm is partial over `dp_shard`, and over tp if TP splits the grad; stacking the norms makes a replicated norm partial over tp too, by dividing it by `tp ** (1 / p)`; the stacked norms are then reduced over `dp_shard`, then tp, each with its own power and root, since no flattened mesh spans tp; then the norm of norms. `flex_shard_grad_norm` now does exactly that on a multi-dim mesh, given which grads are replicated beyond the mesh's first dim. It divides each replicated grad's norm before stacking the norms, the same elementwise division, so that no mask is copied from the host, which would synchronize the stream. `flex_shard_reduce_meshes` maps the dense buckets' mesh to `(bucket mesh, tp)` (`DeviceMesh._concatenate`, as FSDP2 builds it), and the new `is_outer_sharded` tells `flex_shard_grad_norm` which grads TP splits: those of parameters with an outer layout, which FlexShard keeps through `to_empty()`. A replicated grad is thus counted once, as in FSDP2. On a mesh of one dim, `flex_shard_grad_norm` reduces as before, except that it now skips a mesh of size 1, as DTensor does. The probes (not part of the PR) build the model with FSDP2 on meta over a CPU mesh, with production's meshes, give each parameter a random grad as a DTensor with FSDP2's spec, and compare torchtitan's `clip_grad_norm_` on the DTensor grads against the plain local shards: - 12 random trials each at 4 ranks (gloo) for Llama 3 debug at `dp_shard=2, tp=2` with and without sequence parallelism and at `cp=2, tp=2`, Qwen3 MoE debug at `dp_shard=2, tp=2, ep=2` with and without sequence parallelism and at `dp_shard=2, cp=2`, and at 2 ranks for `tp=2` and `tp=2, ep=2`: the reduction `flex_shard_grad_norm` now does is bitwise equal in every trial. Reducing over tp before `dp_shard` differed in 1 of 12 trials for Llama 3, and one all-reduce over each flattened mesh (what the expert-parallelism PR does for routed experts) in 1 of 12 in every 4-rank case with TP. - Per norm, with 2000 replicated grads at `dp_shard=2, tp=2`: with the division, 2001 of 2001 reduced norms equal DTensor's; reducing a replicated norm over `dp_shard` alone matches in only 1248 to 1286 of them, and the total differed in 1 of 5 seeds. **Routed experts under TP.** The expert-parallelism PR reduces routed-expert grads' norm in one all-reduce over torchtitan's loss mesh, flattened from `(dp, cp)`, because DTensor finds it by layout for `(edp_shard, ep)` and uses it. That holds only without TP: with TP, `edp_shard * ep` spans the tp ranks too and the loss mesh doesn't, so DTensor reduces over `edp_shard`, then `ep` (the probe above, Qwen3 MoE at `dp_shard=2, tp=2, ep=2`, which has 4 all-reduces). Under TP, `flex_shard_reduce_meshes` now maps the expert buckets' mesh to the sparse mesh itself. A new flattened mesh over those ranks would have the dense `(dp_shard, tp)` mesh's layout: with FSDP2 in the same process, as in the parity test, DTensor would find it and reduce the dense norms in one all-reduce, unlike a production FSDP2 run. **Validation.** `validate_flex_shard_training` no longer rejects TP or CP. **Hugging Face loads under TP.** The Hugging Face load PR's `load_hf_into_local_shards` takes each region of a shard's layout as a box of the parameter, so TP's shards need no change. TP splits the last dim of row-wise parallel weights: each region of a `wo` or `w2` shard holds columns `[c0, c1)` of its rows, and the loader declares the same columns of the Hugging Face rows that hold those rows, as views of the shard. The packed QKV, the rotary permutation and `w13`, which TP splits in a leading dim, load as without TP. **Tests.** The parity test's harness now builds TP and CP models as the trainer does: `_check_matches_fsdp2` takes `tp`, `cp` and `sequence_parallel`; the loss is torchtitan's `CrossEntropyLoss` (vocab-parallel under TP) instead of `F.cross_entropy`, for all cases; inputs are preprocessed inside `activate_spmd()`, so CP shards them; the tp and cp ranks of a data-parallel rank share its data; CP models get `ContextParallelTransform` (`AllGatherKVFlexInnerAttention`) and 128 tokens per cp rank. `_assert_initialized_as_one_device` expects a TP-split shard to be its bucket chunk of the tp rank's chunk of one device's init, with buckets over `dp_shard * cp`. Two methods are new, each over 1 and 2 microbatches, with the default reshard policy: - `test_matches_fsdp2_with_tensor_parallelism`: Llama 3 debug and Qwen3 MoE debug (`ep=2`), sequence parallel, `ChunkedLossWrapper`. At CI's 4 GPUs, `dp_shard=2, tp=2`, and Qwen3's routed experts `edp_shard=2`. - `test_matches_fsdp2_with_context_parallelism`: Llama 3 debug and Qwen3 MoE debug (`ep=1`, so its routed experts shard over `dp_shard_cp`), cross-entropy. At 4 GPUs, `dp_shard=2, cp=2`. Both new methods pass on 2 GB200 GPUs with `world_size` set to 2, where they run `tp=2` or `cp=2` with `dp_shard=1`, and so does `test_matches_fsdp2`. At 2 ranks, TP leaves `dp_shard=1`, where neither backend reduce-scatters, so that run lowers the reduce-scatter count's floor to 0. Nor can 2 ranks tell the bucket's split within a TP shard from a split of the whole parameter, or one order of the grad norm's dims from the other: the 4-rank checks above and below cover those. The tests haven't run at CI's 4 GPUs: this machine has 2, and FlexShard needs CUDA. Without the partial-grad declarations, the TP method fails at step 0's grad norm (Llama 3 debug, one microbatch). Checkpointing needs no change under TP: the TP split that a parameter declares as its outer layout is part of the layouts that the checkpointing PR's state dicts declare to DCP, for the parameters and their AdamW states. `test_checkpoints_match_fsdp2` now takes `tp`, and also runs on the Qwen3 MoE debug model at `tp=2` with sequence parallelism and `ep=2`. FlexShard loads FSDP2's checkpoint, in which TP splits the dense parameters and their AdamW states in dim 0 or 1 and the norm weights are replicated over tp, matches FSDP2's parameters and AdamW states on every rank, and saves it again chunk for chunk and bit for bit, also as a bf16 export. At CI's 4 GPUs it runs `dp_shard=2, tp=2`. Both cases pass on 2 GB200 GPUs with `world_size` set to 2 (`dp_shard=1` at `tp=2`). With TP's split not declared as the outer layout, it fails at the load: DCP reports a size mismatch, saved `[4096, 256]` against current `[2048, 256]`, for `layers.0.attention.qkv_linear.wqkv.weight`. `test_hf_loads_match_fsdp2` now takes `tp` too, and also runs the Hugging Face load PR's parity check on the Llama 3 debug model at `tp=2` with sequence parallelism (at CI's 4 GPUs, `dp_shard=2, tp=2`): FSDP2 exports, both backends load, FlexShard's shards equal their boxes of the export, and 3 steps are bitwise equal. Both cases pass on 2 GB200 GPUs with `world_size` set to 2 (`dp_shard=1` at `tp=2`), and so does the expert-parallelism case. At `tp=2`, only the second tp rank's columns start past 0, so the shard check now gathers mismatches from all ranks before it asserts. Before, the failing rank stopped while the other waited in the training's collectives until the timeout. With the region's column offset dropped from the loader's chunks, the test fails on both ranks and lists that rank's 6 `wo` and 6 `w2` shards. The Hugging Face load PR's `test_hf_load_into_uneven_shards` covers shards that split the last dim at `torch.chunk`'s boundaries. **4-rank layouts.** As for EP, a one-off check builds both backends on meta for every rank of a fake process group and compares, for every parameter: FlexShard's layout with FSDP2's DTensor shard region; the mesh `flex_shard_grad_norm` reduces over with the layout of FSDP2's grad mesh; `is_outer_sharded` with whether FSDP2 shards the parameter beyond its first mesh dim; and that exactly the parameters typed `R` on tp declare tp as their partial-grad group. All match at every rank of Llama 3 debug at `dp_shard=2, tp=2` with and without sequence parallelism and at `cp=2, tp=2`, and of Qwen3 MoE debug at `dp_shard=2, tp=2, ep=2`; at ranks 0 and 3 of Qwen3 MoE at `dp_shard=2, tp=2, ep=2` without sequence parallelism, at `dp_shard=2, cp=2` and at `dp_shard=2, cp=2, ep=2`; and at ranks 0, 3, 5 and 6 of 8 for Llama 3 at `dp_shard=2, cp=2, tp=2` and Qwen3 MoE at `dp_shard=2, cp=2, tp=2, ep=4`. **FSDP2 path.** FSDP2's code doesn't change, except `fused_qkv_param_init`'s branch for plain tensors, which FSDP2's DTensor parameters don't take. `scripts/loss_compare.py 4f80bce4f <this PR> --assert-equal --metrics loss,grad_norm` (seed 42, deterministic, 50 steps, 2 GB200 GPUs) reports equal loss and grad norm at every step for llama3 `debugmodel` with `tensor_parallel_degree=2` and sequence parallelism (step-50 loss 2.94190), which runs `fused_qkv_param_init` on TP-sharded DTensors. It ran at an earlier version of this commit whose code on the FSDP2 path differs only in comments, uses flex attention because the environment has no FA4, and skips the seed checkpoint, since both runs start from seed 42 with the same parallelism. FlexShard wasn't compared with FSDP2 through the trainer this way: from a seed alone, the two backends start from different weights, and a trainer-level comparison from a shared seed checkpoint wasn't run. FlexShard runs of the same Llama 3 config with `tp=2` and with `cp=2` (accelerator graphs off) train through the trainer for 50 steps, to a step-50 loss of 2.93671 and 2.93681, against FSDP2's 2.94190 and 2.94029 from its own initialization. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: ec2cff6 Pull-Request: #6014
[ghstack-poisoned]
…FlexShardConfig() Stacked on #5842, the expert-parallelism PR, the chunked-loss PR, the checkpointing PR and the Hugging Face load PR. ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Description `validate_flex_shard_training` rejects `tensor_parallel_degree > 1` and `context_parallel_degree > 1`, so no recipe that uses TP or CP can run with FlexShard. Deleting the rejections alone would train wrong without an error. FSDP2 handles both through the storage mesh and the parameters' SPMD types (`fully_shard(..., dp_mesh_dims=...)`), while `_apply_flex_shard` asserts a 1D `dp_shard` mesh: - **CP:** each cp rank's grads cover its own tokens. FSDP2 shards over `dp_shard` and `cp` flattened into one axis, so its reduce-scatter sums them. Buckets over `dp_shard` alone would never sum the cp ranks' grads. - **TP:** `Module._parallelize` hands FlexShard each tp rank's plain local shard. A parameter typed `R` on tp has a grad that's partial over tp: the norm weights under sequence parallelism, and Qwen3's QK norms and router gate. FSDP2 types such a grad `P` and all-reduces it over tp before its reduce-scatter; FlexShard would keep each tp rank's part. Initialization would treat each tp rank's shard as if it were the whole parameter, and the grad norm would leave out the other tp ranks' shards. This PR deletes both rejections and makes training with TP or CP, also with EP, bitwise identical to FSDP2. As in #5842, nothing on the FlexShard path creates a DTensor. The earlier revision of this PR viewed every parameter under TP as FSDP2's DTensor through `as_fsdp2_dtensor`, which #5842 has since deleted, so initialization and the grad norm are reworked here. **Mesh.** `apply_fsdp_to_decoder` passes `dp_mesh_dims` to `_apply_flex_shard`, whose buckets now shard over the mesh `fully_shard` shards over: `dp_shard`, or under CP, `(dp_shard, cp)` flattened into `dp_shard_cp`, as `fully_shard` flattens it. `DeviceMesh` caches a flattened mesh by name, so both backends reduce on one process group. The new `flex_shard_bucket_mesh` picks that mesh, for `_apply_flex_shard` and `flex_shard_reduce_meshes`. `_decoder_fsdp_groups` already sizes the routed experts' shards over `dp_shard * cp` without EP, so they need no change. **TP declarations.** Before `flex_shard()`, the new `_declare_tensor_parallelism` reads each dense parameter's SPMD type, which is what FSDP2 lays the parameter out by: - A parameter TP splits (`V` on tp with its dim in the `PartitionSpec`) declares where its shard sits in the full parameter, as its outer layout, through flex_shard's spmd_types adapter (`spmd_types_to_global_layout`), as the expert-parallelism PR declares the EP split by hand. flex_shard composes it with the bucket's split in `get_flex_shard_global_layouts`, whose layouts the wrapped `param_init` functions use, so each initializes the full parameter and keeps this rank's part, with no change to the wrapping. - A parameter typed `R` on tp declares the storage mesh's tp group as its partial-grad group (`set_partial_grad_group`). FlexShard all-reduces its unsharded grad over that group before the reduce-scatter, in the grad's dtype. Like FSDP2 (`may_reduce_grad_outside_dp`), it keeps these grads out of the deferred upcast, so with bf16 parameters the sum runs in fp32. - A parameter typed `I` on tp, e.g. a norm weight without sequence parallelism, declares nothing. - Any other type on tp, or none, raises a `ValueError`. Untyped, a parameter would declare itself whole, and the grad norm would count it once per tp rank. - Routed experts are skipped. MoE models need `ep >= tp`, so they're typed on the sparse mesh and keep their EP layout. `fused_qkv_param_init` needed one fix. For a plain tensor under TP, it assumed the tensor is the tp rank's shard (the RL generator's case) and copied only that shard of the full fused init. The wrapped `param_init` hands it the full parameter, so it now copies a shard only when the tensor's rows don't match the full fused tensor's. **Grad norm.** FSDP2's dense grads under TP are DTensors on `(dp_shard, tp)`, or `(dp_shard_cp, tp)` with CP. Tracing `get_total_norm(...).full_tensor()` on them shows what DTensor does: each grad's local norm is partial over `dp_shard`, and over tp if TP splits the grad; stacking the norms makes a replicated norm partial over tp too, by dividing it by `tp ** (1 / p)`; the stacked norms are then reduced over `dp_shard`, then tp, each with its own power and root, since no flattened mesh spans tp; then the norm of norms. `flex_shard_grad_norm` now does exactly that on a multi-dim mesh, given which grads are replicated beyond the mesh's first dim. It divides each replicated grad's norm before stacking the norms, the same elementwise division, so that no mask is copied from the host, which would synchronize the stream. `flex_shard_reduce_meshes` maps the dense buckets' mesh to `(bucket mesh, tp)` (`DeviceMesh._concatenate`, as FSDP2 builds it), and the new `is_outer_sharded` tells `flex_shard_grad_norm` which grads TP splits: those of parameters with an outer layout, which FlexShard keeps through `to_empty()`. A replicated grad is thus counted once, as in FSDP2. On a mesh of one dim, `flex_shard_grad_norm` reduces as before, except that it now skips a mesh of size 1, as DTensor does. The probes (not part of the PR) build the model with FSDP2 on meta over a CPU mesh, with production's meshes, give each parameter a random grad as a DTensor with FSDP2's spec, and compare torchtitan's `clip_grad_norm_` on the DTensor grads against the plain local shards: - 12 random trials each at 4 ranks (gloo) for Llama 3 debug at `dp_shard=2, tp=2` with and without sequence parallelism and at `cp=2, tp=2`, Qwen3 MoE debug at `dp_shard=2, tp=2, ep=2` with and without sequence parallelism and at `dp_shard=2, cp=2`, and at 2 ranks for `tp=2` and `tp=2, ep=2`: the reduction `flex_shard_grad_norm` now does is bitwise equal in every trial. Reducing over tp before `dp_shard` differed in 1 of 12 trials for Llama 3, and one all-reduce over each flattened mesh (what the expert-parallelism PR does for routed experts) in 1 of 12 in every 4-rank case with TP. - Per norm, with 2000 replicated grads at `dp_shard=2, tp=2`: with the division, 2001 of 2001 reduced norms equal DTensor's; reducing a replicated norm over `dp_shard` alone matches in only 1248 to 1286 of them, and the total differed in 1 of 5 seeds. **Routed experts under TP.** The expert-parallelism PR reduces routed-expert grads' norm in one all-reduce over torchtitan's loss mesh, flattened from `(dp, cp)`, because DTensor finds it by layout for `(edp_shard, ep)` and uses it. That holds only without TP: with TP, `edp_shard * ep` spans the tp ranks too and the loss mesh doesn't, so DTensor reduces over `edp_shard`, then `ep` (the probe above, Qwen3 MoE at `dp_shard=2, tp=2, ep=2`, which has 4 all-reduces). Under TP, `flex_shard_reduce_meshes` now maps the expert buckets' mesh to the sparse mesh itself. A new flattened mesh over those ranks would have the dense `(dp_shard, tp)` mesh's layout: with FSDP2 in the same process, as in the parity test, DTensor would find it and reduce the dense norms in one all-reduce, unlike a production FSDP2 run. **Validation.** `validate_flex_shard_training` no longer rejects TP or CP. **Hugging Face loads under TP.** The Hugging Face load PR's `load_hf_into_local_shards` takes each region of a shard's layout as a box of the parameter, so TP's shards need no change. TP splits the last dim of row-wise parallel weights: each region of a `wo` or `w2` shard holds columns `[c0, c1)` of its rows, and the loader declares the same columns of the Hugging Face rows that hold those rows, as views of the shard. The packed QKV, the rotary permutation and `w13`, which TP splits in a leading dim, load as without TP. **Tests.** The parity test's harness now builds TP and CP models as the trainer does: `_check_matches_fsdp2` takes `tp`, `cp` and `sequence_parallel`; the loss is torchtitan's `CrossEntropyLoss` (vocab-parallel under TP) instead of `F.cross_entropy`, for all cases; inputs are preprocessed inside `activate_spmd()`, so CP shards them; the tp and cp ranks of a data-parallel rank share its data; CP models get `ContextParallelTransform` (`AllGatherKVFlexInnerAttention`) and 128 tokens per cp rank. `_assert_initialized_as_one_device` expects a TP-split shard to be its bucket chunk of the tp rank's chunk of one device's init, with buckets over `dp_shard * cp`. Two methods are new, each over 1 and 2 microbatches, with the default reshard policy: - `test_matches_fsdp2_with_tensor_parallelism`: Llama 3 debug and Qwen3 MoE debug (`ep=2`), sequence parallel, `ChunkedLossWrapper`. At CI's 4 GPUs, `dp_shard=2, tp=2`, and Qwen3's routed experts `edp_shard=2`. - `test_matches_fsdp2_with_context_parallelism`: Llama 3 debug and Qwen3 MoE debug (`ep=1`, so its routed experts shard over `dp_shard_cp`), cross-entropy. At 4 GPUs, `dp_shard=2, cp=2`. Both new methods pass on 2 GB200 GPUs with `world_size` set to 2, where they run `tp=2` or `cp=2` with `dp_shard=1`, and so does `test_matches_fsdp2`. At 2 ranks, TP leaves `dp_shard=1`, where neither backend reduce-scatters, so that run lowers the reduce-scatter count's floor to 0. Nor can 2 ranks tell the bucket's split within a TP shard from a split of the whole parameter, or one order of the grad norm's dims from the other: the 4-rank checks above and below cover those. The tests haven't run at CI's 4 GPUs: this machine has 2, and FlexShard needs CUDA. Without the partial-grad declarations, the TP method fails at step 0's grad norm (Llama 3 debug, one microbatch). Checkpointing needs no change under TP: the TP split that a parameter declares as its outer layout is part of the layouts that the checkpointing PR's state dicts declare to DCP, for the parameters and their AdamW states. `test_checkpoints_match_fsdp2` now takes `tp`, and also runs on the Qwen3 MoE debug model at `tp=2` with sequence parallelism and `ep=2`. FlexShard loads FSDP2's checkpoint, in which TP splits the dense parameters and their AdamW states in dim 0 or 1 and the norm weights are replicated over tp, matches FSDP2's parameters and AdamW states on every rank, and saves it again chunk for chunk and bit for bit, also as a bf16 export. At CI's 4 GPUs it runs `dp_shard=2, tp=2`. Both cases pass on 2 GB200 GPUs with `world_size` set to 2 (`dp_shard=1` at `tp=2`). With TP's split not declared as the outer layout, it fails at the load: DCP reports a size mismatch, saved `[4096, 256]` against current `[2048, 256]`, for `layers.0.attention.qkv_linear.wqkv.weight`. `test_hf_loads_match_fsdp2` now takes `tp` too, and also runs the Hugging Face load PR's parity check on the Llama 3 debug model at `tp=2` with sequence parallelism (at CI's 4 GPUs, `dp_shard=2, tp=2`): FSDP2 exports, both backends load, FlexShard's shards equal their boxes of the export, and 3 steps are bitwise equal. Both cases pass on 2 GB200 GPUs with `world_size` set to 2 (`dp_shard=1` at `tp=2`), and so does the expert-parallelism case. At `tp=2`, only the second tp rank's columns start past 0, so the shard check now gathers mismatches from all ranks before it asserts. Before, the failing rank stopped while the other waited in the training's collectives until the timeout. With the region's column offset dropped from the loader's chunks, the test fails on both ranks and lists that rank's 6 `wo` and 6 `w2` shards. The Hugging Face load PR's `test_hf_load_into_uneven_shards` covers shards that split the last dim at `torch.chunk`'s boundaries. **4-rank layouts.** As for EP, a one-off check builds both backends on meta for every rank of a fake process group and compares, for every parameter: FlexShard's layout with FSDP2's DTensor shard region; the mesh `flex_shard_grad_norm` reduces over with the layout of FSDP2's grad mesh; `is_outer_sharded` with whether FSDP2 shards the parameter beyond its first mesh dim; and that exactly the parameters typed `R` on tp declare tp as their partial-grad group. All match at every rank of Llama 3 debug at `dp_shard=2, tp=2` with and without sequence parallelism and at `cp=2, tp=2`, and of Qwen3 MoE debug at `dp_shard=2, tp=2, ep=2`; at ranks 0 and 3 of Qwen3 MoE at `dp_shard=2, tp=2, ep=2` without sequence parallelism, at `dp_shard=2, cp=2` and at `dp_shard=2, cp=2, ep=2`; and at ranks 0, 3, 5 and 6 of 8 for Llama 3 at `dp_shard=2, cp=2, tp=2` and Qwen3 MoE at `dp_shard=2, cp=2, tp=2, ep=4`. **FSDP2 path.** FSDP2's code doesn't change, except `fused_qkv_param_init`'s branch for plain tensors, which FSDP2's DTensor parameters don't take. `scripts/loss_compare.py 4f80bce4f <this PR> --assert-equal --metrics loss,grad_norm` (seed 42, deterministic, 50 steps, 2 GB200 GPUs) reports equal loss and grad norm at every step for llama3 `debugmodel` with `tensor_parallel_degree=2` and sequence parallelism (step-50 loss 2.94190), which runs `fused_qkv_param_init` on TP-sharded DTensors. It ran at an earlier version of this commit whose code on the FSDP2 path differs only in comments, uses flex attention because the environment has no FA4, and skips the seed checkpoint, since both runs start from seed 42 with the same parallelism. FlexShard wasn't compared with FSDP2 through the trainer this way: from a seed alone, the two backends start from different weights, and a trainer-level comparison from a shared seed checkpoint wasn't run. FlexShard runs of the same Llama 3 config with `tp=2` and with `cp=2` (accelerator graphs off) train through the trainer for 50 steps, to a step-50 loss of 2.93671 and 2.93681, against FSDP2's 2.94190 and 2.94029 from its own initialization. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: e2a705a Pull-Request: #6014
[ghstack-poisoned]
|
@claude review this pr |
|
Claude finished @anshul-si's task in 4m 36s —— View job Request changes: the PR description and its numerics describe a different implementation from HEAD, and TP + CP is now accepted but not tested. Review |
There was a problem hiding this comment.
Verdict: Request changes -- the description, its numerics and its revert-guard evidence describe a different implementation from the code at HEAD, and validation now accepts TP + CP, which HEAD doesn't test.
What this PR does. It drops the TP and CP rejection in validate_flex_shard_training. Under CP, FlexShard's dense buckets now shard over the flattened dp_shard_cp mesh (flex_shard_bucket_mesh). Under TP, each dense parameter's SPMD type is read before flex_shard():
V/S(d)on tp declares the TP split as the parameter's outer layout.Ron tp declares tp as its partial-grad group.
For the grad norm, flex_shard_reduce_meshes maps the dense bucket mesh to (bucket mesh, tp). flex_shard_grad_norm then reduces over each mesh axis in turn and copies DTensor's R->P scaling for replicated parameters.
Example.
config.parallelism.tensor_parallel_degree = 2 # dp_shard=2 on 4 GPUs
config.parallelism.fsdp_backend = FlexShardConfig()
# before: ValueError ... does not support parallelism.tensor_parallel_degree=2 yet.
# after: attention_norm.weight (R on tp under SP) -> set_partial_grad_group(tp)
# wqkv.weight (V on tp, dim 0) -> outer layout rows [384*tp_rank, ...)
# grad norm: per-bucket norms all-reduced over dp_shard, then over tpMust fix
-
The PR description doesn't match the code at HEAD. Several things it describes are missing from the diff:
as_fsdp2_dtensor, the_StridedShardview and its module-level mesh map;- the
decoder_fsdp_groupsstorage-mesh change; - the
fsdp_backenddocstring change intorchtitan/config/parallelism.py; - three of the five named tests (
..._without_sequence_parallelism,..._tensor_and_context_parallelism,test_checkpoints_across_backends_with_tensor_parallelism).
HEAD instead takes a grad-norm-mesh approach (
flex_shard_reduce_meshes,flex_shard_grad_norm,is_outer_sharded). The description says every run was at4aa9fed1c, "whose non-test code differs from it only in comments". That can't be true for this diff, so neither the loss_compare tables nor the revert table back HEAD. Please rewrite What changed, Alternatives and Testing for HEAD, and rerunloss_compare.py --assert-equalat HEAD for at least TP+SP, CP and Qwen3tp=2, ep=2. The "Summary (human-written)" section is also still empty. -
tests/unit_tests/gpu/distributed/test_flex_shard_fsdp.py:440-- validation now accepts TP + CP and TP without SP, but neither is tested. Fix: add one Llama 3cp=2, tp=2, SP offcase. -
torchtitan/distributed/fsdp.py:510-- workarounds for upstream gaps have noTODO:- the private
flex_shard.layout_adaptersimport and the TP declarations done in torchtitan; DeviceMesh._concatenate;- the hand-copied
_NormPartialscaling.
- the private
Should consider
torchtitan/distributed/flex_shard_fsdp.py:203--is_outer_shardedis used only in this module: make it_is_outer_shardedor inline it.tests/unit_tests/gpu/distributed/test_flex_shard_fsdp.py:728-- thetpparametrization of the uneven-shard loader test reaches no new code. Drop it.
Details
Necessity gate. It passes. The problem is real at the base: validate_flex_shard_training rejects tensor_parallel_degree > 1 and context_parallel_degree > 1, and FlexShard with buckets over dp_shard alone would silently miss the cp and tp reductions. Reading each parameter's SPMD type, the same source FSDP2 uses, is a better choice than reading other modules' _sharding_config. The long-term owner is FlexShard itself (see must-fix 3).
Checked and fine at HEAD:
- Skipping routed experts in
_declare_tensor_parallelismis safe.ep < tpfor MoE raises intorchtitan/config/validation.py:191andmodels/common/decoder.py:252, so with tp > 1 the routed experts are always on the sparse mesh. - The R->P division by
size ** (1/p)is DTensor's_NormPartial._partition_value. Forinfit's a no-op (size ** 0 == 1). - A bucket whose parameters are all replicated reduces only over dim 0. That matches a DTensor norm that is
Replicateon tp. - The
config_utils.pyshape test (t.shape[0] != fused.shape[0]) still takes the RL path for plain TP shards, and FlexShard's full-tensor init no longer goes through it. _decoder_fsdp_groupsalready sizes routed-expert sharding bydp_shard * cp, so the description'sdecoder_fsdp_groupschange isn't needed at HEAD.
Note. flex_shard_reduce_meshes is recomputed on every clip_grad_norm_ call, and now calls DeviceMesh._concatenate each time. The per-call recompute isn't new (the edp entry already did it). This is cheap only if _concatenate reuses existing process groups.
Not verified: bitwise parity at HEAD (needs GPUs); whether DeviceMesh._concatenate creates new process groups on each call; FlexShard's fp32 handling of partial-grad all-reduces.
A maintainer still needs to review: this touches torchtitan/distributed/fsdp.py and models/common/config_utils.py.
| from flex_shard import set_partial_grad_group | ||
|
|
||
| # pyrefly: ignore [missing-import] | ||
| from flex_shard.layout_adapters.spmd_types import spmd_types_to_global_layout |
There was a problem hiding this comment.
This adds several upstream workarounds, and none of them has a TODO (principle 3). The PR description says "TODO link, the same issue as the EP layout's", but no TODO was added anywhere in the non-test code:
- this import from
flex_shard.layout_adapters.spmd_types, which the description says flex_shard doesn't export; - the TP declarations themselves (
_declare_tensor_parallelism). They should come from FlexShard reading the parameters' SPMD types, the wayfully_shard(..., dp_mesh_dims=...)reads them; DeviceMesh._concatenateinflex_shard_reduce_meshes(flex_shard_fsdp.py:128), a private torch API;flex_shard_grad_norm(flex_shard_fsdp.py:174-180), which copies DTensor's_NormPartialR->P scaling (size ** (1/p)) by hand to stay bitwise equal. If DTensor's partial-norm handling changes upstream, FlexShard's grad norm silently stops matching FSDP2's.
Fix: add one TODO(<flex_shard issue link>) here that covers the declarations and the private import, and a short TODO at each of the other two places.
| @with_comms | ||
| def test_matches_fsdp2_with_context_parallelism(self): | ||
| # Each cp rank's grads cover its own tokens. FSDP2 sums them in its | ||
| # reduce-scatter over dp_shard and cp, flattened into one axis, and so | ||
| # do FlexShard's buckets. Qwen3's routed experts shard over it too. | ||
| self._check_matches_fsdp2( | ||
| ep=1, | ||
| cp=2, | ||
| cases=product( | ||
| ( | ||
| (build_llama3_config, "debugmodel"), | ||
| (build_qwen3_config, "debugmodel_moe"), | ||
| ), | ||
| ("default",), | ||
| (1, 2), | ||
| ), | ||
| ) |
There was a problem hiding this comment.
After this PR, validate_flex_shard_training accepts TP + CP and TP without sequence parallelism, but neither is tested at HEAD:
- The TP test only runs with
sequence_parallel=True. - The CP test only runs with
tp=1.
So two paths have no coverage:
- the
(dp_shard_cp, tp)mesh thatflex_shard_reduce_meshesbuilds for the grad norm under TP + CP; - the
I-typed branch of_declare_tensor_parallelism.
The description lists test_matches_fsdp2_with_tensor_and_context_parallelism and ..._without_sequence_parallelism, but they aren't in the file.
The cheapest fix extends an existing test rather than adding two. Add one Llama 3 case at cp=2, tp=2, sequence_parallel=False. At 4 ranks the buckets still reduce-scatter over dp_shard_cp (size 2). Qwen3 can't join that case because it needs ep >= tp. Alternatively, keep rejecting TP + CP until it is tested.
| return total_norm | ||
|
|
||
|
|
||
| def is_outer_sharded(param: torch.Tensor) -> bool: |
There was a problem hiding this comment.
is_outer_sharded is used only inside this module (by flex_shard_grad_norm) and isn't listed in __all__. Under the naming rule it should be _is_outer_sharded. It could also be inlined at its one call site, since it's two lines plus an import.
| @pytest.mark.parametrize("tp", [1, 2]) | ||
| @pytest.mark.parametrize("group_bytes", [1 << 30, 1]) | ||
| def test_hf_load_into_uneven_shards(tmp_path, group_bytes: int) -> None: | ||
| # Each of 5 simulated ranks holds the chunk torch.chunk gives it of each | ||
| # parameter's bucket dim (1 for w13, else 0), so shards are uneven and end | ||
| # inside attention heads, unlike the parity tests'. Each rank loads its | ||
| # shards without a process group, with all parameters in one group or each | ||
| # alone. | ||
| def test_hf_load_into_uneven_shards(tmp_path, group_bytes: int, tp: int) -> None: |
There was a problem hiding this comment.
The tp parametrization here doubles this test without reaching new code:
load_hf_into_local_shardsdoesn't care about layouts. It copies whatever boxes the layouts declare, and doesn't know which dims TP split.- The split it simulates (the last dim of every tensor with
ndim > 1) isn't TP's real layout. For example, TP splitswqkvandw13in a leading dim. test_hf_loads_match_fsdp2(tp=2)already loads real TP x FSDP boxes, which have offsets in two dims, end to end.
Suggest dropping this parametrization (tests.md: no duplicate coverage).
[ghstack-poisoned]
|
@claude review this pr |
|
Claude finished @anshul-si's task in 3m 58s —— View job Approve -- please write the human summary and add issue links to the new TODOs before merging. Review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The earlier review's must-fix items are resolved at de4db4c, and I found no correctness problem in the TP/CP declarations or the grad norm.
What this PR does. It stops validate_flex_shard_training from rejecting TP and CP.
- CP: FlexShard's dense buckets shard over
dp_shardandcp, flattened intodp_shard_cp(flex_shard_bucket_mesh). - TP: each dense parameter's SPMD type is read before
flex_shard().V/S(d)on tp: TP's split becomes the parameter's outer layout.Ron tp: tp becomes its partial-grad group.Ion tp: nothing is declared.
- Grad norm: it reduces over
(bucket mesh, tp)one axis at a time, scaling replicated norms the way DTensor does.
Example.
config.parallelism.tensor_parallel_degree = 2 # dp_shard=2 on 4 GPUs, SP on
config.parallelism.fsdp_backend = FlexShardConfig()
# before: ValueError ... does not support parallelism.tensor_parallel_degree=2 yet.
# after: wqkv.weight (V on tp, dim 0) -> outer layout rows [384*tp_rank, +384)
# attention_norm.weight (R on tp) -> grad all-reduced over tp before reduce-scatter
# grad norm: stacked norms all-reduced over dp_shard, then tpMust fix
- The "Summary (human-written)" section is still empty. The author has to write it; agents don't.
torchtitan/distributed/fsdp.py:509-- the new upstream-gap TODOs have no issue links (this one,flex_shard_fsdp.py:129,flex_shard_fsdp.py:176).
Should consider
tests/unit_tests/gpu/distributed/test_flex_shard_fsdp.py:441-- the TP-without-SP test duplicates the TP+CP test, which also runs SP off. Fold them into one test.
Details
Earlier review, at HEAD:
- Description vs code: resolved. The description now describes the grad-norm-mesh design. Between the earlier reviewed revision and HEAD, the PR's non-test code differs only by the three TODOs and the
_is_outer_shardedrename (the rest of that diff comes from the base update), which matches what the description says about where the numerics ran. - TP + CP and TP without SP are now tested.
- The TODOs are present, but without links.
is_outer_shardedis now_is_outer_sharded.- The
tpparametrization oftest_hf_load_into_uneven_shardsis dropped.
Checked at HEAD:
- Routed experts skipped in
_declare_tensor_parallelism: MoE withep < tpraises (config/validation.py:191,models/common/decoder.py:252), so under TP they are always on the sparse mesh. - Models now accepted under TP: those that don't override
_apply_fsdpand pass the other checks. Kimi K3 and Qwen3.5 still fail the check (KDA/GDNpreserve_dtype_params). DeepSeek V4 and multimodal models override_apply_fsdp. So the description's claim that their TP-replicated parameters are rejected today holds. GPT-OSS is accepted and wasn't re-run at this revision, as the description says. shard_on_cp_axis=Falseis used only byMultimodalModel, which overrides_apply_fsdp. Soflex_shard_reduce_meshes, which callsresolve_fsdp_meshwith the default, agrees with the buckets' mesh for every accepted model.- The
config_utils.pyrow test still chunks plain TP shards (RL generator). It is needed: otherwise FlexShard's full-tensor init under an active tp SPMD mesh would be chunked wrongly. - The R->P scale is
size ** (1/p), which is a no-op forinf. Size-1 dims are skipped after scaling by 1.
Not verified: bitwise parity at HEAD (needs GPUs); FlexShard's fp32 handling of partial-grad all-reduces (in flex_shard, outside this diff).
A maintainer still needs to review: this touches torchtitan/distributed/fsdp.py and models/common/config_utils.py.
| # TODO: Drop once flex_shard() reads the parameters' SPMD types itself, as | ||
| # fully_shard(..., dp_mesh_dims=...) does. Until then torchtitan declares TP's | ||
| # layouts, through a flex_shard adapter that flex_shard doesn't export. |
There was a problem hiding this comment.
The three new upstream-gap TODOs don't link an issue. Principle 3 asks for an upstream issue link on each one:
- this one: flex_shard doesn't read SPMD types itself, and the adapter is private;
flex_shard_fsdp.py:129:DeviceMesh._concatenate;flex_shard_fsdp.py:176: the copied_NormPartialscaling.
The last one matters most. If DTensor's partial-norm handling changes, FlexShard's grad norm stops being bitwise equal to FSDP2's without any error, and the parity tests are the only thing that would notice.
Fix: open a flex_shard issue that covers the SPMD-type reading and the grad norm, and a PyTorch issue for a public mesh-concatenate API. Then write each TODO as TODO(<link>).
| @with_comms | ||
| def test_matches_fsdp2_with_tensor_parallelism_without_sequence_parallelism( | ||
| self, | ||
| ): | ||
| # Without sequence parallelism, the norm weights are typed I on tp: each | ||
| # tp rank computes their whole grad, so neither backend all-reduces it. | ||
| self._check_matches_fsdp2( | ||
| ep=1, | ||
| tp=2, | ||
| cases=product([(build_llama3_config, "debugmodel")], ("default",), (1, 2)), | ||
| ) | ||
|
|
||
| @with_comms | ||
| def test_matches_fsdp2_with_tensor_and_context_parallelism(self): | ||
| # Needs 4 ranks. The buckets shard over dp_shard and cp, flattened, and | ||
| # the grad norm of the dense parameters reduces over that mesh, then tp. | ||
| self._check_matches_fsdp2( | ||
| ep=1, | ||
| tp=2, | ||
| cp=2, | ||
| cases=product([(build_llama3_config, "debugmodel")], ("default",), (1,)), | ||
| ) |
There was a problem hiding this comment.
The first test here duplicates coverage that the second already has. test_matches_fsdp2_with_tensor_and_context_parallelism also runs Llama 3 with sequence_parallel=False, so it already covers:
- the
I-on-tp branch of_declare_tensor_parallelism; - a dense
(bucket mesh, tp)grad-norm mesh.
On 4 ranks its bucket mesh is dp_shard_cp of size 2, so it still reduce-scatters. The plain (dp_shard, tp) mesh is covered by test_matches_fsdp2_with_tensor_parallelism.
What the SP-off test adds on its own is the two-microbatch case. That costs a separate pair of FSDP2 and FlexShard builds on 4 GPUs.
Suggest folding them into one test (tests.md: one test that composes features beats several):
| @with_comms | |
| def test_matches_fsdp2_with_tensor_parallelism_without_sequence_parallelism( | |
| self, | |
| ): | |
| # Without sequence parallelism, the norm weights are typed I on tp: each | |
| # tp rank computes their whole grad, so neither backend all-reduces it. | |
| self._check_matches_fsdp2( | |
| ep=1, | |
| tp=2, | |
| cases=product([(build_llama3_config, "debugmodel")], ("default",), (1, 2)), | |
| ) | |
| @with_comms | |
| def test_matches_fsdp2_with_tensor_and_context_parallelism(self): | |
| # Needs 4 ranks. The buckets shard over dp_shard and cp, flattened, and | |
| # the grad norm of the dense parameters reduces over that mesh, then tp. | |
| self._check_matches_fsdp2( | |
| ep=1, | |
| tp=2, | |
| cp=2, | |
| cases=product([(build_llama3_config, "debugmodel")], ("default",), (1,)), | |
| ) | |
| @with_comms | |
| def test_matches_fsdp2_with_tensor_and_context_parallelism(self): | |
| # Needs 4 ranks. The buckets shard over dp_shard and cp, flattened, and | |
| # the grad norm of the dense parameters reduces over that mesh, then tp. | |
| # Without sequence parallelism, the norm weights are typed I on tp, so | |
| # neither backend all-reduces their grads. | |
| self._check_matches_fsdp2( | |
| ep=1, | |
| tp=2, | |
| cp=2, | |
| cases=product([(build_llama3_config, "debugmodel")], ("default",), (1, 2)), | |
| ) |
Stack from ghstack (oldest at bottom):
Stacked on #5842, the expert-parallelism PR, the chunked-loss PR, the
checkpointing PR and the Hugging Face load PR.
Summary (human-written)
Description
FlexShardConfig.validate_modelrejectstensor_parallel_degree > 1andcontext_parallel_degree > 1, so no recipe that uses TP or CP can run with FlexShard.Deleting the rejections alone would train wrong without an error. FSDP2 handles both
through the storage mesh and the parameters' SPMD types (
fully_shard(..., dp_mesh_dims=...)), whileFlexShardConfig.apply_to_decoderasserts a 1Ddp_shardmesh:
dp_shardandcpflattened into one axis, so its reduce-scatter sums them. Buckets overdp_shardalone would never sum the cp ranks' grads.Module._parallelizehands FlexShard each tp rank's plain local shard. Aparameter typed
Ron tp has a grad that's partial over tp: the norm weights undersequence parallelism, and Qwen3's QK norms and router gate. FSDP2 types such a grad
Pand all-reduces it over tp before its reduce-scatter; FlexShard would keep eachtp rank's part. Initialization would treat each tp rank's shard as if it were the
whole parameter, and the grad norm would leave out the other tp ranks' shards.
This PR deletes both rejections and makes training with TP or CP, also with EP, bitwise
identical to FSDP2. As in #5842, nothing on the FlexShard path creates a DTensor. The
earlier revision of this PR viewed every parameter under TP as FSDP2's DTensor through
as_fsdp2_dtensor, which #5842 has since deleted, so initialization and the grad normare reworked here.
Mesh.
FlexShardConfig.apply_to_decoderpassesdp_mesh_dimstoFlexShardConfig.apply_to_decoder, whose buckets now shard over the meshfully_shardshards over:
dp_shard, or under CP,(dp_shard, cp)flattened intodp_shard_cp, asfully_shardflattens it.DeviceMeshcaches a flattened mesh by name, so bothbackends reduce on one process group. The new
FlexShardConfig._bucket_meshpicks thatmesh, for
FlexShardConfig.apply_to_decoderandFlexShardConfig._reduce_meshes.decoder_sharding_unitsalready sizes the routed experts' shards overdp_shard * cpwithout EP, so they need no change.
TP declarations. Before
flex_shard(), the newFlexShardConfig._declare_tensor_parallelism, inflex_shard_backend.py, reads eachdense parameter's SPMD type, which is what FSDP2 lays the parameter out by:
Von tp with its dim in thePartitionSpec) declares whereits shard sits in the full parameter, as its outer layout, through flex_shard's
spmd_types adapter (
spmd_types_to_global_layout), as the expert-parallelism PRdeclares the EP split by hand. flex_shard composes it with the bucket's split in
get_flex_shard_global_layouts, whose layouts the wrappedparam_initfunctionsuse, so each initializes the full parameter and keeps this rank's part, with no
change to the wrapping.
Ron tp declares the storage mesh's tp group as its partial-gradgroup (
set_partial_grad_group). FlexShard all-reduces its unsharded grad over thatgroup before the reduce-scatter, in the grad's dtype. Like FSDP2
(
may_reduce_grad_outside_dp), it keeps these grads out of the deferred upcast, sowith bf16 parameters the sum runs in fp32.
Ion tp, e.g. a norm weight without sequence parallelism,declares nothing.
ValueError. Untyped, a parameter woulddeclare itself whole, and the grad norm would count it once per tp rank.
ep >= tp, so they're typed on thesparse mesh and keep their EP layout.
fused_qkv_param_initneeded one fix. For a plain tensor under TP, it assumed thetensor is the tp rank's shard (the RL generator's case) and copied only that shard of
the full fused init. The wrapped
param_inithands it the full parameter, so it nowcopies a shard only when the tensor's rows don't match the full fused tensor's.
Grad norm. FSDP2's dense grads under TP are DTensors on
(dp_shard, tp), or(dp_shard_cp, tp)with CP. Tracingget_total_norm(...).full_tensor()on them showswhat DTensor does: each grad's local norm is partial over
dp_shard, and over tp if TPsplits the grad; stacking the norms makes a replicated norm partial over tp too, by
dividing it by
tp ** (1 / p); the stacked norms are then reduced overdp_shard, thentp, each with its own power and root, since no flattened mesh spans tp; then the norm of
norms.
FlexShardConfig._grad_normnow does exactly that on a multi-dim mesh, givenwhich grads are replicated beyond the mesh's first dim. It divides each replicated
grad's norm before stacking the norms, the same elementwise division, so that no mask is
copied from the host, which would synchronize the stream.
_reduce_meshesmaps thedense buckets' mesh to
(bucket mesh, tp)(DeviceMesh._concatenate, as FSDP2 buildsit), and the new
_is_outer_shardedtells_grad_normwhich grads TP splits: those ofparameters with an outer layout, which FlexShard keeps through
to_empty(). Areplicated grad is thus counted once, as in FSDP2. On a mesh of one dim,
_grad_normreduces as before, except that it now skips a mesh of size 1, as DTensor does.
The probes (not part of the PR) build the model with FSDP2 on meta over a CPU mesh,
with production's meshes, give each parameter a random grad as a DTensor with FSDP2's
spec, and compare torchtitan's
clip_grad_norm_on the DTensor grads against the plainlocal shards:
dp_shard=2, tp=2withand without sequence parallelism and at
cp=2, tp=2, Qwen3 MoE debug atdp_shard=2, tp=2, ep=2with and without sequence parallelism and atdp_shard=2, cp=2, and at 2ranks for
tp=2andtp=2, ep=2: the reduction_grad_normnow does isbitwise equal in every trial. Reducing over tp before
dp_sharddiffered in 1 of 12trials for Llama 3, and one all-reduce over each flattened mesh (what the
expert-parallelism PR does for routed experts) in 1 of 12 in every 4-rank case with
TP.
dp_shard=2, tp=2: with the division, 2001of 2001 reduced norms equal DTensor's; reducing a replicated norm over
dp_shardalone matches in only 1248 to 1286 of them, and the total differed in 1 of 5 seeds.
Routed experts under TP. The expert-parallelism PR reduces routed-expert grads' norm
in one all-reduce over torchtitan's loss mesh, flattened from
(dp, cp), becauseDTensor finds it by layout for
(edp_shard, ep)and uses it. That holds only withoutTP: with TP,
edp_shard * epspans the tp ranks too and the loss mesh doesn't, soDTensor reduces over
edp_shard, thenep(the probe above, Qwen3 MoE atdp_shard=2, tp=2, ep=2, which has 4 all-reduces). Under TP,_reduce_meshesnow maps the expert buckets' mesh to the sparse mesh itself. A new flattened mesh over
those ranks would have the dense
(dp_shard, tp)mesh's layout: with FSDP2 in the sameprocess, as in the parity test, DTensor would find it and reduce the dense norms in one
all-reduce, unlike a production FSDP2 run.
Validation.
FlexShardConfig.validate_modelno longer rejects TP or CP.Hugging Face loads under TP. The Hugging Face load PR's
load_hf_into_local_shardsloads full tensors and copies each region of a shard's layout from them, so TP's shards
need no change: TP's split, declared as the outer layout before
flex_shard(), is partof the layouts flex_shard reports.
Tests. The parity test's harness now builds TP and CP models as the trainer does:
_check_matches_fsdp2takestp,cpandsequence_parallel; the loss istorchtitan's
CrossEntropyLoss(vocab-parallel under TP) instead ofF.cross_entropy,for all cases; inputs are preprocessed inside
activate_spmd(), so CP shards them; thetp and cp ranks of a data-parallel rank share its data; CP models get
ContextParallelTransform(AllGatherKVFlexInnerAttention) and 128 tokens per cprank.
_assert_initialized_as_one_deviceexpects a TP-split shard to be its bucketchunk of the tp rank's chunk of one device's init, with buckets over
dp_shard * cp.Four methods are new, with the default reshard policy:
test_matches_fsdp2_with_tensor_parallelism: Llama 3 debug and Qwen3 MoE debug(
ep=2), sequence parallel,ChunkedLossWrapper, over 1 and 2 microbatches. AtCI's 4 GPUs,
dp_shard=2, tp=2, and Qwen3's routed expertsedp_shard=2.test_matches_fsdp2_with_tensor_parallelism_without_sequence_parallelism: Llama 3debug at
tp=2without sequence parallelism, over 1 and 2 microbatches. The normweights are then typed
Ion tp, so neither backend all-reduces their grads. At 4GPUs,
dp_shard=2, tp=2.test_matches_fsdp2_with_context_parallelism: Llama 3 debug and Qwen3 MoE debug(
ep=1, so its routed experts shard overdp_shard_cp), cross-entropy, over 1 and 2microbatches. At 4 GPUs,
dp_shard=2, cp=2.test_matches_fsdp2_with_tensor_and_context_parallelism: Llama 3 debug atcp=2, tp=2, one microbatch. It needs 4 ranks: the buckets shard overdp_shard_cp, andthe dense grad norm reduces over it, then tp.
At CI's 4 GPUs (4 GB300s, each method run alone under torchrun), all four pass, and so
do the Hugging Face load test's
tp=1andtp=2cases below. On 2 GB200 GPUs withworld_sizeset to 2, where they runtp=2orcp=2withdp_shard=1, the methodsother than TP with CP pass, and so does
test_matches_fsdp2. At 2 ranks, TP leavesdp_shard=1, where neither backend reduce-scatters, so that run lowers thereduce-scatter count's floor to 0. Without the partial-grad declarations, the TP method
fails at step 0's grad norm (Llama 3 debug, one microbatch).
Checkpointing needs no change under TP: the TP split that a parameter declares as its
outer layout is part of the layouts that the checkpointing PR's state dicts declare to
DCP, for the parameters and their AdamW states.
test_checkpoints_match_fsdp2nowtakes
tp, and also runs on the Qwen3 MoE debug model attp=2with sequenceparallelism and
ep=2. FlexShard loads FSDP2's checkpoint, in which TP splits the denseparameters and their AdamW states in dim 0 or 1 and the norm weights are replicated
over tp, matches FSDP2's parameters and AdamW states on every rank, and saves it again
chunk for chunk and bit for bit, also as a bf16 export. At CI's 4 GPUs it runs
dp_shard=2, tp=2. Both cases pass on 2 GB200 GPUs withworld_sizeset to 2(
dp_shard=1attp=2). With TP's split not declared as the outer layout, itfails at the load: DCP reports a size mismatch, saved
[4096, 256]against current[2048, 256], forlayers.0.attention.qkv_linear.wqkv.weight.test_hf_loads_match_fsdp2now takestptoo, and also runs the Hugging Face load PR'sparity check on the Llama 3 debug model at
tp=2with sequence parallelism (at CI's 4GPUs,
dp_shard=2, tp=2), with each parameter as a group of its own: FlexShard's shardsmust equal their boxes of FSDP2's export. Both cases pass on 2 GB200 GPUs with
world_sizeset to 2 (dp_shard=1attp=2), and so does the expert-parallelismtest.
4-rank layouts. As for EP, a one-off check builds both backends on meta for every
rank of a fake process group and compares, for every parameter: FlexShard's layout with
FSDP2's DTensor shard region; the mesh
_grad_normreduces over with thelayout of FSDP2's grad mesh;
_is_outer_shardedwith whether FSDP2 shards the parameterbeyond its first mesh dim; and that exactly the parameters typed
Ron tp declare tp astheir partial-grad group. All match at every rank of Llama 3 debug at
dp_shard=2, tp=2with and without sequence parallelism and at
cp=2, tp=2, and of Qwen3 MoE debug atdp_shard=2, tp=2, ep=2; at ranks 0 and 3 of Qwen3 MoE atdp_shard=2, tp=2, ep=2without sequence parallelism, at
dp_shard=2, cp=2and atdp_shard=2, cp=2, ep=2; andat ranks 0, 3, 5 and 6 of 8 for Llama 3 at
dp_shard=2, cp=2, tp=2and Qwen3 MoE atdp_shard=2, cp=2, tp=2, ep=4.FSDP2 path. FSDP2's code doesn't change, except
fused_qkv_param_init's branch forplain tensors, which FSDP2's DTensor parameters don't take.
scripts/loss_compare.py --assert-equal --metrics loss,grad_norm(seed 42, deterministic, 50 steps, 2 GB200GPUs, flex attention because the environment has no FA4) reports equal loss and grad
norm at every step between FSDP2 runs at the Hugging Face load PR and at this PR, with
no seed checkpoint since both start from seed 42 with the same parallelism (step-50
loss and grad norm):
tp=2with sequence parallelism, which runsfused_qkv_param_initon TP-sharded DTensors: 2.94190 and 0.4018.
cp=2: 2.94029 and 0.4154.tp=2, ep=2: 3.73420 and 2.2851.FlexShard against FSDP2 through the trainer. The same
loss_compareat this PR,FSDP2 against FlexShard (accelerator graphs off, which FlexShard rejects) from a shared
seed checkpoint, also reports equal loss and grad norm at every step: Llama 3 debug at
tp=2with sequence parallelism, 2.94099 and 0.4634; atcp=2, 2.94103 and 0.4633;Qwen3 MoE debug at
tp=2, ep=2, 3.74659 and 2.2714. Forcp=2, the seed checkpointcomes from the config without CP: the seed run sets cp to 1 but keeps the CP attention,
which validation rejects.
Co-authored-by: Wei Feng [email protected]