Skip to content

[DeepSeek V3] Fuse general-shape router forward and backward - #5551

Open
sanketpurandare wants to merge 1 commit into
dsv3-shared-expert-streamfrom
dsv3-fused-router-mlperf
Open

sanketpurandare wants to merge 1 commit into
dsv3-shared-expert-streamfrom
dsv3-fused-router-mlperf

Conversation

@sanketpurandare

@sanketpurandare sanketpurandare commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Agent details (AI-generated)

Adapted from Yidi Wu (@ydwu4), #5258, revision
a5d8990, with original credit and license
preserved. This is an integration and generalization, not an unmodified port.

Keep the gate native and fuse sigmoid, group-limited top-k, routing weights,
map/usage counts and backward. Preserve NVIDIA's BF16 logit/selected-weight
boundaries and independent BF16 rounding for route and auxiliary score
gradients. Forced round-robin remains an explicit benchmark deviation.

Accept general legal token/expert/top-k/group dimensions with parameterized
Triton kernels. Preserve the tuned CuTe launch for the production geometry.
Match ATen's FP32 reduction order, including output-major upstreams, four
virtual-thread accumulators and unaligned vector tails. Use fresh integer
counts in the general path rather than a shape-dependent shared-counter budget.
Keep padding, remat, rank-local counters, checkpoint parameters and native
auxiliary-loss composition. Required unsupported precision/mesh/device
contracts fail explicitly; supported shapes stay fused.

Verification

Owning-commit CPU checks: 61 passed in 7.92s.

Strict relevant Sphinx builds and all non-type repository hooks passed.
Three unchanged main type findings remain attributed, not reported as a clean
full type run. External reviewer and CI acceptance are separate, still pending.

Complete-stack integration (not this PR in isolation): real four-GPU PP2/DP2/
EP2 and PP4/DP1/EP1 ran ten updates with exact model/optimizer tensor parity,
optimizer graphs and sequential validation. A fresh native PP2/PP4 checkpoint
matrix matched resumed state exactly. These are debug-model contract checks,
not 671B throughput or convergence results.

The final 207-case GPU matrix covers in-place gradients, dense attention, PP/FSDP train/eval graphs, shared-stream backward/capture and fused numerical contracts.

GPU JIT kernel/helper ASTs match the previously measured hot/general-shape
implementation. Prior matched GB300 microbenchmarks remain qualified evidence,
not a universal hardware or all-shape speedup claim. Original Yidi Wu source
credit remains above and in the implementation.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 19, 2026
@sanketpurandare
sanketpurandare removed this pull request from stack #5331 October 20, 2026 15:21
@sanketpurandare
sanketpurandare force-pushed the dsv3-fused-router-mlperf branch from 6cd1c0e to 7fc3089 Compare October 20, 2026 15:22
@sanketpurandare
sanketpurandare changed the base branch from dsv3-unequal-dist-moe-activation-slots to dsv3-shared-expert-stream October 20, 2026 15:22
@sanketpurandare sanketpurandare changed the title [DeepSeek V3] Fuse MLPerf router forward and backward [DeepSeek V3] Fuse general-shape router forward and backward Oct 20, 2026
@sanketpurandare
sanketpurandare removed this pull request from stack #5567 October 23, 2026 21:49
@sanketpurandare
sanketpurandare force-pushed the dsv3-fused-router-mlperf branch from 7fc3089 to a02cf17 Compare October 23, 2026 21:50
@sanketpurandare
sanketpurandare marked this pull request as ready for review October 23, 2026 21:52
@pytorch-bot pytorch-bot Bot added ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests labels Oct 23, 2026
@tianyu-l

tianyu-l commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

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


Request changes. Under the MLPerf recipe, the fused router's BF16 backward produces different gradients from the native router, and the production GB300 CuTe kernel never runs in CI. Details are in 7 inline comments.

Review summary

Blocking

  1. The override changes numerics (fused_dsv3_router.py:324-333). The recipe uses a BF16 Linear gate, Sigmoid(fp32) and routing_weight_dtype=bf16. In that configuration the native router sums the route and aux gradients into the same scores_TE in FP32 and rounds to BF16 once. _AuxLossInjection stays in the same autograd graph, so this is how native works today. The fused kernel instead rounds each branch to BF16 separately and uses a different sigmoid-backward op order.
    • Enabling the override therefore changes training gradients.
    • The native fallback path still gives native numerics, so results depend on which path a call takes.
    • Either match native, or make the NVIDIA-style rounding an explicit choice and include a loss comparison against the unfused recipe (CLAUDE.md "Show numerical proof").
  2. Test gaps (tests/unit_tests/gpu/test_fused_dsv3_router.py:225).
    • The CuTe class only runs on SM 10.3; B200 CI is SM 10.0. About 800 lines of inline PTX, DSMEM code and the arrival-counter protocol are never tested continuously, and that is the path production runs use.
    • Every module-level comparison uses a HiMidLoLinear gate (FP32 logits). None covers the recipe's BF16 Linear setup against the native DeepSeekV3Router.
    • Consider landing the Triton path first and the CuTe specialization separately, with a measured end-to-end gain. The current evidence is "prior qualified microbenchmarks".

