Skip to content

[config] Reject unsupported TP/EP degrees for FLUX - #5995

Merged
tianyu-l merged 8 commits into
pytorch:mainfrom
bantianyue:cursor/flux-reject-unsupported-tp-ep-994c
Nov 18, 2026
Merged

tianyu-l merged 8 commits into
pytorch:mainfrom
bantianyue:cursor/flux-reject-unsupported-tp-ep-994c

Conversation

@bantianyue

@bantianyue bantianyue commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Flux has no tensor-parallel plan and no MoE layers, but tensor_parallel_degree / expert_parallel_degree > 1 were accepted at config time and only failed later (often as OOM, #5854). This PR rejects such configs early with a ValueError from validate_model_training_config.

What changed

  • torchtitan/config/validation.py: _validate_declared_parallel_axes() now checks required mesh axes per layout in a single loop over _collect_model_layouts:
    • Dense layouts (everything outside routed-expert submodules) must name each of TP, CP, DP_REPLICATE, and DP_SHARD whose degree is > 1. A logical dp placement counts as declaring the DP storage axes.
    • Sparse layouts are the children of each <moe>.routed_experts slot found by traversing MoE.Config, so Dist-MoE replacements of RoutedExperts are covered too. With expert_parallel_degree > 1, each must name EP and EDP_SHARD (the mesh keeps edp_shard active whenever EP is on), plus DP_REPLICATE when that degree is active. A model with no MoE.Config is rejected. A config built with expert_parallel_degree == 1 gets dense expert weight placements, so validating it at EP > 1 fails here instead of silently ignoring the degree at runtime.
    • Activation contracts on the routed_experts container itself stay on the dense mesh.
  • torchtitan/models/base/module.py: Module._parallelize() raises when TP/EP is enabled and a module owns parameters but declares no sharding_config (they would be silently replicated). Buffers alone do not trip this: MoE load-balance losses own only per-rank statistics buffers. The previous parallelism_context is not None guard is gone; unit tests now pass a minimal context.
  • torchtitan/models/flux/model.py: pipeline() raises NotImplementedError (backstop).
  • torchtitan/models/flux/trainer.py: FluxTrainer.Config.__post_init__ rejects pipeline_parallel_degree > 1 with a ValueError at config time.
  • torchtitan/models/base/model.py: removed the supports_tensor_parallel and supports_pipeline_parallel flags and the flag check in pipeline().
  • Tests: Flux TP/EP cases in test_tp_kv_heads_validation.py now use the public build_model_config("flux-debug", parallelism=...) (moved to module top level, outside the import guard); the accelerator-graphs EP tests in test_config_validation.py rebuild with build_model_config(..., parallelism=...) instead of patching the degree after build; added partial-TP, test_ep_off_routed_experts_checked_as_dense, EP-off-built MoE, and Flux PP tests (the Dist-MoE recipe is covered by the existing B200/RL integration configs, which run this validator); _parallelize protocol tests pass a minimal ParallelismContext. test_later_moe_layer_not_divisible now builds the model with EP=8 so layouts already declare EP/EDP before the expert-count check.

Notes for reviewers

  • This rework follows the feedback on Reject TP/EP degrees for models that do not implement them #5855 and the later reviews on this PR: no new capability flag; the check is derived from the model config itself.
  • The FSDP composability issue (SPMD typechecking failing identically with and without TP inside _cast_fp_tensor) is a separate bug and is intentionally not addressed here.
  • AI-assisted contributions: this PR was developed with AI assistance; the summary above and the test results below were written and verified by the author.

Test plan

  • tests/unit_tests/cpu/config/test_tp_kv_heads_validation.py: 10/10 passed (incl. 3 Flux cases + 1 new partial-TP case).
  • tests/unit_tests/cpu/config/test_config_validation.py: passes, including test_ep_off_routed_experts_checked_as_dense (the always-skipped Dist-MoE case was removed per review).
  • Latest head (77b8c752c): tests/unit_tests/cpu/config/ + tests/unit_tests/cpu/models/base/test_module.py + tests/unit_tests/cpu/distributed/test_expert_parallel.py: 269 passed. This includes the lint fixes (N814/B009) and the EP=8 rebuild of test_later_moe_layer_not_divisible. Earlier rounds: tests/unit_tests/cpu/distributed/test_pipeline_parallel.py: 53/53; tests/unit_tests/cpu/models/base/test_module.py supplies a real ParallelismContext to the _parallelize protocol tests.
  • Sweep over all 13 model debugmodel flavors: every TP-capable model accepts TP=2; every MoE model built with EP accepts EP=2; EP-off-built MoE configs are rejected at EP=2; dense models and Flux reject EP=2; only Flux rejects TP=2.
  • flake8 on the changed files passes after dropping the MeshAxisName as A alias and the constant getattr; ufmt is unchanged on the new/edited hunks.

Fixes #5854.

@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 10, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 10, 2026
@pytorch-bot

pytorch-bot Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

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

see my feedback in #5855

bantianyue added a commit to bantianyue/torchtitan that referenced this pull request Nov 10, 2026
Replace the supports_tensor_parallel / supports_pipeline_parallel flag
approach with a config-time check derived from the model itself:

- validation.py: new _declared_spmd_axes() collects the SPMD axes named
  by every sharding config in the model config tree, and
  _validate_declared_parallel_axes() raises ValueError when
  tensor_parallel_degree > 1 but no tensor is sharded over TP. TP
  placements are unconditional, so this does not depend on how the model
  config was built. Expert parallelism cannot be derived the same way:
  MoE weight placements only name the EP axis when the config was built
  with EP enabled, so a config built with expert_parallel_degree == 1
  would look EP-incapable even for a genuine MoE model; EP support
  instead follows from the presence of MoE layers. Flux declares only
  DP/CP and has no MoE layers, so both TP and EP degrees > 1 are rejected
  at config time (fixes pytorch#5854).
- base/model.py: delete supports_tensor_parallel and
  supports_pipeline_parallel flags and the flag check in pipeline().
- flux/model.py: delete both flags; add a pipeline() override that raises
  NotImplementedError.
- tests: merge the Flux TP/EP cases into
  test_tp_kv_heads_validation.py and delete
  test_flux_parallelism_validation.py (its try/except import guard and
  skipUnless could hide a broken import as a skip); drop the
  supports_pipeline_parallel line in test_pipeline_parallel.py.

Verified locally: test_tp_kv_heads_validation.py 9/9,
test_config_validation.py 55 tests, test_pipeline_parallel.py 53/53;
a 13-model sweep confirms every TP-capable model accepts TP=2, every
MoE model accepts EP=2 even when built with EP off, dense models and
Flux reject EP=2, and only Flux rejects TP=2.

Signed-off-by: bantianyue <[email protected]>
@bantianyue

Copy link
Copy Markdown
Contributor Author

Hi @tianyu-l, reworked per your feedback in #5855 — the flag approach is gone:

  • No supports_tensor_parallel flag; the TP check is derived from the sharding configs themselves (_declared_spmd_axes() in validation.py): TP > 1 raises when no tensor is sharded over TP. Flux only declares DP/CP, so it is rejected at config time.
  • EP is checked via MoE-layer presence rather than sharding axes, because MoE weight placements only name the EP axis when the config was built with EP enabled — deriving EP from sharding configs would wrongly reject a genuine MoE config built with expert_parallel_degree == 1 (verified: a deepseek_v3 debugmodel built with EP off declares no EP axis, and the repo's own test_accelerator_graphs_reject_synchronizing_ep_dispatcher relies on that build-then-mutate pattern). Flux has no MoE layers, so EP > 1 is rejected.
  • supports_pipeline_parallel is also deleted (base + flux + the test line), with a pipeline() override on Flux raising NotImplementedError.
  • Flux test cases are merged into test_tp_kv_heads_validation.py and the separate test file is deleted.

Local verification: the four config test files pass (65 tests incl. 9/9 in test_tp_kv_heads_validation.py), test_pipeline_parallel.py 53/53, plus a 13-model sweep confirming TP-capable models accept TP=2, MoE models accept EP=2, and only Flux rejects TP=2. Lint (flake8/ufmt/pydoclint/codespell) passes on the changed files.

Could you approve the ciflow/fake-pg workflow runs so CI can run on this head, and re-review when you have a chance? Thanks!

Comment thread torchtitan/config/validation.py Outdated
Comment on lines +85 to +88
if (
parallelism.tensor_parallel_degree > 1
and MeshAxisName.TP not in _declared_spmd_axes(model)
):

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.

It feels to me the logic is not robust here.

  • If some module is defined with TP sharding but other are not, current PR will allow but it should fail.
  • For dense and sparse, we have to do different treatment: TP / CP doesn't need to be in sparse module, EP / EDP doesn't need to be in dense module

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 4m 27s —— View job


Request changes: the TP/EP checks run over the whole model, so partly sharded models still pass, and @tianyu-l's comment at validation.py:88 is still open. 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: Request changes -- @tianyu-l's comment at validation.py:88 holds up and is not addressed at HEAD. The check runs once over the whole model ("does any layout name TP?" / "is there any MoE?"), so a model that is only partly sharded still passes.

What this PR does. It adds a config-time check: if tp > 1, the model's sharding configs must mention TP somewhere; if ep > 1, the tree must contain an MoE.Config. It also deletes supports_pipeline_parallel (Flux now overrides pipeline() to raise) and adds three Flux cases to the existing test.

Example.

flux_schnell, tp=2            main: OOM at model build    PR: ValueError (good)
model X, tp=2: attention declares TP, a second block's
  layouts omit TP             main: block silently replicated   PR: passes (bad)
deepseek_v3 built ep=1, then ep=2   routed experts have no EP layout   PR: passes (bad)

On @tianyu-l's comment (validation.py:88)

Both bullets are right, and Module._parallelize already gives the data needed to fix them.

  • Partial TP. Each state is distributed only over the axes its own layout names (_spmd_distribute_state -> get_optional_mesh(spmd_axes(layout)), base/module.py:383). A layout that leaves out TP is therefore replicated over TP without any error. The check has to run on each layout, not on the union of all of them.
  • Dense vs sparse. Dense layouts are the ones outside routed-expert weights. When tp > 1 each of them must name TP, and when cp > 1 each must name CP. Routed-expert weight layouts (w13/w2 under RoutedExperts.Config) must name EP when ep > 1. If ep > 1 and the model has no routed experts, raise. This one rule replaces both branches here, and it rejects EP-off-built MoE configs too (see the inline comment).
  • Modules with no sharding_config are still a gap. Flux's Linears have none; only its inner attention declares layouts. _parallelize silently returns for these modules (base/module.py:369-371, where a TODO already wants an assert). The config tree can't tell which configs own parameters. So, as a small companion change: when tp > 1 or ep > 1, raise in _parallelize if a module owns parameters but has no sharding_config. This still runs on the meta device, before any memory is allocated.

Must fix

  1. validation.py:85-88 -- rewrite the TP check per layout, as above (@tianyu-l).
  2. validation.py:95 -- the EP check looks for MoE layers, not for EP-sharded expert weights. Details inline.
  3. test_tp_kv_heads_validation.py:41 -- imports the private _flux_debug, inside a try/except guard that can turn a broken import into a silent skip. Details inline.

Should consider

  • validation.py:81-84 -- the _owner is None fallback can never run.
  • flux/model.py:109 -- reject PP > 1 in FluxTrainer.Config.__post_init__ instead, so it fails at config time.

Questions

  • Does any TP-capable model (qwen3, deepseek_v3/v4, gpt_oss, kimi, muse_glimmer, qwen3_5 vision encoder) today have parameter-owning modules with no sharding_config, or dense layouts that omit TP? Your 13-model sweep can answer this directly once the check runs per layout. If there are any, they are real TP gaps and need fixing or listing.

Not verified: I could not run Python here, so the per-layout coverage of the other models and the runtime behavior of an EP-off-built MoE config at ep > 1 are unconfirmed.

Comment thread torchtitan/config/validation.py Outdated
f"{parallelism.tensor_parallel_degree}. Set tensor_parallel_degree "
"to 1, or use a model that shards over 'tp'."
)
if parallelism.expert_parallel_degree > 1 and not list(model.traverse(MoE.Config)):

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 EP check asks "does the tree contain an MoE.Config?", not "are the routed experts actually EP-sharded?". Here is a MoE config that passes it but won't be EP-sharded: one built with expert_parallel_degree == 1 and then given ep > 1. build_model_config set enable_ep=False, so routed_expert_weight_placement (models/common/moe/sharding.py:165-173) returned the dense {DP, CP, TP: R} layout. Nothing in that tree names EP, so the EP degree gets ignored. That is the same failure this PR fixes for Flux, just in a MoE model.

The PR description defends this by pointing at build-then-mutate tests (test_config_validation.py:146-173). That argues for changing those tests, not for keeping the heuristic: config.md says derived values like sharding are set when the config is built and are not patched afterwards. Following @tianyu-l's dense/sparse split: when ep > 1, require every routed-expert weight layout (the w13/w2 configs under each RoutedExperts.Config) to name EP. If there are no routed experts at all, raise. That one rule covers Flux, dense Decoders, and EP-off MoE configs. Then update those tests to rebuild with build_model_config(..., parallelism=config.parallelism).

Unverified: whether an EP-off-built MoE config fails loudly or silently at runtime with ep > 1. Either way, config time is the place to reject it.

Comment thread torchtitan/config/validation.py Outdated
Comment on lines +81 to +84
model_cls = type(model)._owner
model_name = (
model_cls.__name__ if model_cls is not None else type(model).__qualname__
)

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.

_owner is always set on a BaseModel.Config subclass, so the None branch never runs. Use type(model).__qualname__ directly (as validate_context_parallel does with config names) and drop the two-way fallback. This goes away anyway if the helper is rewritten per the review body.

Linear,
RMSNorm,
)
from torchtitan.models.flux.flavors import _flux_debug

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.

There are two problems with this import:

  1. It imports the private _flux_debug from another module. Use the public builder instead: build_model_config("flux-debug", parallelism=parallelism) from torchtitan.models.flux. Pass it the same ParallelismConfig you validate against, so the test doesn't build the config at TP/EP = 1 and then validate it at 2.
  2. It sits inside the file's broad try/except Exception -> _IMPORTS_OK = False guard. If the Flux import breaks, every test in this file, including the existing GQA ones, becomes a silent skip. That is the problem the previous review raised about the deleted file. Import Flux at module top level, outside the guard (it needs no optional dependency).


def pipeline(self, **kwargs: Any) -> tuple[Any, list[BaseModel], bool, bool]:
"""Flux has no pipeline-parallel plan."""
raise NotImplementedError("FluxModel does not support pipeline parallelism.")

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.

Should consider: with this override, pipeline_parallel_degree > 1 for Flux still only fails after the mesh is built and the model is constructed. The repo rule is a ValueError at config time for unsupported configurations. Flux already has its own FluxTrainer.Config, so rejecting parallelism.pipeline_parallel_degree > 1 in its __post_init__ keeps the check in the model folder. Keep this override as a backstop, or drop it if the config check makes it unreachable.

bantianyue added a commit to bantianyue/torchtitan that referenced this pull request Nov 12, 2026
Address tianyu-l's and claude's review comments on the per-model
TP/EP config validation:

- validation.py: check TP/EP per layout instead of over the union of
  all layouts. Dense layouts (everything outside routed-expert
  weights) must each name TP when tensor_parallel_degree > 1. EP is
  checked on the routed-expert weights themselves (w13/w2 under each
  RoutedExperts.Config): with expert_parallel_degree > 1 each must
  name EP, and a model with no routed experts is rejected. A config
  built with expert_parallel_degree == 1 gets dense expert weight
  placements, so it is rejected here instead of silently ignoring the
  EP degree at runtime. CP is intentionally not checked per layout:
  Kimi K3's layer-0 block_residual boundary omits CP while Kimi K3
  with context_parallel_degree == 2 is a working, integration-tested
  configuration; CP stays covered by validate_context_parallel.
  Also use type(model).__qualname__ for the model name (the _owner
  None branch could never run).
- base/module.py: in Module._parallelize, raise when TP/EP is enabled
  and a module owns parameters but declares no sharding_config (it
  would silently replicate them). Buffers alone do not trip this:
  MoE load-balance losses own only per-rank statistics buffers.
- flux/trainer.py: reject pipeline_parallel_degree > 1 with a
  ValueError in FluxTrainer.Config.__post_init__ (config time);
  the FluxModel.pipeline() override stays as a backstop.
- tests: use the public build_model_config("flux-debug", ...) instead
  of the private _flux_debug import, moved outside the import guard;
  rebuild the accelerator-graphs EP tests with
  build_model_config(..., parallelism=...) instead of patching the
  degree after build; add partial-TP, EP-off MoE, and Flux PP tests.

Verified locally: config tests 68/68 (incl. 3 new), pipeline tests
53/53, module tests 35/35; a 13-model sweep confirms every
TP-capable model accepts TP=2, every MoE model built with EP accepts
EP=2, EP-off-built MoE configs are rejected at EP=2, dense models
and Flux reject EP=2, and only Flux rejects TP=2.

Signed-off-by: bantianyue <[email protected]>
@bantianyue

Copy link
Copy Markdown
Contributor Author

Hi @tianyu-l, addressed your second-round feedback in 601cf2a: the TP/EP check now runs per layout (every dense layout must name TP; EP is checked on the routed-expert w13/w2 weights, so EP-off-built MoE configs are rejected too), plus the FluxTrainer.Config PP ValueError and the _parallelize guard for parameter-owning modules without a sharding_config. One deliberate deviation, documented in the PR description: CP is not checked per layout, because Kimi K3's layer-0 block_residual boundary omits CP while Kimi K3 cp=2 is a working integration-tested config. Could you approve the ciflow/fake-pg CI runs and re-review when you get a chance? Thanks!

Comment thread torchtitan/config/validation.py Outdated
Comment on lines +99 to +104
CP is intentionally not checked per layout: Kimi K3's layer-0
``block_residual`` boundary omits CP (``multimodal_first_layer_sharding_config``;
the tensor is empty at layer 0 and no later layer declares it), while
Kimi K3 with ``context_parallel_degree == 2`` is a working,
integration-tested configuration. CP stays covered by the structural
``validate_context_parallel`` check below.

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.

Hmm, maybe it was working, but can we make every axis explicit, including DP, CP, EDP?

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

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


Request changes: the earlier must-fix items are resolved, but the new check would reject the verified Dist-MoE recipes, and @tianyu-l's "every axis explicit" comment is still open. 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: Request changes -- every must-fix from the last review is resolved, but the new sparse-region detection rejects the verified Dist-MoE recipes, and @tianyu-l's "make every axis explicit" comment (validation.py:104) is still open.

What changed since the last review. The TP check now runs on each layout instead of the union of all layouts. EP is checked on the routed-expert weights. The Flux tests use the public builder. Flux PP is rejected in FluxTrainer.Config.__post_init__. _parallelize raises for modules that own parameters but have no sharding_config.

Example.

flux_schnell, tp=2                        -> ValueError (good)
llama3, tp=2, one dense layout without TP -> ValueError (good)
deepseek_v3 built ep=1, validated ep=2    -> ValueError (good)
deepseek_v3_671b_dist_moe_bf16 (EP=64)    -> ValueError "has no routed experts" (bad)
muse_spark Dist-MoE, TP=4, EP=64          -> ValueError "declares no 'tp' sharding" (bad)

Earlier must-fix items

  • Per-layout TP check (@tianyu-l): resolved.
  • EP checked on expert weights, EP-off-built MoE configs rejected: resolved.
  • Private _flux_debug import inside the import guard: resolved.
  • _owner fallback, Flux PP rejected at config time: resolved.

Must fix

  1. validation.py:104 -- @tianyu-l asked that every axis be explicit, including DP, CP and EDP. HEAD still exempts CP and doesn't check DP/EDP. Proposed shape:
    • Dense layouts must name each of DP, CP, TP whose degree is > 1.
    • Sparse layouts must name each of EDP, EP whose degree is > 1.
    • This removes the CP carve-out, so Kimi K3's layer-0 block_residual layout (multimodal_first_layer_sharding_config) has to name CP, instead of the validator working around it.
    • Maintainers should confirm whether the check is gated on degree > 1 or always applies. "Always" would reject EP-off-built MoE configs by design.
  2. validation.py:115 -- the sparse region is found with traverse(RoutedExperts.Config). After DistMoeTransform no RoutedExperts.Config remains, so the verified 671B Dist-MoE recipes and the muse_spark Dist-MoE recipes fail validation. Use the MoE.Config.routed_experts slot instead (inline).
  3. validation.py:140-143 -- the EP block silently skips an expert weight with no sharding_config, and its None guards protect required fields. Fold it into the single per-layout loop (inline).

Should consider

  • module.py:380 -- the parallelism_context is not None branch exists only for _parallelize(None) calls in tests. Fix the tests, not the production code (inline).

Questions

  • The 13-model sweep covers the debugmodel flavors only. Did it apply any config transforms? Please extend it to the Dist-MoE recipes (deepseek_v3_671b_dist_moe_*, the muse_spark Dist-MoE builders), building their configs on CPU. That would have caught item 2.

Not verified: I could not run Python. The Dist-MoE failures come from reading config/transform/dist_moe.py:66-85 and config/transform/apply.py:124.

Comment thread torchtitan/config/validation.py Outdated
ep = parallelism.expert_parallel_degree

# The routed-expert (sparse) region lives under RoutedExperts.Config.
sparse_prefixes = [fqn for fqn, _, _, _ in model.traverse(RoutedExperts.Config)]

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 rejects every Dist-MoE recipe. DistMoeTransform (config/transform/dist_moe.py:66-85) replaces each RoutedExperts.Config with a DistMoeRoutedExperts.Config, which subclasses Module.Config and not RoutedExperts.Config. Then apply_transforms re-runs __post_init__ (config/transform/apply.py:124), and that calls this validator. At that point sparse_prefixes is empty, so:

  • deepseek_v3_671b_dist_moe_bf16 / _mxfp8 (EP=64) and the muse_spark Dist-MoE recipes (EP=16/32/64) fail with "has no routed experts".
  • muse_spark with TP=4/8 + Dist-MoE also fails the TP loop, because its w13/w2 expert layouts are now counted as dense and they don't name TP.

Take the sparse region from the MoE.Config.routed_experts slot instead of from the expert type. That covers both implementations without importing dist_moe:

sparse_prefixes = [
    f"{fqn}.routed_experts" if fqn else "routed_experts"
    for fqn, _, _, _ in model.traverse(MoE.Config)
]

Unverified: I couldn't run Python here. The path above is from reading the code.

Comment thread torchtitan/config/validation.py Outdated
Comment on lines +140 to +143
for fqn, experts, _, _ in model.traverse(RoutedExperts.Config):
for sub in ("w13", "w2"):
sub_cfg = getattr(experts, sub, None)
if sub_cfg is None or sub_cfg.sharding_config is None:

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 second traversal duplicates _collect_model_layouts and has two problems:

  • w13/w2 are required fields on RoutedExperts.Config, so getattr(..., None) and sub_cfg is None guard against a case that can't happen.
  • sharding_config is None: continue silently passes the exact case this check exists for: expert weights that won't be EP-sharded.

Use one loop instead. For each layout from _collect_model_layouts, decide its region (dense or sparse) with _is_sparse(fqn), then require every axis of that region whose degree is > 1. That deletes this block and the hardcoded ("w13", "w2"). A missing sharding_config on a parameter-owning module is still caught by the new _parallelize guard. This loop is also where @tianyu-l's "every axis explicit" request (line 104) would go.

Comment thread torchtitan/models/base/module.py Outdated
# protocol check above; without mesh info there is nothing to
# enforce here.
if (
parallelism_context is not None

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.

Should consider: parallelism_context is typed ParallelismContext, not Optional. So this is not None branch only exists for the three model._parallelize(None) calls in tests/unit_tests/cpu/models/base/test_module.py:429,450,470. Production code shouldn't accommodate a test calling it with an invalid argument. Have those tests pass a minimal context (or a stub with tp_enabled = ep_enabled = False) and drop this condition along with the comment lines that explain it.

@cursor
cursor Bot force-pushed the cursor/flux-reject-unsupported-tp-ep-994c branch 2 times, most recently from 6043d0f to c73583d Compare November 13, 2026 01:03
@bantianyue

Copy link
Copy Markdown
Contributor Author

Hi @tianyu-l, the third-round review comments are addressed in c73583d:

  • Every active axis is now required explicitly: dense layouts must name TP / CP / DP_REPLICATE / DP_SHARD when the corresponding degree is > 1, and sparse routed_experts layouts must name EP (plus EDP_SHARD / DP_REPLICATE when those are active). The previous CP carve-out is gone — Kimi K3's layer-0 block_residual placement now names CP.
  • Sparse regions are detected from the routed_experts path under MoE.Config, so Dist-MoE recipes still validate after DistMoeTransform replaces RoutedExperts.Config. Added test_dist_moe_recipe_passes_parallel_axis_validation for that path.
  • The separate expert-weight walk is folded into the single per-layout loop.
  • Module._parallelize no longer special-cases a missing context; the unit tests now pass a minimal ParallelismContext.

Could you take another look when you have a chance? Thanks!

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 4m 0s —— View job


Approve -- please address the items before merging (a maintainer still needs to review, and CI has not run on this head yet): 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 design now matches what @tianyu-l asked for, and every earlier must-fix is resolved. What's left is a local simplification and a test that never runs in CI. This touches core (validation.py, base/module.py), so a maintainer still needs to review, and the fake-pg CI still needs approval and a pass.

What this PR does. At config time, every SPMD layout in the model must name each mesh axis that is active for its region. Dense layouts: TP / CP / DP_REPLICATE / DP_SHARD (logical dp counts for both DP storage axes). Layouts under routed_experts: EP / EDP_SHARD / DP_REPLICATE. If EP > 1 and the model has no MoE, the config is rejected. _parallelize raises when a module owns parameters but has no sharding_config under TP/EP. Flux PP is rejected in FluxTrainer.Config.

Example.

flux-debug, tp=2                          -> ValueError "declares no 'tp' sharding" (main: OOM)
flux-debug, ep=2                          -> ValueError "has no routed experts"
llama3, tp=2, wqkv weight without TP      -> ValueError (main: silently replicated)
deepseek_v3 built ep=1, validated at ep=2 -> ValueError "declares no 'ep' sharding"
deepseek_v3 Dist-MoE, tp=2 ep=2 fsdp=2    -> passes
kimi_k3, cp=2                             -> passes (block_residual now names CP)

Earlier must-fix items

  • Every axis explicit, including DP/CP/EDP (@tianyu-l, validation.py:104): resolved. The Kimi K3 CP carve-out is gone. block_residual is built from h_TD (kimi_k3/model.py:457), so CP: V with (DP, CP[, TP]) is the accurate type and matches the decoder convention.
  • Dist-MoE detection: resolved. _is_sparse now matches the routed_experts slot instead of the RoutedExperts.Config type.
  • Separate EP walk with None guards: resolved (folded into one loop).
  • _parallelize(None) branch: resolved. The tests now pass a real context.

Must fix

  1. validation.py:186-218 -- three single-use helpers, a per-iteration message dict, and EDP arithmetic that re-derives dp_shard*cp*tp//ep and doesn't match ParallelismContext._axis_is_active (edp_shard stays active whenever ep > 1). Inline sketch, about 100 fewer lines.
  2. test_config_validation.py:187 -- the Dist-MoE test always skips in CI (dist_moe isn't installed in the CPU job), and the B200 and RL Dist-MoE integration configs already run this validator. Delete it.
  3. validation.py:145 -- broken docstring line (suggestion attached).
Details
  • Net +352 LoC. About 140 of that is in validation.py, and the sketch above roughly halves it. The rest is tests and the small Flux/K3/module changes.
  • The hybridep test edits are right: deepseek_v3_debugmodel_hybridep already builds with expert_parallel_degree=2 (torchtitan_recipes/tests/models/deepseek_v3.py:160), so the removed post-build mutation was redundant.
  • The _parallelize guard only fires at model build. The 13-model sweep in the description is config-level, so it doesn't exercise this guard.

Not verified: no CI run on this head yet (all workflows are action_required). In particular, the _parallelize guard across TP/EP integration configs and Kimi K3 cp=2 with spmd typechecking still need the fake-pg and GPU runs.

Comment thread torchtitan/config/validation.py Outdated
Comment on lines +186 to +218
for fqn, field, axes in _collect_model_layouts(model):
axes_set = set(axes)
if _is_sparse(fqn):
required_axes = sparse_required
sparse = True
else:
required_axes = dense_required
sparse = False
for axis in required_axes:
if _layout_declares_axis(axis, axes_set, sparse=sparse):
continue
degree_field = {
MeshAxisName.TP: "tensor_parallel_degree",
MeshAxisName.CP: "context_parallel_degree",
MeshAxisName.EP: "expert_parallel_degree",
MeshAxisName.DP_REPLICATE: "data_parallel_replicate_degree",
MeshAxisName.DP_SHARD: "data_parallel_shard_degree",
}.get(axis)
if degree_field is not None:
degree = getattr(parallelism, degree_field)
degree_msg = (
f"parallelism.{degree_field} is {degree}. Set {degree_field} to 1, "
"or declare the axis on that layout."
)
else:
degree_msg = (
"parallelism enables a derived expert FSDP axis (edp_shard). "
"Declare 'edp_shard' on that layout."
)
raise ValueError(
f"{model_name} declares no '{axis.value}' sharding in {fqn} ({field}), "
f"but {degree_msg}"
)

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 rule is now right, but it is spread over three single-use helpers (_layout_declares_axis, _dense_parallel_axes_required, _sparse_parallel_axes_required) plus a per-iteration degree_field dict with a .get() fallback just for the error message. That is about 140 lines for a check that fits in about 35. axes_set = set(axes) also copies something that is already a set.

The EDP arithmetic in _sparse_parallel_axes_required (lines 124-132) re-derives dp_shard * cp * tp // ep, and it doesn't match the mesh: ParallelismContext._axis_is_active keeps edp_shard alive whenever ep > 1, even at size 1. Every sparse placement (expert_param_placement_sparse, replicated_param_placement_sparse) already names EDP_SHARD. So just require it whenever EP is on, and the arithmetic goes away.

Suggested shape (inline the helpers, delete them):

    A = MeshAxisName
    p = parallelism
    model_name = type(model).__qualname__
    # degree != 1 also covers dp_shard == -1.
    dense_required = [
        axis
        for axis, degree in (
            (A.TP, p.tensor_parallel_degree),
            (A.CP, p.context_parallel_degree),
            (A.DP_REPLICATE, p.data_parallel_replicate_degree),
            (A.DP_SHARD, p.data_parallel_shard_degree),
        )
        if degree != 1
    ]
    sparse_required = []
    if p.expert_parallel_degree > 1:
        if not any(model.traverse(MoE.Config)):
            raise ValueError(f"{model_name} has no routed experts; ...")
        # The mesh keeps edp_shard alive whenever EP is enabled.
        sparse_required = [A.EP, A.EDP_SHARD]
        if p.data_parallel_replicate_degree > 1:
            sparse_required.append(A.DP_REPLICATE)

    for fqn, field, axes in _collect_model_layouts(model):
        if _is_sparse(fqn):
            required = sparse_required
        else:
            required = dense_required
            if A.DP in axes:  # logical dp folds dp_replicate and dp_shard
                axes = axes | {A.DP_REPLICATE, A.DP_SHARD}
        for axis in required:
            if axis not in axes:
                raise ValueError(
                    f"{model_name} declares no '{axis.value}' sharding in "
                    f"{fqn} ({field}), but that mesh axis is active. Set its "
                    "parallelism degree to 1, or declare the axis on that layout."
                )

This keeps the existing test regexes (declares no 'tp' sharding, has no routed experts). Optionally, take _is_sparse's prefixes from model.traverse(MoE.Config) (f"{fqn}.routed_experts.") rather than matching the bare "routed_experts" name. Then the sparse region and the has_routed_experts check come from the same source.

Comment thread torchtitan/config/validation.py Outdated
that never mentions an axis is replicated over that axis, so a model
that is only partly sharded must not pass.

Dense and sparse layouts get different treatment. Layouts on ``routed_experts`` submodules (``w13``, ``w2``, 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.

A bad edit left a run of spaces mid-sentence, and the line is now over the docstring width.

Suggested change
Dense and sparse layouts get different treatment. Layouts on ``routed_experts`` submodules (``w13``, ``w2``, postprocess,
Dense and sparse layouts get different treatment. Layouts on
``routed_experts`` submodules (``w13``, ``w2``, postprocess,

Comment on lines +187 to +208
def test_dist_moe_recipe_passes_parallel_axis_validation() -> None:
"""Dist-MoE configs must validate after MoE routed_experts replacement."""
dist_moe = pytest.importorskip(
"dist_moe",
reason="Dist-MoE validation test requires the optional dist_moe package",
)
del dist_moe # imported only to skip cleanly when missing
from torchtitan.config.parallelism import ParallelismConfig

from torchtitan_recipes.tests.models.deepseek_v3 import (
deepseek_v3_debugmodel_dist_moe_bf16,
)

config = deepseek_v3_debugmodel_dist_moe_bf16(
parallelism=ParallelismConfig(
tensor_parallel_degree=2,
expert_parallel_degree=2,
data_parallel_shard_degree=2,
context_parallel_degree=1,
)
)
config.__post_init__()

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.

In CI this test always skips, and the path it targets is already covered elsewhere.

  • unit_test_cpu.yaml runs tests/unit_tests/cpu without installing dist_moe, so importorskip always skips it there. The only job that installs dist_moe (integration_test_b200.yaml:83-85) runs tests/unit_tests/cpu/models/common/test_dist_moe.py, not this file.
  • The validator already runs on Dist-MoE recipes that have EP active. It runs in __post_init__ of the B200 integration configs (deepseek_v3_debugmodel_dist_moe_{bf16,mxfp8}_fsdp2_ep2, tests/integration_tests/b200.py) and of the RL rl_grpo_moe_debug_dist_moe_tp2_ep4 (TP=2, EP=4), and those jobs do install dist_moe.

Delete it. If you want a CPU-level guard anyway, move it into tests/unit_tests/cpu/models/common/test_dist_moe.py, which already has the module-level importorskip and actually runs. Also, the local ParallelismConfig import duplicates the top-level one, and context_parallel_degree=1 is the default.

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

please address comments from me and claude

Comment thread torchtitan/config/validation.py Outdated
model_name = type(model).__qualname__
ep = parallelism.expert_parallel_degree

has_routed_experts = any(True for _ in model.traverse(MoE.Config))

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.

should search for RoutedExperts or DistMoeRoutedExperts; o/w should rename to has_moe

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.

Renamed away from has_routed_experts: the sparse region is now derived from model.traverse(MoE.Config) (<moe>.routed_experts.*), and the EP>1 "no routed experts" check uses the same traversal, so it is effectively a has_moe check that also covers DistMoeRoutedExperts. Fixed in 82fd9c7.

bantianyue added a commit to bantianyue/torchtitan that referenced this pull request Nov 16, 2026
Address review on pytorch#5995:
- Inline the per-layout axis check (drop three single-use helpers and
  the per-axis message dict); require edp_shard whenever EP is on, as
  the mesh keeps it active.
- Derive the sparse region from MoE.Config traversal
  (<moe>.routed_experts.*) so the MoE check and sparse detection share
  one source; this also replaces has_routed_experts.
- Fix the broken docstring line.
- Remove the Dist-MoE test that always skips in CPU CI; Dist-MoE B200
  and RL integration configs already run this validator.

Signed-off-by: bantianyue <[email protected]>
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 30s —— View job


Approve: every earlier must-fix is resolved, and a maintainer still needs to review the core changes and the CI run. 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 -- 82fd9c7 resolves every must-fix item from the last review and @tianyu-l's has_moe comment, and the new commit adds no new problems that block merging. This touches core (config/validation.py, models/base/module.py), so a maintainer still needs to review. CI has not run on this head yet (no workflow runs are recorded).

What changed since the last review. The check is now one ~70-line function. Dense layouts must name each active axis among TP, CP, DP_REPLICATE and DP_SHARD; a logical dp placement counts for both DP axes. When EP > 1, layouts under <moe>.routed_experts. must name EP and EDP_SHARD, plus DP_REPLICATE if that axis is active. The sparse prefixes and the "no routed experts" check both come from model.traverse(MoE.Config). The Dist-MoE test that always skipped is deleted.

Example.

flux-debug, tp=2                          -> ValueError "declares no 'tp' sharding"
flux-debug, ep=2                          -> ValueError "has no routed experts"
deepseek_v3 built ep=1, validated at ep=2 -> ValueError "declares no 'ep' sharding"
deepseek_v3 Dist-MoE, ep>1                -> passes (prefix match, not type match)

Earlier must-fix items

  • Inline the three helpers and the message dict; drop the EDP arithmetic: resolved. EDP_SHARD is now required whenever ep > 1, which matches ParallelismContext._axis_is_active (parallelism_context.py:238-241).
  • Delete the Dist-MoE test that always skipped: resolved.
  • Broken docstring line: resolved.
  • @tianyu-l, rename has_routed_experts or search for the expert types: resolved. The flag is gone, and the region comes from the MoE.Config.routed_experts slot, so DistMoeRoutedExperts is covered.

Should consider

  • torchtitan/config/validation.py:133 -- with EP == 1, nothing under routed_experts is checked, even though those weights then use the dense mesh. Details and a suggested fix are in the inline comment.

Not verified: no CI on this head. The _parallelize guard across the TP/EP integration configs and Kimi K3 cp=2 with the new block_residual CP placement still need the fake-pg and GPU runs.

Comment thread torchtitan/config/validation.py Outdated
Comment on lines +133 to +134
if fqn.startswith(sparse_prefixes):
required = sparse_required

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.

Should consider: with expert_parallel_degree == 1, sparse_required is empty, so no layout under <moe>.routed_experts. is checked at all. That case doesn't use the sparse mesh, though. routed_expert_weight_placement(enable_ep=False) returns dense_param_placement(tp=spmd.R) (models/common/moe/sharding.py:172-173), which lives on the dense mesh. So a w13/w2 layout that leaves out DP or CP would pass with dp_shard/cp > 1, ep == 1. That is the same "silently replicated" gap this check closes everywhere else.

Treat the region as sparse only when EP is on. The current dense layouts already name DP/CP/TP, so this should not reject any existing config (unverified for the Dist-MoE children, which declare no sharding_config of their own):

Suggested change
if fqn.startswith(sparse_prefixes):
required = sparse_required
if p.expert_parallel_degree > 1 and fqn.startswith(sparse_prefixes):
required = sparse_required

Add supports_tensor_parallel on BaseModel (default True), set False on
FluxModel, and validate early in validate_model_training_config so dense
models without MoE reject expert_parallel_degree > 1.

Signed-off-by: bantianyue <[email protected]>
Replace the supports_tensor_parallel capability flag with a config-time
check that derives the declared parallel axes from each model's sharding
config: raise ValueError when tensor_parallel_degree > 1 but no TP axis
is declared, or expert_parallel_degree > 1 but no EP axis is declared.
Flux only declares DP/CP, so it is rejected; llama3 always declares TP
placements.

Also delete supports_pipeline_parallel (FluxModel.pipeline now raises
NotImplementedError) and merge the Flux test cases into the existing
TP validation test file, deleting test_flux_parallelism_validation.py.

Fixes pytorch#5854

Signed-off-by: bantianyue <[email protected]>
Replace the supports_tensor_parallel / supports_pipeline_parallel flag
approach with a config-time check derived from the model itself:

- validation.py: new _declared_spmd_axes() collects the SPMD axes named
  by every sharding config in the model config tree, and
  _validate_declared_parallel_axes() raises ValueError when
  tensor_parallel_degree > 1 but no tensor is sharded over TP. TP
  placements are unconditional, so this does not depend on how the model
  config was built. Expert parallelism cannot be derived the same way:
  MoE weight placements only name the EP axis when the config was built
  with EP enabled, so a config built with expert_parallel_degree == 1
  would look EP-incapable even for a genuine MoE model; EP support
  instead follows from the presence of MoE layers. Flux declares only
  DP/CP and has no MoE layers, so both TP and EP degrees > 1 are rejected
  at config time (fixes pytorch#5854).
- base/model.py: delete supports_tensor_parallel and
  supports_pipeline_parallel flags and the flag check in pipeline().
- flux/model.py: delete both flags; add a pipeline() override that raises
  NotImplementedError.
- tests: merge the Flux TP/EP cases into
  test_tp_kv_heads_validation.py and delete
  test_flux_parallelism_validation.py (its try/except import guard and
  skipUnless could hide a broken import as a skip); drop the
  supports_pipeline_parallel line in test_pipeline_parallel.py.

Verified locally: test_tp_kv_heads_validation.py 9/9,
test_config_validation.py 55 tests, test_pipeline_parallel.py 53/53;
a 13-model sweep confirms every TP-capable model accepts TP=2, every
MoE model accepts EP=2 even when built with EP off, dense models and
Flux reject EP=2, and only Flux rejects TP=2.

Signed-off-by: bantianyue <[email protected]>
Address tianyu-l's and claude's review comments on the per-model
TP/EP config validation:

- validation.py: check TP/EP per layout instead of over the union of
  all layouts. Dense layouts (everything outside routed-expert
  weights) must each name TP when tensor_parallel_degree > 1. EP is
  checked on the routed-expert weights themselves (w13/w2 under each
  RoutedExperts.Config): with expert_parallel_degree > 1 each must
  name EP, and a model with no routed experts is rejected. A config
  built with expert_parallel_degree == 1 gets dense expert weight
  placements, so it is rejected here instead of silently ignoring the
  EP degree at runtime. CP is intentionally not checked per layout:
  Kimi K3's layer-0 block_residual boundary omits CP while Kimi K3
  with context_parallel_degree == 2 is a working, integration-tested
  configuration; CP stays covered by validate_context_parallel.
  Also use type(model).__qualname__ for the model name (the _owner
  None branch could never run).
- base/module.py: in Module._parallelize, raise when TP/EP is enabled
  and a module owns parameters but declares no sharding_config (it
  would silently replicate them). Buffers alone do not trip this:
  MoE load-balance losses own only per-rank statistics buffers.
- flux/trainer.py: reject pipeline_parallel_degree > 1 with a
  ValueError in FluxTrainer.Config.__post_init__ (config time);
  the FluxModel.pipeline() override stays as a backstop.
- tests: use the public build_model_config("flux-debug", ...) instead
  of the private _flux_debug import, moved outside the import guard;
  rebuild the accelerator-graphs EP tests with
  build_model_config(..., parallelism=...) instead of patching the
  degree after build; add partial-TP, EP-off MoE, and Flux PP tests.

Verified locally: config tests 68/68 (incl. 3 new), pipeline tests
53/53, module tests 35/35; a 13-model sweep confirms every
TP-capable model accepts TP=2, every MoE model built with EP accepts
EP=2, EP-off-built MoE configs are rejected at EP=2, dense models
and Flux reject EP=2, and only Flux rejects TP=2.

Signed-off-by: bantianyue <[email protected]>
Require every active dense/sparse mesh axis on each layout, detect sparse
MoE regions via MoE.Config (including Dist-MoE), name CP on Kimi block
residual boundaries, and drop the optional parallelism_context guard in
Module._parallelize now that unit tests supply a minimal context.

Signed-off-by: bantianyue <[email protected]>
Address review on pytorch#5995:
- Inline the per-layout axis check (drop three single-use helpers and
  the per-axis message dict); require edp_shard whenever EP is on, as
  the mesh keeps it active.
- Derive the sparse region from MoE.Config traversal
  (<moe>.routed_experts.*) so the MoE check and sparse detection share
  one source; this also replaces has_routed_experts.
- Fix the broken docstring line.
- Remove the Dist-MoE test that always skips in CPU CI; Dist-MoE B200
  and RL integration configs already run this validator.

Signed-off-by: bantianyue <[email protected]>
When expert_parallel_degree == 1, routed-expert weights live on the
dense mesh, so those layouts must name DP/CP/TP like any other dense
layout. Also collect input_shardings/output_shardings after the
ShardingConfig API change that removed implicit redistribution.

Signed-off-by: bantianyue <[email protected]>
@tianyu-l

Copy link
Copy Markdown
Contributor

@bantianyue thanks, please fix remaining claude comments and rebase

@bantianyue
bantianyue force-pushed the cursor/flux-reject-unsupported-tp-ep-994c branch from 82fd9c7 to cca69f8 Compare November 17, 2026 03:58
@bantianyue

Copy link
Copy Markdown
Contributor Author

Rebased onto latest main to resolve the merge conflict (head is now cca69f848). The review fixes are unchanged. @tianyu-l, could you take another look when you have a moment?

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 57s —— View job


Approve -- please address the items before merging: the last open item is fixed, and what's left is a stale PR-description bullet plus an optional test simplification. A maintainer still needs to review, and CI is still running. 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 item below before merging. cca69f8 fixes the last open item (routed-expert layouts are now checked as dense when EP is off), and the rebase onto the new ShardingConfig fields (input_shardings / output_shardings) is correct. This touches core (config/validation.py, models/base/module.py), so a maintainer still needs to review. CI on this head is still running.

What changed since the last review. Layouts under <moe>.routed_experts. count as sparse only when expert_parallel_degree > 1. With EP off they must name DP/CP/TP like any other dense layout, which matches routed_expert_weight_placement(enable_ep=False) -> dense_param_placement. A new unit test covers this. _collect_model_layouts now reads the fields ShardingConfig has on main (state_shardings, input_shardings, output_shardings). The Kimi K3 change has left the diff: main no longer has the layer-0 block_residual layout, so there is nothing left to fix there.

Example.

deepseek_v3 (ep=1), dp_shard=2/tp=2, w13 layout missing TP
    previous head: passes (routed_experts skipped when EP off)
    HEAD:          ValueError "declares no 'tp' sharding"
deepseek_v3 built ep=2, validated ep=2 -> passes (sparse EP/EDP rule)
Dist-MoE: reuses source.sharding_config for the replacement (config/transform/dist_moe.py:68), so the same rule applies

Earlier items

  • Check EP-off routed experts as dense (validation.py:133): resolved.

Must fix

  1. PR description: it still lists torchtitan/models/kimi_k3/sharding.py under "What changed", but after the rebase that file is not in the diff (main removed the layer-0 boundary layout). Drop that bullet so the description matches the code. Also add the new test_ep_off_routed_experts_checked_as_dense to the test list.

Should consider

  • tests/unit_tests/cpu/config/test_config_validation.py:216-236 -- the new test's nested traversal plus flag-and-break can be replaced by patching routed_experts.w13 directly (inline suggestion).

Not verified: the _parallelize guard across the TP/EP integration configs; the fake-pg and GPU jobs on this head are still running.

Comment on lines +216 to +236
from torchtitan.models.base.module import Module
from torchtitan.models.common.moe import MoE

config = deepseek_v3_debugmodel()
patched = False
for _, moe_cfg, _, _ in config.model.traverse(MoE.Config):
for _, rcfg, _, _ in moe_cfg.routed_experts.traverse(
Module.Config, recurse=True
):
sharding = rcfg.sharding_config
if sharding is None or "weight" not in sharding.state_shardings:
continue
sharding.state_shardings["weight"] = spmd.SpmdType(
{MeshAxisName.DP: spmd.R, MeshAxisName.CP: spmd.R},
partition_spec=spmd.PartitionSpec(None, None),
)
patched = True
break
if patched:
break
assert patched

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.

Should consider: the nested traversal, the patched flag and the two breaks are there to find one layout to patch. MoE.Config.routed_experts is typed RoutedExperts.Config with a required w13 field (models/common/moe/moe.py:89,779), and its layout key is "weight" (moe/sharding.py:179). So you can patch that layout directly:

Suggested change
from torchtitan.models.base.module import Module
from torchtitan.models.common.moe import MoE
config = deepseek_v3_debugmodel()
patched = False
for _, moe_cfg, _, _ in config.model.traverse(MoE.Config):
for _, rcfg, _, _ in moe_cfg.routed_experts.traverse(
Module.Config, recurse=True
):
sharding = rcfg.sharding_config
if sharding is None or "weight" not in sharding.state_shardings:
continue
sharding.state_shardings["weight"] = spmd.SpmdType(
{MeshAxisName.DP: spmd.R, MeshAxisName.CP: spmd.R},
partition_spec=spmd.PartitionSpec(None, None),
)
patched = True
break
if patched:
break
assert patched
from torchtitan.distributed.parallelism_context import MeshAxisName
from torchtitan.models.common.moe import MoE
config = deepseek_v3_debugmodel()
_, moe_cfg, _, _ = next(iter(config.model.traverse(MoE.Config)))
sharding = moe_cfg.routed_experts.w13.sharding_config
assert sharding is not None
sharding.state_shardings["weight"] = spmd.SpmdType(
{MeshAxisName.DP: spmd.R, MeshAxisName.CP: spmd.R},
partition_spec=spmd.PartitionSpec(None, None, None),
)

(w13.weight is 3-D, so I gave the spec three entries. The validator only reads the axes either way.)

@tianyu-l

Copy link
Copy Markdown
Contributor

Please fix lint and remaining comments

Address lint failures and remaining review comments on pytorch#5995:
- Import MeshAxisName without a constant alias (N814) and access
  qkv_linear via GQAttention.Config (B009).
- Build the later-MoE-layer divisibility test with EP=8 so layouts
  already declare EP/EDP before the expert-count check.
- Simplify the EP-off routed-experts dense-axis test.

Signed-off-by: bantianyue <[email protected]>
@bantianyue

Copy link
Copy Markdown
Contributor Author

Thanks @tianyu-l — lint and the remaining comments should be addressed in 77b8c75:

  • flake8 N814/B009 and the CPU failure in test_later_moe_layer_not_divisible (that test now builds the MoE debug model with expert_parallel_degree=8, so routed-expert layouts already declare EP/EDP before the expert-count check).
  • PR description: dropped the stale kimi_k3/sharding.py bullet (that file is no longer in the diff after the rebase) and listed test_ep_off_routed_experts_checked_as_dense.
  • Simplified that test to patch routed_experts.w13 directly, as suggested.

Locally, tests/unit_tests/cpu/config/ + test_module.py + test_expert_parallel.py are 269 passed. Please take another look when you have a chance.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 41s —— View job


Approve: both items left open by the last review are fixed, and the new commit adds no new problems. CI on this head still needs to pass. 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 -- 77b8c75 resolves both items left open by the last review, and it adds no new problems. This PR touches core (config/validation.py, models/base/module.py). @tianyu-l has approved it, but CI on this head still needs to pass.

What changed since the last review. The new commit only touches tests and lint:

  • validation.py drops the MeshAxisName as A alias. Behavior is unchanged.
  • test_ep_off_routed_experts_checked_as_dense now patches routed_experts.w13 directly, with a 3-D spec.
  • The partial-TP test narrows to GQAttention.Config with isinstance instead of a constant getattr.
  • test_later_moe_layer_not_divisible now builds the model with expert_parallel_degree=8.

Example.

test_later_moe_layer_not_divisible
  before: model built at EP=1, validated at EP=8
          -> new axis check fires first ("declares no 'ep' sharding"); test fails
  after:  built and validated at EP=8; layers.1 num_experts=63
          -> expected divisibility ValueError

This fix is right, not a workaround. A config built at EP=1 has dense expert placements, so rejecting it at EP=8 is the intended behavior of this PR. The test now isolates the divisibility check.

Earlier items

  • The PR description listed kimi_k3/sharding.py and did not list the new test: resolved. The bullet is dropped and the test is listed.
  • Simplify the EP-off routed-experts test: resolved.

Not verified: I could not see the CI status from this job. The _parallelize guard across the TP/EP integration configs still depends on the fake-pg and GPU runs on this head.

@tianyu-l
tianyu-l merged commit fb1d2ba into pytorch:main Nov 18, 2026
aditvenk added a commit that referenced this pull request Nov 20, 2026
TorchTitan commit fb1d2ba
([config] Reject unsupported TP/EP degrees for FLUX, #5995) broke B200
Integration by adding validation for active mesh axes. The Dist-MoE test
built the DeepSeek V3 recipe with EP off, then enabled EP after the expert
weight layouts had been built. The new check correctly rejected the
missing ep axis. Regular CPU CI skips this test without dist_moe.

Pass EP and PP to the recipe at construction so the expert weights
declare the EP axis. Recipe construction already validates the final
config; assert that accelerator graphs remain enabled.

Test: the targeted Dist-MoE unit test fails on 2377d43 with an
undeclared EP axis and passes with this change.
aditvenk added a commit that referenced this pull request Nov 20, 2026
B200 CI is broken. TorchTitan commit
fb1d2ba ([config] Reject unsupported
TP/EP degrees for FLUX, #5995) exposed latent issue in B200 Integration
test by adding validation for active mesh axes. The Dist-MoE test built
the DeepSeek V3 recipe with EP off, then enabled EP after the expert
weight layouts had been built. The new check correctly rejected the
missing ep axis. Regular CPU CI skips this test without dist_moe.

Pass EP and PP to the recipe at construction so the expert weights
declare the EP axis. Recipe construction already validates the final
config; assert that accelerator graphs remain enabled.

Test: the targeted Dist-MoE unit test fails on 2377d43 with an
undeclared EP axis and passes with this change.
felipemello1 added a commit that referenced this pull request Nov 24, 2026
…outs (#6359)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Agent details

**TLDR:** `Transformers Modeling Backend 8 GPU Integration Tests` has
been red on main since 2026-11-18: 15 of 15 completed runs. Its MoE test
(`fsdp+tp+ep+cp`) fails at config load with `HFTransformerModel.Config
has no routed experts; set parallelism.expert_parallel_degree to 1 (got
2).` It broke with #5995 ("[config] Reject unsupported TP/EP degrees for
FLUX"). @bantianyue, could you please take a look? This PR skips the
parallel-axes check when a model config declares no sharding layouts.
Native TorchTitan models all declare layouts, so their checks don't
change. A dense transformers-backend model with EP > 1 now gets a clear
error at parallelize time.

![On main the parallel-axes check stops every transformers-backend run
at EP 2 at config load; with this PR configs with 0 layouts skip it, so
the CI MoE recipe trains (loss 12.41, then 7.31, on 4 GB300s), a dense
flavor at EP 2 fails at parallelize, and native models are still
checked.](https://raw.githubusercontent.com/felipemello1/pr_images/984e0f211a7b5734845f05c41c08f0817519ea39/torchtitan/6359/lanes.png)
<!-- pr-image drawn at 0f17083 -->

```python
# torchtitan/config/validation.py, _validate_declared_parallel_axes
layouts = _collect_model_layouts(model)
if not layouts:
    return
```

**Problem**
1. `_validate_declared_parallel_axes` checks the sharding layouts that
the model config declares. It finds the routed experts by looking for
`MoE.Config` in the config tree.
2. When EP > 1 and the tree has no `MoE.Config`, it raises "has no
routed experts". Commit fb1d2ba ("Reject unsupported TP/EP degrees for
FLUX") added this.
3. The transformers backend builds its MoE and its layouts later, in
`parallelize_hf_transformers` (`build_and_swap_native_moe`, then
`set_hf_sharding_configs`). When the check runs, its config declares 0
layouts and has no `MoE.Config`.
4. So every transformers-backend MoE run with EP > 1 fails at config
load. The workflow runs only when
`torchtitan/experiments/transformers_modeling_backend/**` changes. So
the commit that added the check never ran it. The 12-hour schedule
caught it.

**Solution**
1. Return early when the config declares no layouts. Nothing is declared
yet, so nothing can be checked.
2. Native models don't change. Layouts each one declares with every
degree at 1 (`_collect_model_layouts` on each `debugmodel`): Flux 32,
Llama3 195, DeepSeek-V3 311, Qwen3.5 379, Kimi K3 1406, Kimi K3.1 1416.
All 15 models in `torchtitan/models` have at least 32. The
transformers-backend MoE and dense debug configs have 0.
3. New CPU test `test_hf_moe_config_accepts_ep_gt1`. It builds the
transformers-backend MoE debug config from a local `Qwen3MoeConfig` (no
network) and validates it at EP = 2. It runs in `CPU Unit Test`, so the
next change to `validation.py` gets checked against this case.
4. `parallelize_hf_transformers` raises when `expert_parallel_degree >
1` and the flavor is dense (`config.is_moe` is False). Only MoE flavors
build Titan MoE, so EP would go unused. It reads the config, not
`model.layers`: under PP each stage keeps only its own layers, but a
full copy of the config.

**Results**
```
CI recipe transformers_backend_moe_fsdp_tp_ep_cp, 2 steps
  main:     ValueError at config load (ConfigLoader re-runs __post_init__)
  this PR:  4x GB300, mesh pp=1 dp_shard=1 cp=2 tp=2 ep=2
            step 1 loss 12.41, step 2 loss 7.31, "Training completed"
Dense debug recipe, expert_parallel_degree = 2, 2x GB300
  main:     ValueError at config load: "has no routed experts" (the core check above)
  this PR:  ValueError at parallelize: "parallelism.expert_parallel_degree > 1 needs an MoE
            flavor (TitanMoeModelConfig), got 2 for a dense model."
```

You may ask:
- Why change core and not the experiment? The check is in core. The
experiment builds its MoE config at parallelize time on purpose, once EP
and sequence parallelism are known (`moe_replacement.py`).
- Why is the test in core? It guards a core function. The experiment's
own unit tests run in no CI workflow.
- Why not add `torchtitan/config/**` to the workflow's path filter? Many
core files can break this backend. A CPU test on every PR is cheaper
than an 8-GPU job.

NOTE: The GPU run above used 4 GB300s and transformers 5.23. CI uses 8
A10Gs (dp_shard = 2) and transformers 5.9.0. CI runs the 8-GPU workflow
on this PR only once it is out of draft.
NOTE: fegin's open draft "[dist_moe] Keep the output postprocess weights
on the dense FSDP mesh" edits the same lines of
`_validate_declared_parallel_axes`. It adds the same `layouts =
_collect_model_layouts(model)` line, so whichever lands second needs a
small rebase.
NOTE: Two red checks here come from main. `CPU Unit Test` shows the
profiler-close test's 3 failures until its fix lands. `lint` fails on a
pyrefly error in `torchtitan/models/kimi_k3/dsa.py` until the Kimi K3.1
FLOPs fix lands.

**Test plan**
```
pytest tests/unit_tests/cpu/config/test_config_validation.py -k test_hf_moe_config_accepts_ep_gt1
  main:    1 failed (the ValueError above)
  this PR: 1 passed (also with HF_HUB_OFFLINE=1)
pytest tests/unit_tests/cpu/config/ tests/unit_tests/cpu/models/base/test_module.py \
  tests/unit_tests/cpu/distributed/test_expert_parallel.py: 279 passed
NGPU=4 MODULE=torchtitan_recipes.tests.transformers_modeling_backend \
  CONFIG=transformers_backend_moe_fsdp_tp_ep_cp ./run_train.sh --output-dir <dir>
NGPU=2, dense debug recipe with data_parallel_shard_degree = -1, expert_parallel_degree = 2:
  the ValueError above, raised in parallelize_hf_transformers
```
pre-commit run --files <changed files> (SKIP=pyrefly-check): all hooks
pass. pyrefly check torchtitan/config/validation.py: 0 errors.
Full core CPU suite (`pytest tests/unit_tests/cpu`) on main 34ac322 +
both CI fixes, local CPU: 2099 passed, 7 failed. The same 7 also fail on
plain main in this local venv (older torch nightly, no torchao). CI at
34ac322 passed 5 of them and skips the other 2's file.

---------

Co-authored-by: Felipe Mello <[email protected]>
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 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.

FLUX: tensor_parallel_degree / expert_parallel_degree > 1 are silently ignored and fail later as OOM

2 participants