Repository navigation
[config] Reject unsupported TP/EP degrees for FLUX - #5995
Conversation
|
|
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]>
|
Hi @tianyu-l, reworked per your feedback in #5855 — the flag approach is gone:
Local verification: the four config test files pass (65 tests incl. 9/9 in 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! |
| if ( | ||
| parallelism.tensor_parallel_degree > 1 | ||
| and MeshAxisName.TP not in _declared_spmd_axes(model) | ||
| ): |
There was a problem hiding this comment.
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
|
@claude review |
There was a problem hiding this comment.
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 outTPis 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 > 1each of them must nameTP, and whencp > 1each must nameCP. Routed-expert weight layouts (w13/w2underRoutedExperts.Config) must nameEPwhenep > 1. Ifep > 1and 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_configare still a gap. Flux'sLinears have none; only its inner attention declares layouts._parallelizesilentlyreturns 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: whentp > 1orep > 1, raise in_parallelizeif a module owns parameters but has nosharding_config. This still runs on the meta device, before any memory is allocated.
Must fix
validation.py:85-88-- rewrite the TP check per layout, as above (@tianyu-l).validation.py:95-- the EP check looks for MoE layers, not for EP-sharded expert weights. Details inline.test_tp_kv_heads_validation.py:41-- imports the private_flux_debug, inside atry/exceptguard that can turn a broken import into a silent skip. Details inline.
Should consider
validation.py:81-84-- the_owner is Nonefallback can never run.flux/model.py:109-- reject PP > 1 inFluxTrainer.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 omitTP? 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.
| 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)): |
There was a problem hiding this comment.
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.
| model_cls = type(model)._owner | ||
| model_name = ( | ||
| model_cls.__name__ if model_cls is not None else type(model).__qualname__ | ||
| ) |
There was a problem hiding this comment.
_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 |
There was a problem hiding this comment.
There are two problems with this import:
- It imports the private
_flux_debugfrom another module. Use the public builder instead:build_model_config("flux-debug", parallelism=parallelism)fromtorchtitan.models.flux. Pass it the sameParallelismConfigyou validate against, so the test doesn't build the config at TP/EP = 1 and then validate it at 2. - It sits inside the file's broad
try/except Exception->_IMPORTS_OK = Falseguard. 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.") |
There was a problem hiding this comment.
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.
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]>
|
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 |
| 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. |
There was a problem hiding this comment.
Hmm, maybe it was working, but can we make every axis explicit, including DP, CP, EDP?
|
@claude review again |
There was a problem hiding this comment.
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_debugimport inside the import guard: resolved. _ownerfallback, Flux PP rejected at config time: resolved.
Must fix
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_residuallayout (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.
validation.py:115-- the sparse region is found withtraverse(RoutedExperts.Config). AfterDistMoeTransformnoRoutedExperts.Configremains, so the verified 671B Dist-MoE recipes and the muse_spark Dist-MoE recipes fail validation. Use theMoE.Config.routed_expertsslot instead (inline).validation.py:140-143-- the EP block silently skips an expert weight with nosharding_config, and itsNoneguards protect required fields. Fold it into the single per-layout loop (inline).
Should consider
module.py:380-- theparallelism_context is not Nonebranch exists only for_parallelize(None)calls in tests. Fix the tests, not the production code (inline).
Questions
- The 13-model sweep covers the
debugmodelflavors only. Did it apply any config transforms? Please extend it to the Dist-MoE recipes (deepseek_v3_671b_dist_moe_*, themuse_sparkDist-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.
| ep = parallelism.expert_parallel_degree | ||
|
|
||
| # The routed-expert (sparse) region lives under RoutedExperts.Config. | ||
| sparse_prefixes = [fqn for fqn, _, _, _ in model.traverse(RoutedExperts.Config)] |
There was a problem hiding this comment.
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 themuse_sparkDist-MoE recipes (EP=16/32/64) fail with "has no routed experts".muse_sparkwith TP=4/8 + Dist-MoE also fails the TP loop, because itsw13/w2expert 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.
| 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: |
There was a problem hiding this comment.
This second traversal duplicates _collect_model_layouts and has two problems:
w13/w2are required fields onRoutedExperts.Config, sogetattr(..., None)andsub_cfg is Noneguard against a case that can't happen.sharding_config is None: continuesilently 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.
| # protocol check above; without mesh info there is nothing to | ||
| # enforce here. | ||
| if ( | ||
| parallelism_context is not None |
There was a problem hiding this comment.
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.
6043d0f to
c73583d
Compare
|
Hi @tianyu-l, the third-round review comments are addressed in c73583d:
Could you take another look when you have a chance? Thanks! |
|
@claude review |
There was a problem hiding this comment.
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_residualis built fromh_TD(kimi_k3/model.py:457), soCP: Vwith(DP, CP[, TP])is the accurate type and matches the decoder convention. - Dist-MoE detection: resolved.
_is_sparsenow matches therouted_expertsslot instead of theRoutedExperts.Configtype. - Separate EP walk with
Noneguards: resolved (folded into one loop). _parallelize(None)branch: resolved. The tests now pass a real context.
Must fix
validation.py:186-218-- three single-use helpers, a per-iteration message dict, and EDP arithmetic that re-derivesdp_shard*cp*tp//epand doesn't matchParallelismContext._axis_is_active(edp_shard stays active wheneverep > 1). Inline sketch, about 100 fewer lines.test_config_validation.py:187-- the Dist-MoE test always skips in CI (dist_moeisn't installed in the CPU job), and the B200 and RL Dist-MoE integration configs already run this validator. Delete it.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_hybridepalready builds withexpert_parallel_degree=2(torchtitan_recipes/tests/models/deepseek_v3.py:160), so the removed post-build mutation was redundant. - The
_parallelizeguard 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.
| 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}" | ||
| ) |
There was a problem hiding this comment.
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.
| 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, |
There was a problem hiding this comment.
A bad edit left a run of spaces mid-sentence, and the line is now over the docstring width.
| 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, |
| 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__() |
There was a problem hiding this comment.
In CI this test always skips, and the path it targets is already covered elsewhere.
unit_test_cpu.yamlrunstests/unit_tests/cpuwithout installingdist_moe, soimportorskipalways skips it there. The only job that installsdist_moe(integration_test_b200.yaml:83-85) runstests/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 RLrl_grpo_moe_debug_dist_moe_tp2_ep4(TP=2, EP=4), and those jobs do installdist_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
left a comment
There was a problem hiding this comment.
please address comments from me and claude
| model_name = type(model).__qualname__ | ||
| ep = parallelism.expert_parallel_degree | ||
|
|
||
| has_routed_experts = any(True for _ in model.traverse(MoE.Config)) |
There was a problem hiding this comment.
should search for RoutedExperts or DistMoeRoutedExperts; o/w should rename to has_moe
There was a problem hiding this comment.
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.
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]>
|
@claude review again |
There was a problem hiding this comment.
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_SHARDis now required wheneverep > 1, which matchesParallelismContext._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_expertsor search for the expert types: resolved. The flag is gone, and the region comes from theMoE.Config.routed_expertsslot, soDistMoeRoutedExpertsis covered.
Should consider
torchtitan/config/validation.py:133-- with EP == 1, nothing underrouted_expertsis 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.
| if fqn.startswith(sparse_prefixes): | ||
| required = sparse_required |
There was a problem hiding this comment.
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):
| 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]>
|
@bantianyue thanks, please fix remaining claude comments and rebase |
82fd9c7 to
cca69f8
Compare
|
Rebased onto latest |
|
@claude review again |
There was a problem hiding this comment.
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
- PR description: it still lists
torchtitan/models/kimi_k3/sharding.pyunder "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 newtest_ep_off_routed_experts_checked_as_denseto 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 patchingrouted_experts.w13directly (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.
| 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 |
There was a problem hiding this comment.
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:
| 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.)
|
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]>
|
Thanks @tianyu-l — lint and the remaining comments should be addressed in 77b8c75:
Locally, |
|
@claude review again |
There was a problem hiding this comment.
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.pydrops theMeshAxisName as Aalias. Behavior is unchanged.test_ep_off_routed_experts_checked_as_densenow patchesrouted_experts.w13directly, with a 3-D spec.- The partial-TP test narrows to
GQAttention.Configwithisinstanceinstead of a constantgetattr. test_later_moe_layer_not_divisiblenow builds the model withexpert_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.pyand 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.
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.
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.
…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.  <!-- 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]>
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 aValueErrorfromvalidate_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:dpplacement counts as declaring the DP storage axes.<moe>.routed_expertsslot found by traversingMoE.Config, so Dist-MoE replacements ofRoutedExpertsare covered too. Withexpert_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 noMoE.Configis rejected. A config built withexpert_parallel_degree == 1gets dense expert weight placements, so validating it at EP > 1 fails here instead of silently ignoring the degree at runtime.routed_expertscontainer 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 nosharding_config(they would be silently replicated). Buffers alone do not trip this: MoE load-balance losses own only per-rank statistics buffers. The previousparallelism_context is not Noneguard is gone; unit tests now pass a minimal context.torchtitan/models/flux/model.py:pipeline()raisesNotImplementedError(backstop).torchtitan/models/flux/trainer.py:FluxTrainer.Config.__post_init__rejectspipeline_parallel_degree > 1with aValueErrorat config time.torchtitan/models/base/model.py: removed thesupports_tensor_parallelandsupports_pipeline_parallelflags and the flag check inpipeline().test_tp_kv_heads_validation.pynow use the publicbuild_model_config("flux-debug", parallelism=...)(moved to module top level, outside the import guard); the accelerator-graphs EP tests intest_config_validation.pyrebuild withbuild_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);_parallelizeprotocol tests pass a minimalParallelismContext.test_later_moe_layer_not_divisiblenow builds the model with EP=8 so layouts already declare EP/EDP before the expert-count check.Notes for reviewers
_cast_fp_tensor) is a separate bug and is intentionally not addressed here.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, includingtest_ep_off_routed_experts_checked_as_dense(the always-skipped Dist-MoE case was removed per review).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 oftest_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.pysupplies a realParallelismContextto the_parallelizeprotocol tests.MeshAxisName as Aalias and the constantgetattr; ufmt is unchanged on the new/edited hunks.Fixes #5854.