Should fix

  1. Recompiles: TOKENS is a tl.constexpr in both Triton kernels, so each distinct token count triggers a new JIT compile. Pass bucketed values computed on the host instead (:168).
  2. Forward/backward dispatch can disagree.
    • The backward doesn't check the multiprocessor count, groups or epsilon that the forward checks, so one call can mix the two backends.
    • The CuTe backward flushes subnormals to zero when not deterministic; the Triton backward never does.
    • Decide the backend once in the forward and store it on ctx (:1416).
  3. Coupling to ATen internals: _native_row_sum and the unsorted-top-k ordering copy ATen implementation details (Reduce.cuh heuristics, gatherTopK output order), not contracts. That is a lot of code for bitwise parity on an 8-element sum, while the backward already differs from native on purpose (:85).

Nits

  • _with_local_counter_sharding uses string axis names; use the DP/CP/TP constants.
  • _generic_router_forward takes counter but never uses it, yet the op still declares it mutated.
  • Other override tests live under tests/unit_tests/{cpu,gpu}/recipes/; move the new tests there.
  • test_whole_override_compiles_without_graph_breaks calls the eager fused module native, which is misleading.
  • The imports inside test_dsv3_mtp1_mlperf_recipe_contract should be hoisted to module level.
  • Typos with missing spaces: "uses256 / top8 / scale2.5" in FUSED_DSV3.md and "At128" in the _native_row_sum docstring.

I did not run the tests: running pytest in this environment needed an approval I didn't have, and no GPU was available.

Comment on lines +324 to +333
if BF16_LOGITS:
route_gradient = (
(route_gradient * scores * (1.0 - scores)).to(tl.bfloat16).to(tl.float32)
)
score_gradient = (
(score_gradient * scores * (1.0 - scores)).to(tl.bfloat16).to(tl.float32)
)
result = route_gradient + score_gradient
else:
result = ((score_gradient + route_gradient) * (1.0 - scores)) * scores

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 changes numerics compared with the native router; it is not a drop-in fusion. This branch is exactly what the MLPerf recipe runs: BF16 Linear gate, Sigmoid(compute_dtype=fp32) and routing_weight_dtype=bf16.

In the native TokenChoiceTopKRouter.forward, the gather branch and the aux-loss branch both read the same FP32 scores_TE. _AuxLossInjection puts the aux gradient into that same autograd graph. Autograd therefore sums both gradients in FP32, runs SigmoidBackward as (g*(1-s))*s, and the .to(fp32) backward rounds to BF16 once.

This kernel does something different. It rounds each branch to BF16 separately, uses g*s*(1-s), and adds the two rounded values. So turning the override on changes the recipe's training gradients. The fallback path (require_fusion=False) still gives native numerics, so the gradients also depend on which path a call takes.

The GPU tests don't catch this because they compare against _MegatronSigmoid (applied twice), not against the native module.

If matching NVIDIA's numerics is the goal, it should be a visible choice: a native config option, or at least a named flag on this override. Under CLAUDE.md that also needs a loss comparison against the unfused recipe. Otherwise, the BF16 path should match native: sum both branches in FP32 and round once.

Comment on lines +225 to +228
@unittest.skipUnless(
torch.cuda.is_available() and torch.cuda.get_device_capability() == (10, 3),
"GB300 specialization",
)

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 whole class only runs on SM 10.3. The CI job enabled by ciflow/b200 uses B200 (SM 10.0), so the CuTe forward/backward never runs in CI. That is about 800 lines of inline PTX, cluster/DSMEM code and the arrival-counter protocol, and it is the path production GB300 runs actually take. The B200 job only exercises the Triton path.

Two options: drop the CuTe specialization from this PR (the Triton path is already fused) and land it separately with a measured end-to-end gain, or find a way to test it continuously.

Also, _config() uses a HiMidLoLinear gate (FP32 logits) everywhere. No module-level test covers the recipe's BF16 Linear + Sigmoid(fp32) + routing_weight_dtype=bf16 setup against the native DeepSeekV3Router. That is the comparison that would expose the gradient difference flagged in fused_dsv3_router.py:324.

Scores,
Selected,
Denominator,
TOKENS: tl.constexpr,

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.

