Repository navigation
Conversation
|
@claude review this pr - review for correctness and make sure that fsdp2 behavior is untouched |
|
Claude finished @anshul-si's task in 5m 11s —— View job Approve (please fill in the empty human-written summary before merging); FSDP2 sets exactly the same prefetch targets as before. See the review. |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The FSDP2 path sets exactly the prefetch targets it set before. The FlexShard EP path matches FSDP2's two-group layout, and the config check bans the one case that would silently corrupt training (output_postprocess). A maintainer still needs to review this, because it touches core (fsdp.py, decoder.py, config/validation.py).
What this PR does. It lets fsdp_backend=FlexShardConfig() run with expert_parallel_degree > 1 for decoders that use Decoder._apply_fsdp. Each MoE block gets two buckets: a dense bucket on dp_shard and an expert bucket on edp_shard. The PR copies FSDP2's explicit EP prefetch schedule, and as_fsdp2_dtensor now presents routed-expert shards on (edp_shard, ep) the way FSDP2 lays them out. The FSDP2 prefetch code is rewritten as a loop over the new decoder_ep_prefetch_order.
Example. qwen3_moe_debug with dp_shard=4, ep=2:
before: FlexShardConfig() + ep=2 -> ValueError (validate_flex_shard_training)
after: layers.<i> dense bucket on dp_shard (4), routed_experts bucket on edp_shard (2);
init / grads / clipped grad_norm / AdamW params bitwise == FSDP2
(test_matches_fsdp2_with_expert_parallelism)
Must fix
- PR description: the "Summary (human-written)" section is empty. The author has to write it (per
CONTRIBUTING.md, agents don't fill it in).
Details: FSDP2 is unchanged
I compared the old and new apply_fsdp_to_decoder code (torchtitan/distributed/fsdp.py:620-627) case by case, using order = [tok_embeddings?] + layers + [lm_head if norm and lm_head]:
| case | old | new |
|---|---|---|
tok_embeddings fwd |
[block0] if layers non-empty |
same (order[0] -> order[1]) |
| block i fwd | [block i+1] |
same |
| last block fwd | [norm, lm_head] if both exist |
[lm_head], see below |
lm_head bwd |
[last block] if both exist and layers non-empty |
same |
| block i bwd | [block i-1], block0 -> [tok_embeddings] if present |
same |
tok_embeddings bwd / lm_head fwd |
not set | not set |
| no layers | nothing set | [], nothing set |
[norm, lm_head]->[lm_head].decoder_fsdp_groupsalways putsnormandlm_headin the samefully_shardcall: the head group when weights are untied, the embedding group when tied. If either module is missing, no head group exists and neither version adds a prefetch. Both entries therefore resolve to the sameFSDPState, and the secondunshard()returns early because an all-gather is already in flight (_all_gather_result is not None). No collective changes.- Tied weights.
tok_embeddings,normandlm_headshare one state. The new code callsset_modules_to_forward_prefetchandset_modules_to_backward_prefetchon the same modules as before, so the shared state ends up with the same lists. - MTP decoders. The order is still read from
model.layersinsideapply_fsdp_to_decoder, after MTP layers are appended, as before. Decoder._apply_fsdp. Hoistingresolve_sparse_fsdp_meshabove the branch changes nothing for FSDP2. It returns(None, None)when EP is off, so the FlexShard path withep=1is also safe.
FlexShard EP path checks.
- Bucket order and storage pairing:
zip(groups, group_buckets)consumes the storages in bucket order, and the root bucket comes last and is never consumed. - Prefetch wiring:
current[0]forward-prefetches both of the next block's buckets.following[0]backward-prefetchescurrent[::-1](experts first). Expert buckets are set to[]. - Routed-expert parameters: the only ones are
w13andw2(weights and biases). NoBinaryActivationFnhas parameters, so the only parameters that areReplicateonepcome fromoutput_postprocess, which the new check bans. - Exact-type check: nothing in
torchtitan/modelssubclassesRoutedExperts.Config, sotype(...) is not RoutedExperts.Configrejects only Dist-MoE and similar, and GPT-OSS and Qwen3 pass. - Checkpointing is still rejected by
validate_flex_shard_training, so the undeclared EP layout can't reach DCP in this PR.
Not verified:
- FlexShard internals (the package isn't importable in this runner). That covers whether
sharded_bucket_storageskeepsbucketsorder, whether the dense bucket's parameter-FQN patterns hook the block, and the explicit-prefetch override semantics. A wrong guess here would only change overlap, not values. The PR's prefetch-dump script is the evidence for it. - GPU numerics. I relied on the PR's loss_compare and unit-test results.
|
@claude review the pr's newest changes |
|
Claude finished @anshul-si's task in 4m 27s —— View job Approve -- please address the items before merging. The PR description no longer matches the rewritten code, the 4-rank evidence needs re-running on HEAD, and the grad-norm-mesh workaround needs a TODO. FSDP2 behavior is unchanged. See the review. |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The FSDP2 path is unchanged from the last review, and I found no correctness bug in the rewritten FlexShard EP path. But the PR description now describes the previous implementation, and the 4-rank evidence predates the rewrite. A maintainer still needs to review, because this touches core (distributed/fsdp.py, distributed/utils.py).
What changed since the last review (13d0e82 -> 1aad874, rebased on new main). as_fsdp2_dtensor is gone. Instead:
- each routed-expert parameter declares its EP split to FlexShard with
set_global_layout, soinit_paraminitializes all experts as one device would; record_grad_norm_meshmaps the expert bucket'sedp_shardmesh to the flattened(edp_shard, ep)loss mesh, soclip_grad_norm_reduces expert grads where FSDP2's DTensor grads do;- the EP checks (dispatcher, Dist-MoE,
output_postprocess) moved fromconfig/validation.pyintovalidate_flex_shard_training; decoder.pyandparallelism.pyare no longer touched.
Example. qwen3 debugmodel_moe, dp_shard=4, ep=2:
init: w13 local = full_init(all 8 experts)[ep_rank half].chunk(2)[edp_rank] # set_global_layout
grad norm: FSDP2 -> DTensor on (edp_shard, ep) -> one all-reduce on loss_mesh
FlexShard -> plain shard on edp_shard -> _GRAD_NORM_MESHES -> loss_mesh # same ranks, same order
Must fix
- PR description: it no longer matches the code. It describes
as_fsdp2_dtensor, a publicdecoder_ep_prefetch_order, edits todecoder.py/config/validation.py/parallelism.py, and a newtest_flex_shard_rejects_unsupported_modelscase, and none of these are in the diff. "Known issues -> EP layout in FlexShard" says the layout isn't declared, but this PR now declares it. The Numerics and Testing rows withfsdp_defer_gradient_reduction=Truecan't run anymore: the base rejects that flag (flex_shard_fsdp.py:188). The 4-GPU (edp_shard=2) runs were made on code that this rewrite replaced. Please re-runtest_matches_fsdp2_with_expert_parallelismat 4 ranks on HEAD (CI's multi-GPU job may cover it) and update the description. torchtitan/distributed/flex_shard_fsdp.py:65--_GRAD_NORM_MESHESand_flatten("loss_mesh")need a TODO with an upstream link (inline).
Should consider
torchtitan/distributed/flex_shard_fsdp.py:101-- init now materializes every expert on every rank, so init memory grows withnum_experts, notnum_experts / ep(inline).tests/unit_tests/gpu/distributed/test_flex_shard_fsdp.py:270-- the 1-microbatch EP case is redundant (inline).torchtitan/distributed/flex_shard_fsdp.py:230-- theoutput_postprocessban lost its CPU test (inline).
Details
FSDP2 unchanged. The prefetch rewrite in apply_fsdp_to_decoder (fsdp.py:832-835) is the same code I compared case by case last time. The only change is that the helper is now private (_decoder_prefetch_order). The only other FSDP2-side change is edp_mesh= passed to the FlexShard branch. clip_grad_norm_ still groups DTensor grads by device_mesh; flex_shard_grad_norm_mesh is consulted only for non-DTensor grads, and returns None when flex_shard isn't imported.
FlexShard EP path.
- Storage pairing: there is one storage per bucket (asserted).
zip(groups, group_buckets)consumes them in bucket order, and the root bucket is last and never consumed. - Prefetch: embedding -> block 0
[dense, expert]-> ... -> last block ->[head]. In backward, each step prefetches the previous group's buckets reversed (expert first), and expert buckets prefetch nothing. This matches FSDP2. - Grad norm: the dense groups come first in both backends, then the expert group, so
sum(norm**p)adds in the same order. - Validation: Qwen3 and GPT-OSS get
AllToAllTokenDispatcherfromrouted_experts_config/ their flavors, andTokenDispatcherTransformruns beforeTrainingEngine.__init__, so the exact-type check sees the final dispatcher.
Not verified: FlexShard internals (set_global_layout composing with non-dim-0 Shard, sharded_bucket_storages order, which module the param-FQN dense bucket hooks), and whether WeakKeyDictionary entries are actually freed, given that the value mesh may hold a reference back to the key through the root mesh. GPU numerics.
| # The mesh to reduce a grad norm over for the parameters of the FlexShard buckets | ||
| # on a mesh, when it isn't that mesh, for flex_shard_grad_norm_mesh. Keyed by the | ||
| # mesh the buckets hold, which keeps the entry alive as long as the model. | ||
| _GRAD_NORM_MESHES: weakref.WeakKeyDictionary[ | ||
| DeviceMesh, DeviceMesh | ||
| ] = weakref.WeakKeyDictionary() |
There was a problem hiding this comment.
_GRAD_NORM_MESHES works around a FlexShard gap. The parameter now declares its EP split (set_global_layout), but flex_shard.get_mesh still returns only the bucket's mesh. Getting the right mesh then takes a module-level map keyed by mesh value, plus edp_mesh._flatten("loss_mesh") (fsdp.py:517), a private DeviceMesh API that only works because ParallelismContext happened to flatten a mesh with that name. _PARAM_LAYOUTS right above has a TODO for the same kind of workaround. This one needs one as well, with an upstream issue link (CLAUDE.md principle 3), so it gets deleted once FlexShard can report it:
| # The mesh to reduce a grad norm over for the parameters of the FlexShard buckets | |
| # on a mesh, when it isn't that mesh, for flex_shard_grad_norm_mesh. Keyed by the | |
| # mesh the buckets hold, which keeps the entry alive as long as the model. | |
| _GRAD_NORM_MESHES: weakref.WeakKeyDictionary[ | |
| DeviceMesh, DeviceMesh | |
| ] = weakref.WeakKeyDictionary() | |
| # The mesh to reduce a grad norm over for the parameters of the FlexShard buckets | |
| # on a mesh, when it isn't that mesh, for flex_shard_grad_norm_mesh. Keyed by the | |
| # mesh the buckets hold, which keeps the entry alive as long as the model. | |
| # TODO(<flex_shard issue>): Read the reduction mesh from flex_shard instead, | |
| # once a parameter's declared outer layout carries the mesh it is split over. | |
| _GRAD_NORM_MESHES: weakref.WeakKeyDictionary[ | |
| DeviceMesh, DeviceMesh | |
| ] = weakref.WeakKeyDictionary() |
| one full parameter: under expert parallelism, a routed-expert parameter with | ||
| all experts. |
There was a problem hiding this comment.
Under EP, this transient full parameter is the routed-expert tensor for all experts, on every rank. So peak init memory now grows with num_experts rather than num_experts / ep. In fp32, w13 for one layer is E * 2 * F * D * 4 bytes: about 6.4 GB for Qwen3-235B (128 x 1536 x 4096). At Kimi-K2 scale (384 x 2048 x 7168) it is about 45 GB, which won't fit next to the model on an 80 GB GPU. FSDP2's DTensor init only materializes local shards.
This doesn't block the debug models, but large MoE models are exactly what EP is for. Please list it under "Known issues" (one-device init vs. init memory). Or say whether init_from_full could generate only this EP rank's experts, e.g. by drawing per expert, at the cost of matching one-device init only per expert slice.
| self._check_matches_fsdp2( | ||
| ep=2, | ||
| cases=product( | ||
| [(build_qwen3_config, "debugmodel_moe")], ["default"], (1, 2) | ||
| ), | ||
| ) |
There was a problem hiding this comment.
test_matches_fsdp2 just above says "Two microbatches cover one". The base now rejects fsdp_defer_gradient_reduction (flex_shard_fsdp.py:188), so the 1-microbatch case exercises no path that 2 microbatches skip. Each case builds two 4-rank models and trains 6 steps on the shared multi-GPU runner. Unless EP has a specific reason to need it, drop it, and the itertools.product import with it:
| self._check_matches_fsdp2( | |
| ep=2, | |
| cases=product( | |
| [(build_qwen3_config, "debugmodel_moe")], ["default"], (1, 2) | |
| ), | |
| ) | |
| self._check_matches_fsdp2( | |
| ep=2, | |
| cases=[((build_qwen3_config, "debugmodel_moe"), "default", 2)], | |
| ) |
| elif routed_experts.output_postprocess is not None: | ||
| feature = "routed-expert output_postprocess" |
There was a problem hiding this comment.
The output_postprocess ban is the one check here that prevents silent corruption: without it, each EP rank's copy of those parameters drifts. The previous revision tested it, and the description still says a case was added to test_flex_shard_rejects_unsupported_models. Neither is in this diff anymore. It's a CPU-only check, so it's cheap. Extend test_flex_shard_rejects_models_with_their_own_fsdp (tests/unit_tests/cpu/config/test_config_validation.py:229) with a Qwen3 MoE expert_parallel_degree=2 config that has output_postprocess set on one MoE, and pytest.raises(ValueError, match="routed-expert output_postprocess with expert parallelism").
[ghstack-poisoned]
|
@claude review the newest changes |
|
Claude finished @anshul-si's task in 3m 41s —— View job Approve, with two items to fix before merging: the PR description is out of date, and |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The new commits remove the module-level _GRAD_NORM_MESHES map and pass the reduce meshes to clip_grad_norm_ explicitly. I found no correctness bug, and FSDP2 behavior is unchanged. The PR description still describes an older implementation, though. A maintainer still needs to review, because this touches core (distributed/fsdp.py, distributed/utils.py, components/optim/optim.py).
What changed since the last review (1aad874 -> 7fbe0fa, rebased on a new base). The global map and record_grad_norm_mesh are gone. flex_shard_reduce_meshes(parallelism_context) now returns {edp_shard mesh: loss mesh} under EP. GradientClipper calls it on every step and passes it as the new clip_grad_norm_(..., flex_shard_reduce_meshes=...) argument. flex_shard_grad_norm reduces each bucket group over reduce_meshes.get(bucket_mesh, bucket_mesh). Everything else is a rebase onto the base's switch to init_from_full wrapping param_init and its split into _apply_fsdp2.
Example. qwen3 debugmodel_moe, dp_shard=2, ep=2 (edp_shard=1):
dense buckets (mesh dp_shard) -> not in the map -> all-reduce over dp_shard
expert buckets (mesh edp_shard) -> map hit -> all-reduce over loss mesh (edp_shard x ep)
FSDP2: DTensor grads on (edp_shard, ep) -> same loss-mesh all-reduce
FSDP2 path: flex_shard_enabled=False -> flex_shard_reduce_meshes=None -> unchanged
Must fix
- PR description (still open): it still describes
as_fsdp2_dtensor, a publicdecoder_ep_prefetch_order, and edits todecoder.py,config/validation.pyandparallelism.py. It also describes a newtest_flex_shard_rejects_unsupported_modelscase and Numerics/Testing rows withfsdp_defer_gradient_reduction=True. None of these are in the diff, and the base rejects that flag (flex_shard_fsdp.py:159). "Known issues -> Expert-mesh lookup / EP layout in FlexShard" no longer matches the code, and the description doesn't mention the newclip_grad_norm_argument. The 4-GPU (edp_shard=2) evidence comes from code this PR has since replaced. Please re-runtest_matches_fsdp2_with_expert_parallelismat 4 ranks on HEAD and update the description. torchtitan/distributed/flex_shard_fsdp.py:68-77-- this still calls the private_flatten, has no TODO, and re-slices the mesh on every step. Usingparallelism_context.get_mesh("edp_shard")andget_mesh("loss")fixes all three (inline).
Should consider (still open from the last review, not re-commented)
- The
output_postprocess+ EP ban invalidate_flex_shard_trainingstill has no CPU test. It is the one check that prevents silent drift. test_matches_fsdp2_with_expert_parallelismstill runs the 1-microbatch case, which the 2-microbatch case covers.- Initializing routed experts holds every expert on every rank. The code comment now says so (
fsdp.py:517-520), but "Known issues" doesn't.
Details
FSDP2 unchanged. GradientClipper passes flex_shard_reduce_meshes=None when flex_shard_enabled is False, and clip_grad_norm_ reads it only inside the flex_shard_enabled and mesh is not None branch. In fsdp.py, the PR's only FSDP2-side change is the prefetch loop I compared case by case in the first review, which moved into the base's _apply_fsdp2. The other change, edp_mesh= on the FlexShard call, runs only on the FlexShard path. The test_optim.py change is needed: a MagicMock context has a truthy flex_shard_enabled, which would call flex_shard_reduce_meshes.
Map lookup. The key (edp_mesh["edp_shard"] in flex_shard_reduce_meshes) and the bucket mesh (edp_mesh["edp_shard"] in _apply_flex_shard) are separate slices, so the lookup relies on DeviceMesh value equality. A miss would fall back to edp_shard without any error, giving a wrong grad norm. The EP GPU test would catch that: at 2 ranks edp_shard has size 1, so a miss would leave out the other EP rank's experts. The suggested get_mesh("edp_shard") key is also a slice of full_sparse_mesh, so it relies on the same equality.
Not verified: GPU numerics, and that DeviceMesh.__eq__ compares by value in the pinned torch. ParallelismContext's comment at parallelism_context.py:115 says equality is by identity, which would make the lookup miss every time. The author's reported EP test passes suggest the comment is out of date.
| from torchtitan.distributed.fsdp import resolve_sparse_fsdp_mesh | ||
|
|
||
| edp_mesh, _ = resolve_sparse_fsdp_mesh(parallelism_context) | ||
| if edp_mesh is None: | ||
| return {} | ||
| # FSDP2's DTensor grad norm reduces routed-expert grads over edp_shard and | ||
| # ep in one all-reduce, on torchtitan's loss mesh, which spans the same | ||
| # ranks and which DTensor finds by layout. _flatten returns that mesh, and | ||
| # raises if its layout differs. | ||
| return {edp_mesh["edp_shard"]: edp_mesh._flatten("loss_mesh")} |
There was a problem hiding this comment.
This still calls the private DeviceMesh._flatten API, and it has no TODO (left over from the last review's must-fix 2). It also runs on every optimizer step: GradientClipper.clip_grad_norm_ calls it, so each step slices a new edp_shard submesh and repeats the _flatten lookup. ParallelismContext already caches both meshes, and they are public. get_mesh("loss") returns the same object that _flatten("loss_mesh") gives back here, because build_mesh created it under that name (parallelism_context.py:338). edp_shard exists whenever ep > 1, even with size 1 (parallelism_context.py:432-434). With the public accessors the private call and the fsdp import both go away:
| from torchtitan.distributed.fsdp import resolve_sparse_fsdp_mesh | |
| edp_mesh, _ = resolve_sparse_fsdp_mesh(parallelism_context) | |
| if edp_mesh is None: | |
| return {} | |
| # FSDP2's DTensor grad norm reduces routed-expert grads over edp_shard and | |
| # ep in one all-reduce, on torchtitan's loss mesh, which spans the same | |
| # ranks and which DTensor finds by layout. _flatten returns that mesh, and | |
| # raises if its layout differs. | |
| return {edp_mesh["edp_shard"]: edp_mesh._flatten("loss_mesh")} | |
| if not parallelism_context.ep_enabled: | |
| return {} | |
| # FSDP2's DTensor grad norm reduces routed-expert grads over edp_shard and | |
| # ep in one all-reduce, on torchtitan's loss mesh. validate_flex_shard_training | |
| # allows only dp_shard and ep, so the loss mesh spans the same ranks. | |
| return { | |
| parallelism_context.get_mesh("edp_shard"): parallelism_context.get_mesh("loss") | |
| } |
The _flatten call also guarded against a mismatched layout, and this version drops that guard. It matters only once CP, TP or dp_replicate are allowed with FlexShard, and validation rejects all three today. If you'd rather keep _flatten, add a TODO that says it is a private upstream API (CLAUDE.md principle 3).
[ghstack-poisoned]
Stack from ghstack (oldest at bottom):
Stacked on #5842.
Summary (human-written)
Each MoE block gets two FlexShard buckets - one for dense parameters sharded across al dp_shard ranks, and one for its routed experts across the edp_shard ranks. Tested bitwise numerics with FSDP2 on Qwen3 MoE and GPT-OSS debug models.
Description
#5842 adds
parallelism.storage=FlexShardConfig()for data parallelismover
dp_shardonly, andFlexShardConfig.validate_modelrejectsexpert_parallel_degree > 1. Large MoE models train with expert parallelism, so none ofthem can use FlexShard yet. This PR lets FlexShard shard MoE decoders under EP, with
training bitwise identical to FSDP2. As in #5842, nothing on the FlexShard path creates
a DTensor. The earlier revision of this PR viewed routed experts as DTensors through
as_fsdp2_dtensor, which #5842 has since deleted.Under EP,
decoder_sharding_unitsalready gives each MoE block's routed experts theirplacements over the
edp_shard * epexpert shards, and FSDP2'sfully_shard(block)makes two parameter groups: the routed experts on the sparse mesh's
edp_shardaxis,and the rest of the block on
dp_shard.FlexShardConfig.apply_to_decodernow passesthe sparse mesh to
FlexShardConfig.apply_to_decoder, which gives each MoE block abucket for each group, with the same parameters and placements: one on
dp_shardthathooks the block, and one on
edp_shardthat hookslayers.<i>.feed_forward.routed_experts. Both arefsdp2_compatible, so theirall-gathers and reduce-scatters match FSDP2's byte for byte. Because the expert bucket
hooks the routed experts, FlexShard reshards them as soon as the routed experts finish
forward or backward, while FSDP2 keeps them gathered until the whole block finishes.
Peak memory and timing differ; values don't.
FSDP2 prefetches explicitly under EP, because EP's device-to-host syncs keep the CPU
from issuing the next all-gathers early. FlexShard's default prefetches the next bucket
in forward order. A block's expert bucket, whose hook runs before the routed experts
reach the sync, would gather the next block's dense bucket, but the next block's expert
bucket would start gathering only at that block's start, after the sync. FlexShard now
gets FSDP2's schedule through its explicit prefetch (
set_buckets_to_forward_prefetch/set_buckets_to_backward_prefetch): a block's first bucket prefetches both of the nextblock's buckets in forward, and in backward a block's buckets are prefetched experts
first, the order FSDP2 uses for a module's groups. Expert buckets prefetch nothing
themselves. Both backends read the order from a new
decoder_prefetch_orderinfsdp.py(embedding, each block, output projection; public, likedecoder_sharding_units, sinceFlexShardConfigis in another module), so FSDP2's36-line prefetch block, which
fsdp_unshard_in_current_streamalso uses, becomes a4-line loop. One FSDP2 list changes without effect: the last block's forward list was
[norm, lm_head]. Both modules are in one FSDP group, so the second entry named thesame group again and its unshard returned early. The list is now
[lm_head]. DumpingFSDP2's prefetch lists on the Qwen3 MoE debug model with
dp_shard=4, ep=2(on meta,with a fake process group) gives the same targets before and after, except that this
list loses its duplicate. FlexShard's lists gather the same parameters as FSDP2's 18
non-empty lists, and its 8 expert buckets prefetch nothing.
Before sharding, each EP rank holds a plain tensor with only its experts, which
FlexShard then shards over
edp_shard. Two places needed to see past that split:flex_shard(),FlexShardConfig.apply_to_decoderdeclares each routed-expert parameter's EP split, this rank's block of dim 0, as its
outer layout (
flex_shard.set_global_layout, which sets DCP'sCheckpointableTensorfields). flex_shard composes it with its own sharding in
get_flex_shard_global_layouts, whose layouts the wrappedparam_initfunctions use.Each therefore initializes a tensor with all experts and keeps this rank's (
ep,edp_shard) part, so each shard is its slice of one device's initialization, as fordense parameters. Without the declaration, each EP rank would initialize its experts
as if they were all of them, and every later draw would be out of step with one
device's. A one-off check builds both backends on meta for every rank of a fake
process group and compares each FlexShard layout with FSDP2's DTensor shard region:
they match for every parameter and rank at
dp_shard=4, ep=2, and at sampled ranks ofdp_shard=8, ep=4anddp_shard=128withep=2and 8, where the experts shard theirrows on
edp_shard(edp_shard * ep > num_experts). The cost: initializing arouted-expert parameter briefly holds all its experts on every rank, in the
parameter's dtype, while FSDP2's DTensor init draws only the local shard. For a
DeepSeek-V3-sized
w13(256 experts, 2 x 2048 x 7168 each, fp32) that is 30 GB.(edp_shard, ep).Probing
get_total_norm(...).full_tensor()shows that DTensor merges the two axes'reductions into one all-reduce on a flattened mesh of the same ranks (torchtitan's
loss mesh, which DTensor finds by layout): each grad's local norm, raised to the p-th
power, all-reduced once over all
edp_shard * epranks, then the root and the norm ofnorms. Reducing over
edp_shardand thenep, each with its own power and root,differed from DTensor in 1 of 8 trials at 4 ranks (CPU, gloo,
edp_shard=2, ep=2).The single reduction matched in 8 of 8, at 4 ranks on CPU and at 2 ranks on GPU.
FlexShard knows only each bucket's mesh,
edp_shardfor the expert buckets, sotorchtitan supplies the mesh to reduce over: the new
FlexShardConfig._reduce_meshes(parallelism_context)maps the expert buckets' mesh totorchtitan's loss mesh (
edp_mesh._flatten("loss_mesh")returns it, and raises if itslayout differs). It resolves the sparse mesh as
FlexShardConfig.apply_to_decoderdoes, so its key equals the buckets' mesh.
FlexShardConfig.clip_grad_norm_, whichreceives the
ParallelismContext, givesFlexShardConfig._grad_normthe mapped mesh,or the bucket's own if it isn't in the map.
GradientClipperandFullyShardConfig.clip_grad_norm_don't change._grad_normreduces in Add parallelism.storage to shard decoders with FlexShard #5842'sorder, on the process group FSDP2's DTensor norm reduces on, so no process group is
added. Nothing is recorded when the model is built, so no module-level state outlives
a model.
FlexShardConfig.validate_modelno longer rejectsexpert_parallel_degree > 1. UnderEP, it accepts only the configuration checked against FSDP2,
RoutedExpertswithAllToAllTokenDispatcherand nooutput_postprocess, read from the model config. Itrejects:
None has been run with FlexShard.
output_postprocess. Its parameters areReplicateonep(
models/common/moe/SHARDING.md), but the expert bucket treats every routed-expertparameter as split over
ep, so their grads would never be summed overep, andeach EP rank's copy would drift silently.
DeepSeek V3 and V4 are still rejected, since they override
_apply_fsdp.The parity test's body moves into
_check_matches_fsdp2(ep, cases)with no otherchange, and the new
test_matches_fsdp2_with_expert_parallelismruns the Qwen3 MoEdebug model with
ep=2, with one and with two microbatches. In CI it runs on 4 GPUs(
dp_shard=4, soedp_shard=2)._assert_initialized_as_one_devicenow expects eachrouted-expert shard to be its
edp_shardchunk of its EP rank's experts. The EP caseis a separate method because a second
ParallelismContextwith a differentepcan't build its meshes in the same process. Both methods pass on 2 GB200 GPUs with
world_sizeset to 2 (edp_shardthen has size 1). The test fails without the EPouter layout (at initialization, on
layers.0.feed_forward.routed_experts.w13.weight)and without the grad-norm mesh (at step 0's grad norm). It hasn't run at 4 GPUs: this
machine has 2, and FlexShard needs CUDA. At 2 ranks the two grad-norm reduction orders
agree, so the 4-rank evidence for initialization and the grad norm is the two probes
above.
The FSDP2 path matches #5842 bit for bit.
scripts/loss_compare.py 7322fb333 <this PR> --assert-equal --metrics loss,grad_norm(seed 42, deterministic, 50 steps, 2 GB200GPUs) reports equal loss and grad norm at every step for qwen3
moe_debugwithexpert_parallel_degree=2(step-50 loss 3.71933), which runs the refactoredprefetch code. It 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.
Co-authored-by: Wei Feng [email protected]