Skip to content

[MoE] sibling token_dispatcher + grouped_experts for composable override - #3859

Merged
wwwjn merged 1 commit into
mainfrom
override-conflict
Jul 16, 2026
Merged

wwwjn merged 1 commit into
mainfrom
override-conflict

Conversation

@wwwjn

@wwwjn wwwjn commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Previously

fused_swiglu (grouped-experts variant) swapped the experts module and deepep_inference
swapped its token dispatcher. Since the dispatcher was a child of the experts module, the
two overrides were ancestor/descendant and the override engine rejected them (it's
order-dependent). The workaround was a combined inference_moe override.

Now

Split the routed experts so communication and computation are sibling submodules, with
the parent as the local_map region:

MoE
├── routed_experts # RoutedExperts — local_map region (dispatch -> GEMM ->
combine)
│ ├── token_dispatcher # <- deepep_inference
│ └── grouped_experts # grouped-GEMM weights <- fused_grouped_experts
└── shared_experts

Now the two overrides claim disjoint sibling nodes and compose out of the box,
order-independently — no engine change needed.

  • Removed the combined inference_moe; restored deepep_inference as a standalone
    dispatcher override.
  • fused_swiglu now registers both the dense-FFN (fused_swiglu) and routed-experts
    (fused_grouped_experts) fusion.
  • Expert FQNs move moe.experts.* → moe.routed_experts.grouped_experts.*; HF adapters
    updated (no native-DCP back-compat by design).

Validation

  • Bitwise-identical loss on deepseek_v3 and gpt_oss debug models (pure refactor).
  • fused_swiglu + deepep_inference compose with no conflict, order-independent (unit
    tests).
  • Unit tests + 8-GPU FSDP sharding test pass.

