Skip to content

[CI] Build the B200 Dist-MoE test with EP and PP enabled - #6263

Merged
aditvenk merged 1 commit into
mainfrom
avenkataraman/fix-b200-dist-moe-ep-pp-main
Nov 20, 2026
Merged

aditvenk merged 1 commit into
mainfrom
avenkataraman/fix-b200-dist-moe-ep-pp-main

Conversation

@aditvenk

Copy link
Copy Markdown
Contributor

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.

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.
@pytorch-bot pytorch-bot Bot added ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests labels Nov 20, 2026
@aditvenk

Copy link
Copy Markdown
Contributor Author

@claude

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 20, 2026
@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @aditvenk's task in 1m 36s —— View job


Approve: the test now gets EP/PP when the recipe is built, so the expert weights declare the ep axis. One open question on the kimi_k3 B200 entries. 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 -- a test-only fix that builds the config with its final parallelism instead of editing it afterwards. This is the root-cause fix the new axis validation calls for.

What this PR does. test_eager_dist_moe_recipe_supports_accelerator_graphs_with_pipeline_parallelism used to build the Dist-MoE recipe with EP=1, then set EP=2/PP=2 and re-run __post_init__(). Since fb1d2ba (#5995), _validate_declared_parallel_axes rejects that, because the expert weights were built with dense placements and declare no ep axis. The PR passes the ParallelismConfig into the recipe, so build_model_config produces EP-aware layouts. apply_transforms already runs Trainer.Config.__post_init__() (torchtitan/config/transform/apply.py:124), so the explicit call is no longer needed.

Example.

# before: layouts built for EP=1, degree flipped afterwards
config = deepseek_v3_debugmodel_dist_moe_bf16(seq_len=128)
config.parallelism.expert_parallel_degree = 2
config.__post_init__()   # ValueError: routed_experts layout does not name ep
# after: layouts built for EP=2/PP=2, validated inside apply_transforms
config = deepseek_v3_debugmodel_dist_moe_bf16(seq_len=128, parallelism=ParallelismConfig(
    expert_parallel_degree=2, pipeline_parallel_degree=2,
    pipeline_parallel_schedule="Interleaved1F1B"))

Questions

  • tests/integration_tests/b200.py:28-56: kimi_k3_debugmodel_mm and kimi_k3_debugmodel_mm_muon also build with default DP/TP, then set data_parallel_shard_degree = 2 / tensor_parallel_degree = 2 afterwards. torchtitan/config/loader.py:56 re-runs __post_init__() on the result, so the same dense-axis check applies there. If a TP=1 build leaves out the tp/dp_shard axes, these entries break the same way. The B200 Integration run on this PR will show whether they do. If so, pass the full ParallelismConfig at construction there too. Unverified: I didn't check whether TP=1 kimi_k3 layouts still name tp.

Not verified: B200 run (still queued when I reviewed). On CPU, accelerator_graphs_supported() is false, so the EP dispatcher graph check in validation.py:217 only runs on B200.

@aditvenk

Copy link
Copy Markdown
Contributor Author

Looks like there is a second issue in b200 integration tests (more recent issue):

_____ ERROR collecting tests/unit_tests/gpu/models/kimi_k3/test_kimi_k3.py _____
ImportError while importing test module '/__w/torchtitan/torchtitan/tests/unit_tests/gpu/models/kimi_k3/test_kimi_k3.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/github/home/.local/share/uv/python/cpython-3.12.16-linux-x86_64-gnu/lib/python3.12/importlib/__init__.py:90: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests/unit_tests/gpu/models/kimi_k3/test_kimi_k3.py:26: in <module>
    from torchtitan_recipes.tests.models.kimi_k3 import _dist_muon_optimizer
torchtitan_recipes/tests/__init__.py:17: in <module>
    from torchtitan.trainer import Trainer
torchtitan/trainer.py:28: in <module>
    from torchtitan.components.validator import BaseValidator, Validator
torchtitan/components/validator.py:22: in <module>
    from torchtitan.components.data.text_datasets import DATASETS
torchtitan/components/data/text_datasets.py:13: in <module>
    from renderers import build_training_sample, Message, Renderer, ToolSpec
.venv/lib/python3.12/site-packages/renderers/__init__.py:45: in <module>
    from renderers.client import MalformedGenerateResponseError, OverlongPromptError
.venv/lib/python3.12/site-packages/renderers/client.py:16: in <module>
    import httpx
E   ModuleNotFoundError: No module named 'httpx'

Merging this PR, follow up fix coming

@aditvenk
aditvenk merged commit 078bdc6 into main Nov 20, 2026
21 of 23 checks passed
shuhuayu added a commit that referenced this pull request Nov 21, 2026
#6053)

## Summary (human-written)

add recipe with kernel overrides

## Why

Stacked on #6052 (3/n).

After 2/n (static QSA) and 3/n (fixed-capacity PLE routing), Flash-Next
forward/backward has no host synchronization and no batch-dependent
shapes when expert dispatch is CPU-free, so a step can be captured and
replayed as one accelerator graph. Nothing guards that: a later change
that adds a `.tolist()` or a data-dependent shape would only show up
when someone turns graphs on. There is also no recipe for the released
125B-A6B model.

**Example.** On the debug model with FSDP2 + EP2 and Dist-MoE, step 3
captures forward/backward and step 4 replays it with a different
document layout. A host sync fails capture (before 2/n:
`cudaErrorStreamCaptureUnsupported` at `valid_T.nonzero()`). Metadata
passed into the graph but not registered as a pytree fails graph input
validation at step 4. Replay reading stale state that is not a graph
input is not caught until the test has a golden (see Known issues).

## What changed

**Recipe and flavor**
- `qwen38_flash_next_125b_dist_moe` in
`torchtitan_recipes/models/qwen3_8_flash_next.py` fine-tunes the
released decoder from its HF checkpoint on 16 GB300s:
- FSDP16 + EP16 (all 512 experts, 32 per rank, in one NVLink domain)
with Dist-MoE, and PLE rows over DP16.
- 2M tokens per step: 8 packed 16K-token microbatches per rank
(documents split at the model's 4K context). This is the per-GPU work of
a 33.5M-token step on 256 GPUs.
- Full remat, the model's `local_compile` regions, and forward/backward
as one accelerator graph.
- `max_num_documents=64`, because graph replay needs a fixed document
capacity (twice `c4_document_capacity`'s 16K estimate).
- Dist-MoE activation slot 0.5: about the first half of the MoE layers
keep their expert intermediates instead of recomputing them (decided per
layer on device), +2.9% throughput for ~45 GiB. Factor 1.0 (~94 GiB)
reached 264 GiB and thrashed the allocator. Saving whole GDN blocks from
remat bought ~1% for 31.6 GiB and is not used.
- Two overrides, below: the fused gated residual read and the fused QSA
indexer teacher. The indexer KL coefficient is 1.0; the comment explains
it only matters through global gradient clipping.
- 30 steps at a small learning rate, for throughput measurement; a real
run sets `training.steps` and the schedule.
- `125B-A6B-text` flavor: the released decoder without the vision
encoder, loaded from the multimodal checkpoint. With `125B-A6B`, the
encoder runs a dummy forward on text batches every step for no training
signal.

**Fused gated residual read (opt-in override, enabled by this recipe)**

Every sublayer reads its four residual streams through `GatedResidual`,
97 calls per forward. Two parts were slow at 125B shapes (T = 16K, C = 4
x 2560, rank 320):
- `hc_norm`'s compiled backward fuses the input gradient into the
weight-gradient sum over tokens, a column-major loop over 16K rows (0.73
ms per call).
- `inject`'s `[10240 -> 4]` GEMM is too narrow for a fast kernel (sm80
CUTLASS), and `down` and `inject` each produce an `x_norm` gradient that
autograd adds.

```text
x_TC -> hc_norm -> x_norm -+-> down   [10240 -> 320]  -> mix = silu(down / 4) -> up -> read -> mixed
                           +-> inject [10240 -> 4]    -> write = 2 sigmoid(inject / 4)
                           +-> read

module:   hc_norm (compiled) + separate down / inject GEMMs     2.56 ms  (one call, fwd+bwd, graph replay)
override: hc_norm (Triton)   + one [down | inject] GEMM          1.52 ms
```

- `torchtitan_recipes/overrides/flash_next_grouped_rms_norm.py`:
`GroupedOffsetRMSNorm` as Triton kernels with a hand-written backward
(input gradient row by row; weight gradient as per-chunk partials summed
afterwards, deterministic). Wrapped as a `torch.library.custom_op` with
fake and autograd registrations so it traces and graph-captures.
- `torchtitan_recipes/overrides/flash_next_gated_residual.py`:
`FusedGatedResidual`, `@override(target=GatedResidual.Config)`. `down`
and `inject` run as one `F.linear` over their concatenated weights,
padded to a 16-row multiple (324 -> 336) for cuBLAS. `up` and the stream
read are unchanged. Parameters and checkpoint keys are unchanged. Config
validation rejects a `Linear` subclass, a bias, or an `hc_norm` other
than a plain `GroupedOffsetRMSNorm`, since `forward` reads their weights
directly.

**Fused QSA indexer teacher (opt-in override, enabled by this recipe)**

The indexer's KL target is the head-mean softmax over each query's
selected tokens, max-pooled per block. The model's
`QSAInnerAttention._teacher` gathers a `[Q, J, H_kv, K]` key copy,
writes fp32 logits and runs a separate softmax: 18.8 ms per layer per
microbatch at 125B shapes (16K tokens, J = 2051). `gather_attn` already
computes the softmax normalizer, so each token's probability `exp(S -
lse_h)` does not depend on the rest of the selection.

```text
per 64-query tile, per 128-key tile of its window:
    S = scale * Q_h @ K_g^T               # per head h, KV head g = h // group
    sums += exp(S - lse_h)                # head sum, fp32
teacher[q, b] = max over block b's tokens of sums[q, token] / H   -> [T, B]
```

- `torchtitan_recipes/overrides/flash_next_qsa_teacher.py`:
`FusedTeacherQSAInnerAttention` asks `gather_attn` for the log-sum-exp
and runs one Triton kernel densely per 64-query tile against the context
window before it (tensor-core GEMMs, skipping key tiles before the
tile's first selected token), then gathers and max-pools the selected
blocks: 1.4-2.2 ms depending on document lengths. The override targets
`QSAAttention.Config` (not the inner attention) to read the indexer's
RoPE context, which bounds each tile's window. Same parameters (none)
and attention output; only the KL target is computed differently. Its
`forward` mirrors `QSAInnerAttention.forward` except for the LSE request
and the teacher call. A TODO notes the teacher is generic to sparse
attention with an indexer teacher and belongs in Attention Gym.

Reviewers can read the three override files separately from the recipe.

**GDN in_proj split (model code, every flavor)**

Flash-Next's GDN `in_proj` is a `SplitLinear` (q|k|v projection GEMM,
z|a|b gates GEMM). `SplitLinear` interleaves the two outputs per key
head into the single-`Linear` layout only for the shared `GDN` to split
them again:

```text
projection  [q0 k0 v0 | q1 k1 v1]
gates       [z0 a0 b0 | z1 a1 b1]
SplitLinear [q0 k0 v0 z0 a0 b0 | q1 k1 v1 z1 a1 b1]    <- copy skipped
GDN split   mixed_qkv [q0 q1 | k0 k1 | v0 v1], z, a, b
```

- `torchtitan/models/qwen3_8_flash_next/gdn.py`: `SplitInProjGDN`, a
`GDN` subclass in the model folder, builds `mixed_qkv`, `a`, `b` and the
gate straight from the two GEMM outputs (in a `gdn_split_in_proj`
local-compile region). This removes a ~540 MB copy and its backward
split per layer call. The shared `GDN` is unchanged.
- `flavors.py` builds Flash-Next's linear-attention layers as
`SplitInProjGDN.Config` via `derive`; same parameters, so HF checkpoint
loading is unchanged.

**Graph test**
- B200 integration test
`qwen3_8_flash_next_dist_moe_fsdp_ep_accelerator_graph`: FSDP2 + EP2
with row-sharded PLE, Dist-MoE and full remat; step 3 captures, step 4
replays. Replay uses a new document layout, so the test fails on any
host synchronization or batch-dependent shape. It has no golden loss
file yet (see Known issues). SPMD typechecking is off, with a TODO,
because Dist-MoE does not register its autograd functions with it;
`qwen3_8_flash_next_fsdp` typechecks the model with the default
dispatcher. The test's debug config enables neither override.
- A text-only `qwen38_flash_next_debugmodel` test config
(`torchtitan_recipes/tests/models/qwen3_8_flash_next.py`) backs the
graph test.
- The B200 workflow's pytest list adds the QSA teacher override's GPU
test.

**Mechanical (skim)**
- `gdn.py`: the split helpers are private static methods of
`SplitInProjGDN`.
- Model README: the 125B recipe (416 TFLOP/s per GPU, 16.7% MFU, under
forced round-robin routing), Dist-MoE under EP, and the graph test.

No library code changes outside the model folder, `torchtitan_recipes/`,
the tests, and the one-line registration.

## Alternatives considered

- **HybridEP instead of Dist-MoE.** Blocking HybridEP has per-layer host
syncs, so it can't run under graphs. Non-blocking HybridEP pads expert
buffers to capacity factor 1.0 (every token to every local expert) and
was 1.5x slower than eager.
- **Compile the whole `GatedResidual.forward` as one region.** The
forward got 0.43 ms faster, but Inductor's backward got 0.42 ms slower,
for the same column-loop reason.
- **Fully fused residual kernels** (norm folded into per-stream
projection GEMMs, `up` with a Triton read epilogue, custom backward):
316.7 TFLOPS against 321.3 (measured at an earlier revision), in about
560 lines.
- **Change `GatedResidual` itself.** That changes eager numerics and
goldens for every Flash-Next config; as an override it stays opt-in.
- **QSA teacher with one query per program** (selected keys gathered per
query): 4.3 ms per layer per microbatch, against 1.4-2.2 ms dense.
- **Change the shared `GDN` or `SplitLinear`.** Only Flash-Next uses the
split `in_proj`; a subclass in the model folder keeps shared code
untouched.

## User-facing changes

| Before | After |
| --- | --- |
| No released-model recipe | `qwen38_flash_next_125b_dist_moe` (16
GB300s, 2M tokens per step, Dist-MoE + graphs) |
| Only `125B-A6B` (with vision encoder) | Adds `125B-A6B-text` |
| No Flash-Next overrides |
`torchtitan_recipes.overrides.flash_next_gated_residual.fused_gated_residual`
(and `...flash_next_grouped_rms_norm.fused_grouped_offset_rms_norm` for
the norm alone),
`torchtitan_recipes.overrides.flash_next_qsa_teacher.fused_qsa_teacher`
|
| Flash-Next GDN layers are `GDN` | `SplitInProjGDN` (same parameters
and checkpoint keys, bitwise-identical numerics) |
| Flash-Next graph capture/replay untested | B200 FSDP2 + EP2 Dist-MoE
graph test (capture and replay; golden to follow) |

## Performance

125B-A6B, 16 GB300s, FSDP16 + EP16, Dist-MoE + graphs, full remat, 2M
tokens per step, activation slot 0.5, HF checkpoint. Mean over steps
4-30, peak memory max over ranks.

Current stack (with 1/n's shared fp32 router and PLE table on
`spmd_dense_mesh`):

| Routing | TFLOPS / GPU | Peak memory |
| --- | ---: | ---: |
| Natural | **378.6-379.0** | 243.59 GiB |
| Forced round-robin | 416.4 | 243.89 GiB |

Per-optimization deltas (measured at an earlier revision, before 1/n's
router change; torch nightly 20261118):

| Step | Natural routing | Round-robin |
| --- | ---: | ---: |
| Fused gated residual read | 304.8 -> 321.3 | |
| Fused QSA teacher (after 1/n's indexer window) | 335.1 -> 369.4 | |
| GDN in_proj split | 369.4 -> 378.5 | 406.0 -> 418.2 |
| Final (at that revision) | 378.5 (15.14% MFU), 243.4 GiB | 418.2
(16.73% MFU), 243.8 GiB |

The GDN split left peak memory unchanged. For reference, the earlier
eager blocking-HybridEP recipe ran at 168.3 TFLOPS (6.73% MFU) with one
16K microbatch per step.

## Numerics

- Graph replay runs the same kernels as eager. On two GB300s with FSDP2
+ EP2 and Dist-MoE, graphs and eager matched bitwise in loss and
gradient norm over 4 steps, (measured at an earlier revision, before the
GDN split moved into model code and the 1/n router switch).
- The GDN split is bitwise: a GPU unit test compares outputs and all
gradients against the shared `GDN` (eager and compiled region), and the
debug model's loss, grad_norm and indexer loss matched the shared `GDN`
bitwise over 10 steps (seed 42, deterministic).
- The gated residual override is not bitwise: the merged GEMM and the
Triton norm change summation order. Its output and every gradient stay
at or below the eager module's error against an fp64 golden (measured at
an earlier revision):

| Tensor (T = 16K, bf16, rel. L2 vs fp64) | Eager module | Override |
| --- | ---: | ---: |
| mixed / write | 3.38e-3 / 1.80e-3 | 3.38e-3 / 1.80e-3 |
| d x | 3.76e-3 | 3.38e-3 |
| d hc_norm.weight / d Wd / d Wu / d Wi | 3.74e-3 / 5.07e-3 / 5.11e-3 /
4.18e-3 | 3.37e-3 / 5.07e-3 / 5.11e-3 / 3.84e-3 |

125B loss at step 30 tracked the run without it: 2.27436 vs 2.27435
(earlier revision).
- The QSA teacher override is not bitwise: relative error against an
fp64 golden 1.52e-7 vs 1.21e-7 for the model's teacher. 125B loss at
step 30: 2.27438 vs 2.27436 (earlier revision).
- Current stack, 125B natural routing: loss 2.34428-2.34429 at step 1
and 2.27433-2.27437 at step 30. The 125B recipe is not run-to-run
bitwise (~1e-4 in loss, up to 5e-3 in grad_norm between runs of the same
math); the debug configs are.
- Goldens are unaffected by the overrides because no golden config
enables them.

## Testing

```bash
python -m tests.integration_tests.run_tests outputs/flash_next_b200 \
  --test_suite b200 --execution_mode real_pg --ngpu 2 \
  --test_name qwen3_8_flash_next_dist_moe_fsdp_ep_accelerator_graph
pytest tests/unit_tests/gpu/recipes/test_flash_next_gated_residual_override.py \
  tests/unit_tests/gpu/recipes/test_flash_next_qsa_teacher_override.py \
  tests/unit_tests/gpu/models/qwen3_8_flash_next/test_gdn.py
```

- The graph test passed, along with the other Flash-Next B200 tests and
the CPU tests, before the GDN split moved into model code; it has not
been rerun on B200 since.
- `test_flash_next_gated_residual_override.py` (new) bounds the
override's error against an fp64 golden by 2x the eager module's error
(plus the dtype's rounding floor): output and all gradients, with and
without `inject`, at 256 and 257 tokens; a second case covers the norm
alone with leading dims and a non-power-of-two group size. It catches a
wrong hand-written backward or a broken `[down | inject]` split.
- `test_flash_next_qsa_teacher_override.py` (new, SM100; added to the
B200 workflow's pytest list, since the A10G GPU job skips it) bounds the
fused teacher's error against an fp64 golden by 2x the model teacher's
error, over mixed document lengths that straddle the 64-query tiles, and
checks that padding rows (no selected tokens) get zeros.
- `test_gdn.py` (new) compares `SplitInProjGDN` against the shared `GDN`
bitwise (outputs and all gradients), eager and with the
`gdn_split_in_proj` region compiled. It catches a q/k/v or z/a/b slice
that disagrees with the shared split, e.g. after a `SplitLinear`
head-layout change.
- The recipe ran for 30 steps on 16 GB300s at the current stack (numbers
above). Loading the 125B HF checkpoint still works (~320-345 s).

## Known issues / follow-ups

- The graph test has no golden loss file yet. A golden checked bitwise
against the same config run eagerly would also catch replay reusing
stale state; until now the B200 lane stopped at its pytest step on main
(`test_dist_moe.py::test_eager_dist_moe_recipe_supports_accelerator_graphs_with_pipeline_parallelism`),
so no integration test ran to produce it. #6263 fixed that test on
2026-11-20; the golden follows once the lane runs again. TODO in the
test. The earlier golden was removed because 1/n's router switch changed
this test's numerics.
- The stack is rebased onto main, which already registers
`LinearAttentionMetadata` as a pytree dataclass (#5680), so this PR no
longer carries that change.
- The gated residual override expects bias-free plain `Linear`
projections and raises otherwise.
- TP/SP layouts are not exercised with the overrides; the 125B recipe
does not use TP. 5/n (#6054) adds the QSA teacher override's TP path
with the model's.
- The QSA teacher kernel belongs in Attention Gym next to `gather_attn`
(TODO in the code).

## Stack

1. #6046: Flash-Next model, DTensor PLE, FSDP/EP, optimizer policy, QSA
indexer performance.
2. #6047: static-shape QSA metadata and selection.
3. #6052: fixed-capacity PLE row-sharded routing.
4. **This PR (#6053)**: the released 125B-A6B recipe, fused gated
residual and QSA teacher overrides, the GDN in_proj split, and an
accelerator-graph test.
5. #6054: tensor/sequence parallelism.
6. #6055: pipeline parallelism.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI 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.

2 participants