TOKENS is a tl.constexpr here and in _generic_router_backward_kernel, so Triton JIT-compiles a new kernel for every distinct token count. That conflicts with the "general token dimensions" claim: any workload whose T varies (validation with a different batch, dropless/varlen, RL) recompiles. In _native_row_sum, T only matters through min(512, next_pow2(T+1)//2) and T % 4. Compute those small bucketed values on the host and pass them as the constexprs instead of raw T.

Comment on lines +1416 to +1422
if (
scores_TE.shape == (4096, 256)
and expert_ids_TK.shape[1] == 8
and route_scale == 2.5
and _CUTEDSL_IMPORT_ERROR is None
and torch.cuda.get_device_capability(scores_TE.device) == (10, 3)
):

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 backward picks its kernel with different conditions from the forward (_use_tuned_router). It doesn't check multi_processor_count >= 128, the group/limited/forced shape, or epsilon. So a call whose forward ran the Triton kernel (for example on an MIG slice, or with a different epsilon) can run its backward on the CuTe kernel.

The two backends also aren't numerically identical. The CuTe backward flushes subnormal scattered gradients to zero when not deterministic (L1001-1006); the Triton backward never does. Make the dispatch decision once in the forward, store it on ctx, and either keep the backends' numerics in sync or document the difference.

Comment on lines +85 to +99
@triton.jit
def _native_row_sum(
values,
token,
TOKENS: tl.constexpr,
SIZE: tl.constexpr,
OUTPUT_MAJOR: tl.constexpr = False,
):
"""Preserve ATen's FP32 virtual-thread, accumulator and warp reduction order.

Block width depends on input/output sizes. At128 columns ATen switches
to aligned vectors with four accumulators, including row head/tail values.
Fold accumulators before the warp tree, not after it.
"""
VECTORIZED: tl.constexpr = SIZE >= 128 and not OUTPUT_MAJOR

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 function copies ATen's internal Reduce.cuh launch heuristics (block width/height, vectorization threshold, four-accumulator folding, output-major split) to get bitwise parity on a sum over K=8 values. The unsorted-top-k output order (L236-243 and native_order) does the same for ATen's gatherTopK. Neither is a PyTorch contract. Any upstream change to them breaks parity and means re-deriving this logic.

Is bitwise parity with the unfused forward worth that coupling when the backward already differs from native on purpose (see L324)? If the goal is "matches native up to reduction order", plain tl.sum plus a tolerance-based test would cut a lot of code. If bitwise parity really is required, add a comment pointing to the exact ATen source revision this mirrors.

Comment on lines +1598 to +1603
state_shardings={
**sharding_config.state_shardings,
"arrival_counter": spmd.SpmdType(
{"dp": spmd.V, "cp": spmd.V, "tp": spmd.V}
),
},

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.

Nit: use the DP/CP/TP axis constants, as _tokens_per_expert_placement in models/common/moe/sharding.py does, rather than string literals.

native gate DGRAD / WGRAD
```

The 671B learned recipe uses256 experts, top8, eight groups/four selected groups,

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.

Typo: missing spaces in "uses256 experts, top8, ... scale2.5". The same thing happens in "At128 columns" in the _native_row_sum docstring. Non-ASCII spaces were probably stripped.

## Agent details (AI-generated)

Adapted from Yidi Wu (@ydwu4), #5258, revision
a5d8990, with original credit and license
preserved. This is an integration and generalization, not an unmodified port.

Keep the gate native and fuse sigmoid, group-limited top-k, routing weights,
map/usage counts and backward. Preserve NVIDIA's BF16 logit/selected-weight
boundaries and independent BF16 rounding for route and auxiliary score
gradients. Forced round-robin remains an explicit benchmark deviation.

Accept general legal token/expert/top-k/group dimensions with parameterized
Triton kernels. Preserve the tuned CuTe launch for the production geometry.
Match ATen's FP32 reduction order, including output-major upstreams, four
virtual-thread accumulators and unaligned vector tails. Use fresh integer
counts in the general path rather than a shape-dependent shared-counter budget.
Keep padding, remat, rank-local counters, checkpoint parameters and native
auxiliary-loss composition. Required unsupported precision/mesh/device
contracts fail explicitly; supported shapes stay fused.

## Test Plan (AI-generated)

python -m pytest tests/unit_tests/cpu/test_fused_dsv3_router.py tests/unit_tests/gpu/test_fused_dsv3_router.py -q
pre-commit run --all-files

40 CPU/GPU tests passed, including original tuned-path cases, exact general
FP32/BF16 gradients, forced routing, transposed gradients, unaligned top-129
tails, FakeTensor metadata, fullgraph compilation and CUDA capture/replay.
Strict owning documentation rendering passed. All non-type lint hooks passed;
only unchanged baseline type findings remained.

Matched GB300 graph-replay F+B, excluding the common gate GEMM: the production
path measured 28.7795us versus 28.7770us before (0.009%, within trial spread).
General cases outperformed the same native reference: E64/K6/T8193 8.114x,
E512/K8/T4097 6.633x, and E512/K129/T17 4.288x. Seed14536; three trials of
50 replays, with separate eager GPU trace collection and exact reference checks.
These are kernel results, not distributed throughput or convergence claims.
Full updated PP2/PP4 composition and expanded memory accounting remain pending.

This branch has not been deployed

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

Labels

ciflow/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