@wwwjn
wwwjn requested review from fegin, tianyu-l and wconstab as code owners July 2, 2026 21:59
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jul 2, 2026
@wwwjn wwwjn changed the title [WIP] Resolve fused swiglu override and MoE grouped experts override conflict Resolve fused swiglu override and MoE grouped experts override conflict Jul 6, 2026
Comment thread torchtitan/overrides/inference_moe.py Outdated
@override(
"inference_moe",
target=GroupedExperts.Config,
description="Inference experts: fused SwiGLU + cudagraph-able DeepEP expand dispatch.",

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.

I don't like this solution, because it couples different override together. E.g. the name of this override should be DeepEP_inference_and_fused_swiglu_moe.

A good design should compose them more or less independently.

Our current override design is module-oriented. The problem today is that

  • DeepEP inference swaps the grouped_experts.dispatcher
  • fused swiglu swaps the grouped_experts
  • Despite they should compose, the override engine would error out to be conservative. Like, if you remove the erroring out, these two overrides should just work together out-of-box, regardless of application order, right?

I can think of two alternative solutions:

  1. make another parent module moe.X (I don't have a good name for now), so that we have X.grouped_experts (for swiglu override) and X.dispatcher (for deepep override). We still need moe.X to enter & exit local map region.
  2. lift the constraint of two overrides could not target the nested modules. This needs some soundness detection -- e.g. maybe we should first apply parent override (grouped_experts) then apply child override (grouped_experts.dispatcher) so that if the child is gone we could safely error out.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

it couples different override together. E.g. the name of this override should be DeepEP_inference_and_fused_swiglu_moe

Yes my previous design is when overriding the same module, all the override should go into a compound class(combining all the override targeting the same class) and make the name indicative. Someone could make it's override class "DeepEP_inference", another on could make
"HybridEP_inference_and_trick1_and_trick2". Each experiment run would only contain one override. It's impossible to be "composable" given we don't allow double/nested override and the override needs to align with torchtitan module boundary. I choose to put "deepEP_inference_and_fused_swiglu_moe" in torchtitan as an example is because this runs faster in inference testing.

the override engine would error out to be conservative.

This part I agree, we should not allow nested override to be conservative.

make another parent module moe.X (I don't have a good name for now), so that we have X.grouped_experts (for swiglu override) and X.dispatcher (for deepep override). We still need moe.X to enter & exit local map region.

It solved problem, but I'm hesitate about this solution if we only introduce the less meaningful wrapper X because of override. But if introducing X is because our MoE module structure is not clear enough, I think it's fine .We can have X=routed_experts, so MoE has moe.shared_experts and moe.routed_experts.dispatcher, moe.routed_experts.grouped_experts(just grouped gemm), and using routed_experts as the local map entrance and exit, instead of putting dispatcher within the grouped_experts

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

class GroupedExperts

fqn: inner_experts

@tianyu-l

tianyu-l commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

@claude review my review above

@claude

claude Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 3m 17s —— View job


Review of @tianyu-l's review

I traced the override engine (torchtitan/config/override.py) to check the core technical claim. Short version: your design instinct is right, but the load-bearing technical claim ("remove the error-out and they compose regardless of order") is not correct as the engine is written today. That actually strengthens your case for keeping a guard, and it sharpens what alternative (2) really has to do.


1. The coupling critique is valid (and it's a regression)

Agreed that inference_moe couples two orthogonal concerns — gate/up fusion (a moe.experts swap) and the cudagraph-able EXPAND dispatch layout (a moe.experts.token_dispatcher swap) — into one node claim. Two concrete symptoms:

  • The name understates the behavior, as you note. DeepEP_inference_and_fused_swiglu_moe is closer to the truth.
  • It's a composability regression: this PR deletes torchtitan/distributed/deepep/inference_override.py, which registered deepep_inference as a standalone override targeting DeepEPTokenDispatcher.Config. After this PR you can no longer flip the DeepEP layout for inference without also fusing experts — the two are welded together. The only reason they were welded is to dodge the ancestor/descendant conflict in _check_node_conflicts.

So the pushback is well-founded.


2. "Regardless of application order, right?" — no, and here's why

The claim that simply removing the error-out (_check_node_conflicts case (b), override.py:296-306) makes the two overrides compose is incorrect, because of two engine mechanics that interact badly:

  1. Claims are collected against the original tree, before any mutation (_collect_claims, override.py:257-272). Each _Claim captures parent/attr/cfg as references into the pre-override tree.
  2. derive shallow-copies — the fused experts config shares the same token_dispatcher object by reference (the inference_moe docstring even says so: "build / derive preserve the dispatcher child by reference").

Now walk the two orders for fused_grouped_experts (claims moe.experts, call it A) + deepep_inference (claims moe.experts.token_dispatcher, call it B):

B then A (child first): works.

  • B: setattr(orig_experts, "token_dispatcher", flipped) -> orig_experts.token_dispatcher = D_flipped
  • A: derive(orig_experts, ...) reads the now-flipped dispatcher -> fused config carries D_flipped. Correct.

A then B (parent first): silently drops the flip.

  • A: fused = derive(orig_experts); fused.token_dispatcher is D_orig (shared ref). setattr(moe, "experts", fused). The tree now holds fused; orig_experts is detached.
  • B: its captured parent is orig_experts (the detached node). setattr(orig_experts, "token_dispatcher", D_flipped) mutates the detached object. fused.token_dispatcher is still D_orig. The EXPAND flip is lost, with no error.

So it's order-dependent, and the failing order fails silently — exactly the "conservative error-out" the engine is protecting against. Claims iterate in active order (registry/import order), so this isn't something a user controls predictably.


3. What this means for your two alternatives

Alt (2) — lift the nesting constraint. This is viable but it's more than "remove the check plus detect soundness." To be correct it must:

  • order application parent-before-child (apply moe.experts fusion first), and
  • re-resolve the child claim against the post-parent tree rather than the pre-collected parent/cfg references — i.e. after A runs, re-traverse to find token_dispatcher now living under fused, and swap it there. Because derive shares the dispatcher by reference, re-traversal lands on the same object under the new parent, so the child override still applies cleanly.
  • the "child gone -> error" detection you mention then falls out naturally: if the parent override replaced (not just carried) the dispatcher child, re-traversal finds a different/absent node and you error.

The key correction: your phrasing "first apply parent then child" is the right order, but it only works if the child is resolved live after the parent runs. With today's collect-everything-up-front-then-mutate design, parent-then-child is precisely the broken order above. So alt (2) is a real change to _collect_claims/apply_overrides (staged, ancestor-ordered, re-resolved application), not just deleting case (b).

Alt (1) — interpose a parent module with X.grouped_experts and X.dispatcher as siblings. This is the cleaner composition story: siblings never trip the ancestor rule, so no engine change is needed and the two overrides stay fully independent and order-free. Cost is a module-hierarchy refactor of GroupedExperts (splitting weights from the dispatcher, threading dispatch/combine through the new parent's forward and its local_map region) that must be applied across all MoE variants — llama4, qwen3, deepseek_v3, gpt_oss (per .claude/rules/models.md). Bigger blast radius, but it fixes the root cause structurally instead of teaching the engine to handle nested claims.


Recommendation

Your review is correct to reject the coupling. I'd lean alt (1) if the goal is a principled, engine-unchanged composition (siblings are the design the current per-node engine actually wants), and treat alt (2) as the option only if you want to keep the module tree as-is — in which case the implementation must be staged (ancestor-first) with live child re-resolution, not merely a removed check. Whichever you pick, the standalone deepep_inference dispatcher override that this PR deletes should come back rather than being absorbed into a combined node claim.

One more note for the author: if any interim version does allow both overrides on the same actor, the A-then-B silent-drop above means a missing-flip needs to fail loudly (assert the resulting dispatcher is cudagraphable on the inference path), not silently fall back to the compact layout.
· branch override-conflict

from . import model_registry


def enable_fused_swiglu(config: Trainer.Config) -> None:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

need to update the name here

Comment thread torchtitan/overrides/inference_moe.py Outdated
@override(
"inference_moe",
target=GroupedExperts.Config,
description="Inference experts: fused SwiGLU + cudagraph-able DeepEP expand dispatch.",

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

it couples different override together. E.g. the name of this override should be DeepEP_inference_and_fused_swiglu_moe

Yes my previous design is when overriding the same module, all the override should go into a compound class(combining all the override targeting the same class) and make the name indicative. Someone could make it's override class "DeepEP_inference", another on could make
"HybridEP_inference_and_trick1_and_trick2". Each experiment run would only contain one override. It's impossible to be "composable" given we don't allow double/nested override and the override needs to align with torchtitan module boundary. I choose to put "deepEP_inference_and_fused_swiglu_moe" in torchtitan as an example is because this runs faster in inference testing.

the override engine would error out to be conservative.

This part I agree, we should not allow nested override to be conservative.

make another parent module moe.X (I don't have a good name for now), so that we have X.grouped_experts (for swiglu override) and X.dispatcher (for deepep override). We still need moe.X to enter & exit local map region.

It solved problem, but I'm hesitate about this solution if we only introduce the less meaningful wrapper X because of override. But if introducing X is because our MoE module structure is not clear enough, I think it's fine .We can have X=routed_experts, so MoE has moe.shared_experts and moe.routed_experts.dispatcher, moe.routed_experts.grouped_experts(just grouped gemm), and using routed_experts as the local map entrance and exit, instead of putting dispatcher within the grouped_experts

@wwwjn wwwjn changed the title Resolve fused swiglu override and MoE grouped experts override conflict Resolve fused swiglu override and MoE grouped experts override conflict by better MoE structure Jul 9, 2026
Comment thread torchtitan/models/common/moe.py Resolved
wwwjn added a commit that referenced this pull request Jul 9, 2026
Address review (tianyu-l on #3859): the config field / module attribute (and thus
the FQN moe.routed_experts.grouped_experts) is renamed to inner_experts, while the
class name stays GroupedExperts and the fused_grouped_experts override (which
targets GroupedExperts.Config, not the field) is unchanged. State-dict adapters,
sharding, quantization, graph_trainer, RL configs, tests and docs updated to the
new FQN. Pure rename (word-boundary; class/override names preserved).
wwwjn added a commit that referenced this pull request Jul 9, 2026
Address review (tianyu-l on #3859): the config field / module attribute (and thus
the FQN moe.routed_experts.grouped_experts) is renamed to inner_experts, while the
class name stays GroupedExperts and the fused_grouped_experts override (which
targets GroupedExperts.Config, not the field) is unchanged. State-dict adapters,
sharding, quantization, graph_trainer, RL configs, tests and docs updated to the
new FQN. Pure rename (word-boundary; class/override names preserved).
@wwwjn
wwwjn force-pushed the override-conflict branch from caa9d84 to 3265c27 Compare July 9, 2026 16:04
@wwwjn wwwjn changed the title Resolve fused swiglu override and MoE grouped experts override conflict by better MoE structure [MoE] sibling token_dispatcher + grouped_experts for composable override Jul 9, 2026
@wwwjn
wwwjn requested a review from tianyu-l July 9, 2026 22:32

@tianyu-l tianyu-l 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.

I'm positive about this change, but given the scope I'd like to have @sanketpurandare give feedback as well.

Comment thread torchtitan/overrides/fused_swiglu.py Resolved
b2_RD = ScaleBiasForward.apply(b2_RD, tp_degree, h_RD.dtype)
return h_RD + b2_RD

def forward(

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.

are these code gone because now we share the dispatcher logic in routed experts?

@wwwjn wwwjn Jul 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Those functions go away because dispatch/combine now live once in the shared RoutedExperts.forward() and RoutedExperts.paralell()

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 file MOE_SHARDING.md is not present in this PR, it should also be updated since it still mentions GroupedExperts for the LocalMapConfig

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Updated MOE_SHARDING.md, thank you

@wwwjn

wwwjn commented Jul 14, 2026

Copy link
Copy Markdown
Contributor Author

The CI timeout (8 GPU Model tests) are not related to this change

…_experts}

Separate the routed experts' communication (token dispatch/combine) from the
grouped-GEMM computation into sibling submodules under moe.routed_experts
(RoutedExperts, the local_map region):

  routed_experts (RoutedExperts)
    - token_dispatcher   token dispatch/combine
    - grouped_experts    (GroupedExperts) grouped-GEMM expert weights

This makes the fused-experts override (fused_grouped_experts -> grouped_experts)
and the DeepEP inference override (deepep_inference -> token_dispatcher) claim
disjoint sibling nodes, so they compose without the ancestor/descendant conflict
that previously forced the combined inference_moe override. inference_moe is
removed; deepep_inference is a standalone dispatcher override; fused_swiglu
registers both the dense-FFN and routed-experts fusion.

Expert FQNs move moe.experts.* -> moe.routed_experts.grouped_experts.*; per-model
HF state-dict adapters updated. Pure structural refactor (bitwise-identical loss
on deepseek_v3 and gpt_oss).
@wwwjn
wwwjn force-pushed the override-conflict branch from b13fa58 to 5e8655a Compare July 16, 2026 02:55
Comment thread torchtitan/models/common/moe.py Outdated
class Config(Module.Config):
num_experts: int
inner_experts: InnerExperts.Config
dispatcher: LocalTokenDispatcher.Config

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Need to token_dispatcher

Comment thread torchtitan/models/common/moe.py Outdated

@dataclass(kw_only=True, slots=True)
class Config(Module.Config):
num_experts: int

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is not needed

Comment thread torchtitan/overrides/inference_moe.py Outdated
@override(
"inference_moe",
target=GroupedExperts.Config,
description="Inference experts: fused SwiGLU + cudagraph-able DeepEP expand dispatch.",

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

class GroupedExperts

fqn: inner_experts

Comment thread torchtitan/overrides/fused_swiglu.py Resolved
b2_RD = ScaleBiasForward.apply(b2_RD, tp_degree, h_RD.dtype)
return h_RD + b2_RD

def forward(

@wwwjn wwwjn Jul 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Those functions go away because dispatch/combine now live once in the shared RoutedExperts.forward() and RoutedExperts.paralell()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Updated MOE_SHARDING.md, thank you

@wwwjn

wwwjn commented Jul 16, 2026

Copy link
Copy Markdown
Contributor Author
  • GraphTrainer CI failed with the same issue on main
  • RL integration test failure is unrelated, @liangel-02 is helping to check the varlen issue
  • 8GPU Model Test(CUDA, ROCM) timeout at flux test
  • 8GPU Feature test failure on main with same issue, not related

@wwwjn
wwwjn merged commit 3101b42 into main Jul 16, 2026
20 of 25 checks passed
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jul 17, 2026
…3859)

70th sync: upstream pytorch#3859 split routed experts into sibling submodules --
MoE.routed_experts (RoutedExperts, the local_map region) now composes
inner_experts (GroupedExperts weights) + token_dispatcher, instead of the
old flat MoE.experts=GroupedExperts(owns dispatcher). GroupedExperts._experts_forward
was renamed to forward and token_dispatcher removed from its Config. Our
ezpz/moe mirrored the old pattern -> moe_debugmodel crashed
(EzpzGroupedExperts.Config got unexpected kwarg token_dispatcher; caught by
sync_smoke job 12470895, rc=143).

Replay across the ezpz/moe tree:
- experts.py: _experts_forward -> forward (override + super() call + comment)
- __init__.py: make_ezpz_experts_config now returns RoutedExperts.Config
  (inner_experts + token_dispatcher siblings); make_ezpz_moe_config +
  caller use routed_experts=; EP=1 dispatcher-rebuild block walks
  routed_experts.{inner_experts,token_dispatcher}
- model.py: config-mutation walks routed_experts.inner_experts.compute_backend
  + routed_experts.token_dispatcher
- parallelize.py: runtime access moe.routed_experts.inner_experts.parameters()
- state_dict_adapter.py: expert weight FQNs moe.experts.wN ->
  moe.routed_experts.inner_experts.wN (HF-side mlp.experts unchanged)

Config-build verified: moe_debugmodel() constructs the RoutedExperts(inner +
dispatcher) hierarchy with our compute_backend preserved. GPU smoke next.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jul 17, 2026
…rts replay

3 commits (merge 412d93f): the MoE refactor pytorch#3859 (sibling
RoutedExperts=inner_experts+token_dispatcher) required a 5-file replay in
ezpz/moe; sync_smoke VERDICT ok (job 12470902, all 3 configs incl moe rc=0).
Full detail in the 70th-sync entry.
mreso added a commit to mreso/torchtitan that referenced this pull request Jul 17, 2026
Absorbs 3 upstream commits: RL CI fix (pytorch#3930), the FlexAttention spmd_types
output typing change (pytorch#3924), and pytorch#3859 ("[MoE] sibling token_dispatcher +
grouped_experts for composable override"), which refactored the core MoE.

pytorch#3859 required adapting the HF backend (no git conflicts, but silent API/struct
breakage):
- moe_replacement.py: make_experts_config -> make_routed_experts_config +
  make_moe_config(routed_experts=...); dropped the token_dispatcher kwarg from
  the GroupedExperts.Config probe (token_dispatcher moved to RoutedExperts).
- parallelize.py: FSDP expert sharding reads moe.routed_experts.inner_experts
  (was moe.experts).
- state_dict_adapter.py: titan MoE expert FQNs moved experts.* ->
  routed_experts.inner_experts.*; the adapter still emitted the old prefix, so
  load_state_dict(strict=False) silently skipped the expert weights (random init
  -> HF-vs-titan forward cos ~= 0 while the round-trip still passed). Route the
  routed-expert keys through the new prefix; also tighten the gate_up/down
  special-cases to ".experts." so shared_experts can't be misrouted.

Verified: MoE numerical equivalence restored (qwen3_moe/deepseek_v2/olmoe PASS
cos ~= 1.0; mixtral WARN at cos 0.999996 -- the documented bf16-combine band, not
structural); round-trips max_diff=0.00; MoE EP=2 trains 12.33 -> 6.72.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jul 18, 2026
… RL cleanup) + fix dashboard SFT-full row

- journal.md: add the 2026-07-18 session -- full-mix SFT eval complete on all 3
  axes (ckpt-900 deliverable, 8672 overfit; LR-x-tokens root cause), GRPO
  0.31->0.74 validation + the vLLM-path detour lesson, RL script cleanup, 70th
  sync (MoE pytorch#3859 replay), macOS import-ezpz gotcha
- dashboard: fix self-contradictory SFT-full row (advancing+complete) -> clean
  complete with deliverable=ckpt-900 summary across all 3 eval axes
pianpwk added a commit that referenced this pull request Aug 20, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.12.0)
(oldest at bottom):
* #4235
* __->__ #4249

PR #3859 moved grouped expert weights from MoE.experts to
MoE.routed_experts.inner_experts. Update the transformers modeling
backend tests to follow the new module structure.
acisseJZhong pushed a commit that referenced this pull request Sep 2, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.12.0)
(oldest at bottom):
* #4235
* __->__ #4249

PR #3859 moved grouped expert weights from MoE.experts to
MoE.routed_experts.inner_experts. Update the transformers modeling
backend tests to follow the new module structure.

Original PR: #4249

(cherry picked from commit 1dfeff9)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl ciflow/8gpu 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.

3 participants