Skip to content

Support expert parallelism with parallelism.storage=FlexShardConfig() - #6010

Open
anshul-si wants to merge 7 commits into
gh/anshul-si/21/basefrom
gh/anshul-si/21/head
Open

anshul-si wants to merge 7 commits into
gh/anshul-si/21/basefrom
gh/anshul-si/21/head

Conversation

@anshul-si

@anshul-si anshul-si commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

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 parallelism
over dp_shard only, and FlexShardConfig.validate_model rejects
expert_parallel_degree > 1. Large MoE models train with expert parallelism, so none of
them 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_units already gives each MoE block's routed experts their
placements over the edp_shard * ep expert shards, and FSDP2's fully_shard(block)
makes two parameter groups: the routed experts on the sparse mesh's edp_shard axis,
and the rest of the block on dp_shard. FlexShardConfig.apply_to_decoder now passes
the sparse mesh to FlexShardConfig.apply_to_decoder, which gives each MoE block a
bucket for each group, with the same parameters and placements: one on dp_shard that
hooks the block, and one on edp_shard that hooks
layers.<i>.feed_forward.routed_experts. Both are fsdp2_compatible, so their
all-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 next
block'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_order in
fsdp.py (embedding, each block, output projection; public, like
decoder_sharding_units, since FlexShardConfig is in another module), so FSDP2's
36-line prefetch block, which fsdp_unshard_in_current_stream also uses, becomes a
4-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 the
same group again and its unshard returned early. The list is now [lm_head]. Dumping
FSDP2'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:

  • Initialization. Before calling flex_shard(), FlexShardConfig.apply_to_decoder
    declares 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's CheckpointableTensor
    fields). flex_shard composes it with its own sharding in
    get_flex_shard_global_layouts, whose layouts the wrapped param_init functions 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 for
    dense 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 of
    dp_shard=8, ep=4 and dp_shard=128 with ep=2 and 8, where the experts shard their
    rows on edp_shard (edp_shard * ep > num_experts). The cost: initializing a
    routed-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.
  • Grad-norm clipping. FSDP2's routed-expert grads are DTensors on (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 * ep ranks, then the root and the norm of
    norms. Reducing over edp_shard and then ep, 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_shard for the expert buckets, so
    torchtitan supplies the mesh to reduce over: the new
    FlexShardConfig._reduce_meshes(parallelism_context) maps the expert buckets' mesh to
    torchtitan's loss mesh (edp_mesh._flatten("loss_mesh") returns it, and raises if its
    layout differs). It resolves the sparse mesh as FlexShardConfig.apply_to_decoder
    does, so its key equals the buckets' mesh. FlexShardConfig.clip_grad_norm_, which
    receives the ParallelismContext, gives FlexShardConfig._grad_norm the mapped mesh,
    or the bucket's own if it isn't in the map. GradientClipper and
    FullyShardConfig.clip_grad_norm_ don't change. _grad_norm reduces in Add parallelism.storage to shard decoders with FlexShard #5842's
    order, 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_model no longer rejects expert_parallel_degree > 1. Under
EP, it accepts only the configuration checked against FSDP2, RoutedExperts with
AllToAllTokenDispatcher and no output_postprocess, read from the model config. It
rejects:

  • Dist-MoE routed experts, and the DeepEP, HybridEP and TorchAO token dispatchers.
    None has been run with FlexShard.
  • An output_postprocess. Its parameters are Replicate on ep
    (models/common/moe/SHARDING.md), but the expert bucket treats every routed-expert
    parameter as split over ep, so their grads would never be summed over ep, and
    each 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 other
change, and the new test_matches_fsdp2_with_expert_parallelism runs the Qwen3 MoE
debug model with ep=2, with one and with two microbatches. In CI it runs on 4 GPUs
(dp_shard=4, so edp_shard=2). _assert_initialized_as_one_device now expects each
routed-expert shard to be its edp_shard chunk of its EP rank's experts. The EP case
is a separate method because a second ParallelismContext with a different ep
can't build its meshes in the same process. Both methods pass on 2 GB200 GPUs with
world_size set to 2 (edp_shard then has size 1). The test fails without the EP
outer 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 GB200
GPUs) reports equal loss and grad norm at every step for qwen3 moe_debug with
expert_parallel_degree=2 (step-50 loss 3.71933), which runs the refactored
prefetch 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]

[ghstack-poisoned]
@anshul-si

Copy link
Copy Markdown
Contributor Author

@claude review this pr - review for correctness and make sure that fsdp2 behavior is untouched

@claude

