Repository navigation
[DeepSeek V3] Fuse general-shape router forward and backward - #5551
sanketpurandare wants to merge 1 commit into
Conversation
6cd1c0e to
7fc3089
Compare
7fc3089 to
a02cf17
Compare
|
@claude review |
|
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 summaryBlocking
Should fix
Nits
I did not run the tests: running pytest in this environment needed an approval I didn't have, and no GPU was available. |
| 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 |
There was a problem hiding this comment.
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.
| @unittest.skipUnless( | ||
| torch.cuda.is_available() and torch.cuda.get_device_capability() == (10, 3), | ||
| "GB300 specialization", | ||
| ) |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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.
| 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) | ||
| ): |
There was a problem hiding this comment.
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.
| @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 |
There was a problem hiding this comment.
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.
| state_shardings={ | ||
| **sharding_config.state_shardings, | ||
| "arrival_counter": spmd.SpmdType( | ||
| {"dp": spmd.V, "cp": spmd.V, "tp": spmd.V} | ||
| ), | ||
| }, |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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.
a02cf17 to
06f248e
Compare
## 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.
06f248e to
4bd0714
Compare
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.