claude Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

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.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. 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_groups always puts norm and lm_head in the same fully_shard call: 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 same FSDPState, and the second unshard() returns early because an all-gather is already in flight (_all_gather_result is not None). No collective changes.
  • Tied weights. tok_embeddings, norm and lm_head share one state. The new code calls set_modules_to_forward_prefetch and set_modules_to_backward_prefetch on the same modules as before, so the shared state ends up with the same lists.
  • MTP decoders. The order is still read from model.layers inside apply_fsdp_to_decoder, after MTP layers are appended, as before.
  • Decoder._apply_fsdp. Hoisting resolve_sparse_fsdp_mesh above the branch changes nothing for FSDP2. It returns (None, None) when EP is off, so the FlexShard path with ep=1 is 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-prefetches current[::-1] (experts first). Expert buckets are set to [].
  • Routed-expert parameters: the only ones are w13 and w2 (weights and biases). No BinaryActivationFn has parameters, so the only parameters that are Replicate on ep come from output_postprocess, which the new check bans.
  • Exact-type check: nothing in torchtitan/models subclasses RoutedExperts.Config, so type(...) is not RoutedExperts.Config rejects 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_storages keeps buckets order, 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.

@anshul-si
anshul-si marked this pull request as ready for review November 10, 2026 21:55
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 10, 2026
@github-actions
github-actions Bot requested a review from weifengpy November 10, 2026 21:55
[ghstack-poisoned]
@anshul-si

Copy link
Copy Markdown
Contributor Author

@claude review the pr's newest changes

@claude

claude Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

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.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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, so init_param initializes all experts as one device would;
  • record_grad_norm_mesh maps the expert bucket's edp_shard mesh to the flattened (edp_shard, ep) loss mesh, so clip_grad_norm_ reduces expert grads where FSDP2's DTensor grads do;
  • the EP checks (dispatcher, Dist-MoE, output_postprocess) moved from config/validation.py into validate_flex_shard_training;
  • decoder.py and parallelism.py are 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

  1. PR description: it no longer matches the code. It describes as_fsdp2_dtensor, a public decoder_ep_prefetch_order, edits to decoder.py / config/validation.py / parallelism.py, and a new test_flex_shard_rejects_unsupported_models case, 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 with fsdp_defer_gradient_reduction=True can'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-run test_matches_fsdp2_with_expert_parallelism at 4 ranks on HEAD (CI's multi-GPU job may cover it) and update the description.
  2. torchtitan/distributed/flex_shard_fsdp.py:65 -- _GRAD_NORM_MESHES and _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 with num_experts, not num_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 -- the output_postprocess ban 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 AllToAllTokenDispatcher from routed_experts_config / their flavors, and TokenDispatcherTransform runs before TrainingEngine.__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.

Comment on lines +65 to +70
# 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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Suggested change
# 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()

Comment on lines +101 to +102
one full parameter: under expert parallelism, a routed-expert parameter with
all experts.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +267 to +272
self._check_matches_fsdp2(
ep=2,
cases=product(
[(build_qwen3_config, "debugmodel_moe")], ["default"], (1, 2)
),
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
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)],
)

Comment on lines +230 to +231
elif routed_experts.output_postprocess is not None:
feature = "routed-expert output_postprocess"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]
[ghstack-poisoned]
@anshul-si

Copy link
Copy Markdown
Contributor Author

@claude review the newest changes

@claude

claude Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

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 flex_shard_reduce_meshes should use ParallelismContext's public meshes instead of the private _flatten. FSDP2 behavior is still unchanged. See the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. PR description (still open): it still describes as_fsdp2_dtensor, a public decoder_ep_prefetch_order, and edits to decoder.py, config/validation.py and parallelism.py. It also describes a new test_flex_shard_rejects_unsupported_models case and Numerics/Testing rows with fsdp_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 new clip_grad_norm_ argument. The 4-GPU (edp_shard=2) evidence comes from code this PR has since replaced. Please re-run test_matches_fsdp2_with_expert_parallelism at 4 ranks on HEAD and update the description.
  2. 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. Using parallelism_context.get_mesh("edp_shard") and get_mesh("loss") fixes all three (inline).

Should consider (still open from the last review, not re-commented)

  • The output_postprocess + EP ban in validate_flex_shard_training still has no CPU test. It is the one check that prevents silent drift.
  • test_matches_fsdp2_with_expert_parallelism still 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.

Comment on lines +68 to +77
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")}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
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]
[ghstack-poisoned]
@anshul-si anshul-si changed the title Support expert parallelism with parallelism.fsdp_backend=FlexShardConfig() Support expert parallelism with parallelism.fsdp_backend=FlexShardBackend.Config() Nov 25, 2026
[ghstack-poisoned]
@anshul-si anshul-si changed the title Support expert parallelism with parallelism.fsdp_backend=FlexShardBackend.Config() Support expert parallelism with parallelism.storage=FlexShardConfig() Nov 30, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant