Skip to content

[HIP] topk_gating: fix dropped and out-of-range top-k slots - #4965

Merged
junhaha666 merged 8 commits into
ROCm:mainfrom
yzhou103:fix_topk_gating_gfx1250
Aug 26, 2026
Merged

junhaha666 merged 8 commits into
ROCm:mainfrom
yzhou103:fix_topk_gating_gfx1250

Conversation

@yzhou103

Copy link
Copy Markdown
Contributor
  • elect the argmax winner by ballot, so tied lanes agree on which expert to retire instead of each retiring its own
  • cap rows-per-warp at topk <= warp_size/N, so wave32 stops picking kernels that write past the topk slots
  • scrub NaN at load in the prefill scan, which otherwise stalls the lane and loses its remaining experts

Motivation

Technical Details

Test Plan

Test Result

Submission Checklist

@yzhou103
yzhou103 marked this pull request as ready for review August 24, 2026 10:11
@yzhou103
yzhou103 requested review from a team and a lite review from Copilot August 24, 2026 10:11
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter op tests (gfx942 + gfx950)
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs; main branch always runs both MI35X and MI300X
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: GPT-OSS-120B, DeepSeek-R1-0528, Kimi-K2.5
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 4965 --add-label <label>

PR title tags:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf] and op tags like [MLA] are left untouched. Add the no-auto-title label to opt this PR out of title tagging.

@github-actions github-actions Bot changed the title topk_gating: fix argmax ties, wave32 dispatch and prefill NaN [HIP] topk_gating: fix argmax ties, wave32 dispatch and prefill NaN Aug 24, 2026
- elect the argmax winner by ballot, so tied lanes agree on which
  expert to retire instead of each retiring its own
- cap rows-per-warp at topk <= warp_size/N, so wave32 stops picking
  kernels that write past the topk slots
- scrub NaN at load in the prefill scan, which otherwise stalls the
  lane and loses its remaining experts
- enable the op test on gfx1250 and add ties/eplb sections; the nan
  section only reaches the prefill path there, since wave64 routes
  E=384 to the reg kernel

Co-authored-by: Cursor <[email protected]>
@yzhou103
yzhou103 force-pushed the fix_topk_gating_gfx1250 branch from 2910ef5 to 32abc96 Compare August 24, 2026 10:15
@yzhou103 yzhou103 changed the title [HIP] topk_gating: fix argmax ties, wave32 dispatch and prefill NaN [HIP] topk_gating: fix dropped and out-of-range top-k slots Aug 24, 2026

Copilot AI 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.

Pull request overview

This PR fixes HIP top-k gating for tie handling, wave32 dispatch safety, and prefill NaN inputs.

Changes:

  • Adds ballot-based tie resolution and NaN scrubbing.
  • Caps row-per-warp dispatch by runtime warp size.
  • Adds tie/EPLB tests, section selection, and gfx1250 support.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Review findings
op_tests/test_moe_topk_gating.py Moderate: gfx1250 is not exercised by the required CI workflow; add coverage or a mandatory validation job (2 votes). Moderate: empty EPLB filters cause a KeyError; handle empty configurations before summary validation (3 votes).
csrc/include/topk_gating_kernels.cuh No final comments.

💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread op_tests/test_moe_topk_gating.py Resolved
Comment thread op_tests/test_moe_topk_gating.py Resolved
Copilot AI review requested due to automatic review settings August 24, 2026 10:19

Copilot AI 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.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

Suppressed comments (4)

op_tests/test_moe_topk_gating.py:877

  • [verified] With the new --section eplb, a valid invocation such as --num-experts 10 --section eplb makes this filtered list empty. pd.DataFrame([]) then has no fused err column, so the error mask below raises KeyError instead of skipping or reporting that no compatible configurations were selected. Author must handle an empty filtered configuration set before applying the result checks.
            if cfg[0] % _EPLB_EP_SIZE == 0
        ]
        df = [bench_topk_gating_eplb(*cfg) for cfg in eplb_configs]

op_tests/test_moe_topk_gating.py:59

  • [verified] Adding gfx1250 to SUPPORTED_GFX enables this test on the wave32 target, but .github/workflows/aiter-test.yaml:20 still prebuilds only gfx942;gfx950 and no automated invocation of this file targets gfx1250. The wave32-specific row-cap and subgroup changes are therefore untested in CI and can regress unnoticed. Author must add a gfx1250 test job/labelled runner or provide equivalent automated coverage before relying on this allow-list.
SUPPORTED_GFX = ["gfx942", "gfx950", "gfx1250"]

op_tests/test_moe_topk_gating.py:844

  • [verified] The new tie/EP sweeps use the default topk list, which stops at 8. That leaves the wave32 boundary cases this dispatch change also targets untested by the default CI run: for example, k=16 with E=128/TPW=4 and k=32 with E=256/RPW=2 previously had only 8/16 participating lanes, leaving output slots unwritten. Author must add targeted k=16/32 wave32 cases to CI.
                ["sqrtsoftplus", "sigmoid", "softmax"],

op_tests/test_moe_topk_gating.py:729

  • [verified] Adding ties and eplb to the default list expands the default matrix from 2,040 to 4,200 configurations, while each fused case invokes run_perftest for 101 iterations (aiter/test_common.py:206-224); the CI scheduler still records 104 seconds for this file (.github/scripts/split_tests.sh:87). This can make the standard op-test shard miss its allocation. Author must either keep these stress sections opt-in or update the measured CI budget after running the default suite.
        default=["sigmoid", "softplus", "softmax", "nan", "ties", "eplb"],

Comment thread csrc/include/topk_gating_kernels.cuh Resolved
Comment thread csrc/include/topk_gating_kernels.cuh Resolved
Copilot AI review requested due to automatic review settings August 24, 2026 10:59

Copilot AI 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.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

Suppressed comments (7)

op_tests/test_moe_topk_gating.py:596

  • [verified] This error metric can become NaN when any selected weight is NaN, and the NaN > _WEIGHT_TOL predicate in the filter below is false, so the new tie test can report success despite invalid routing weights. Author must convert non-finite errors to a failing value or add an explicit isfinite check.
    ret["renorm err"] = float((topk_weights.sum(-1) - 1.0).abs().max())

op_tests/test_moe_topk_gating.py:680

  • [verified] The same NaN-comparison hole exists in the new EPLB metric: sum() can produce NaN, which makes the renorm err threshold false and allows invalid weights to pass. Author must convert non-finite errors to a failing value or add an explicit isfinite check.
    ret["renorm err"] = float((topk_weights.sum(-1) - 1.0).abs().max())

op_tests/test_moe_topk_gating.py:880

  • [verified] With --section eplb --num-experts 2 (or any input containing no multiple of four), the filter produces no configurations, pd.DataFrame([]) has no fused err column, and the expression below raises KeyError instead of skipping the section. Author must guard the empty configuration list before building and filtering the result table.
        df = [bench_topk_gating_eplb(*cfg) for cfg in eplb_configs]
        df = pd.DataFrame(df)
        aiter.logger.info(
            "topk_gating fake-eplb EP balance summary (markdown):\n%s",

op_tests/test_moe_topk_gating.py:562

  • [verified] These new cases target kernels that can leave slots unwritten, but torch.empty makes the unwritten IDs and weights allocator-dependent. A stale in-range ID can evade the oracle while an out-of-range ID makes gather fail, so this is not a deterministic regression test. Author must initialize outputs with sentinels and record invalid IDs before running the oracle.
    topk_weights = torch.empty((num_tokens, topk), dtype=torch.float32, device="cuda")
    topk_ids = torch.empty((num_tokens, topk), dtype=torch.int32, device="cuda")

op_tests/test_moe_topk_gating.py:729

  • [verified] Adding ties and eplb to the default list expands the default matrix by 1,080 configurations each (from 2,040 to 4,200), and each uses run_perftest's 101 iterations. This more than doubles the workload behind the 104-second shard estimate in .github/scripts/split_tests.sh:87. Author must make the stress sections opt-in or update the partition/timeout after measuring the new runtime.
        default=["sigmoid", "softplus", "softmax", "nan", "ties", "eplb"],

op_tests/test_moe_topk_gating.py:646

  • [verified] The EPLB case has the same nondeterministic output allocation: a multi-row kernel that skips slots can leave topk_ids with stale memory, so the balance and duplicate checks are not a reliable guard for the bug this section is intended to catch. Author must initialize outputs with sentinels and record invalid IDs before bincount.
    topk_weights = torch.empty((num_tokens, topk), dtype=torch.float32, device="cuda")
    topk_ids = torch.empty((num_tokens, topk), dtype=torch.int32, device="cuda")

op_tests/test_moe_topk_gating.py:59

  • [verified] SUPPORTED_GFX now advertises gfx1250 coverage, but the Aiter CI workflow still sets GPU_ARCH_LIST to only gfx942;gfx950 (.github/workflows/aiter-test.yaml:20). Therefore the new wave32 row-cap/argmax paths are not exercised by automated CI and can regress or fail to compile unnoticed. Author must add gfx1250 execution coverage or keep it out of the supported test matrix until that path is validated.
SUPPORTED_GFX = ["gfx942", "gfx950", "gfx1250"]

Copilot AI review requested due to automatic review settings August 24, 2026 14:56

Copilot AI 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.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

Suppressed comments (4)

csrc/include/topk_gating_kernels.cuh:747

  • [verified] The softmax prefill path does need an equivalent zeroing step for an all-NaN row: it normalizes row_chunk and copies the resulting 1 / num_experts values into row_orig before is_nan forces only the selection values to -INFINITY (lines 806-815). Consequently, the starved softmax case can emit the fallback expert repeatedly with nonzero weights, even though this comment says no equivalent is needed, and _starved_rows_finite will incorrectly pass it. Author must make invalid softmax entries contribute zero weight (including the all-NaN/all-invalid row) and assert that behavior in the regression test.
                // NaN weight -> 0 so it cannot poison the renorm sum; see opt
                // kernel. Softmax needs no equivalent: it overwrites row_orig
                // with normalized probabilities below.
                row_orig[elt]  = ::isnan(score) ? 0.0f : score;

csrc/include/topk_gating_kernels.cuh:519

  • [verified] This replaces multithread_reduce_max_dpp's fused v_max_f32 ... dpp instruction (csrc/include/hip_reduce.h:450-455) with wave_reduce, whose move_dpp and fmaxf are separate operations (hip_reduce.h:256-300). That extra VALU/DPP work is repeated for every top-k round in the prefill and shared-memory paths, so the tie fix can be a material latency regression even though it still uses DPP. Author must provide old-vs-new timings on the affected gfx942/gfx950/gfx1250 paths and retain a hazard-safe fused reduction or document the measured tradeoff.
    auto        max_op  = [](float a, float b) { return fmaxf(a, b); };
    const float max_val = wave_reduce<float, decltype(max_op), THREADS_PER_ROW>(val, max_op);

op_tests/test_moe_topk_gating.py:776

  • [verified] Adding ties and eplb to the default sweep more than doubles the benchmark workload: with the default E/T/K/dtype lists, each new section creates 1,080 configurations, and each run_perftest performs 2 warmups plus 101 timed launches. The repository still budgets this file at 104 seconds in .github/scripts/split_tests.sh:87, so every normal Aiter CI run now pays a large, unplanned latency/resource increase. Author must make these stress sections opt-in or update the CI timing budget from a measured run.
        default=["sigmoid", "softplus", "softmax", "nan", "ties", "eplb"],
        help="Comma-separated list of sections to run: "
        "sigmoid,softplus,softmax,nan,ties,eplb (default: all). "
        "The first three are named after a score function; nan, ties and eplb "
        "each sweep all score functions. --score-func is a deprecated alias.",

op_tests/test_moe_topk_gating.py:71

  • [verified] The newly added gfx1250 allow-list is intended to exercise the wave32 cap and dispatch, but the standard aiter-test workflow still sets GPU_ARCH_LIST to only gfx942;gfx950 (.github/workflows/aiter-test.yaml:20). Consequently, the primary wave32 path is not exercised by required PR CI, so a regression there can merge green. Author must add a required gfx1250 run or otherwise wire explicit wave32 hardware validation.
SUPPORTED_GFX = ["gfx942", "gfx950", "gfx1250"]

Copilot AI review requested due to automatic review settings August 24, 2026 15:08

Copilot AI 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.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

Suppressed comments (6)

Previously missed (2) — in code that hasn't changed since the last review.

op_tests/test_moe_topk_gating.py:772

  • [verified] Making ties and eplb part of the default section list adds 1,080 configurations each (4 expert counts × 6 token counts × 5 top-k values × 3 score functions × 3 dtypes), and every configuration performs the default 101-iteration run_perftest; this is more than twice the existing workload. The test scheduler still budgets this file at 104 seconds in .github/scripts/split_tests.sh, so the default run can create a large shard-time regression. Author must keep these expensive stress sections opt-in or update the CI time budget and shard plan with measured runtime.
        default=["sigmoid", "softplus", "softmax", "nan", "ties", "eplb"],

op_tests/test_moe_topk_gating.py:299

  • [verified] _starved_rows_finite only checks topk_weights.isfinite(). In the underfilled-row cases used here, a regression can leave topk_ids out of range, return all-zero weights, or produce a finite but incorrectly rescaled weight for the one valid expert and still pass this check. Author must validate the IDs and compare the one-valid/all-invalid rows against an independent expected routing and weight oracle.
    return bool(topk_weights.isfinite().all().item())

csrc/include/topk_gating_kernels.cuh:747

  • [verified] The prefill softmax path still returns nonzero weights for an all-NaN row. NaN logits are converted to -Inf, so -Inf - -Inf enters the isnan(diff) ? 1.0f case later in this kernel and row_orig becomes 1 / num_experts; selection then excludes those IDs but consumes those positive weights. Thus an input such as [NaN] * E with topk > 0 violates the all-invalid/sentinel-zero behavior, while the new starved check only tests finiteness and passes. Author must preserve zero weight for NaN experts in the softmax normalization (including the all-NaN case) and assert that case in the test.
                // NaN weight -> 0 so it cannot poison the renorm sum; see opt
                // kernel. Softmax needs no equivalent: it overwrites row_orig
                // with normalized probabilities below.
                row_orig[elt]  = ::isnan(score) ? 0.0f : score;

csrc/include/topk_gating_kernels.cuh:515

  • [verified] This rationale does not match the helper being called: wave_reduce resolves to moe_sorting_opus.h:660-685, where the reduction uses __builtin_amdgcn_ds_bpermute, not __builtin_amdgcn_mov_dpp. The new subwarp path therefore is not the claimed DPP path, and the hazard/performance explanation can mislead future tuning. Author must either use the intended DPP reduction or update this comment to describe the actual primitive and its measured trade-off.
    // step short.  wave_reduce goes through __builtin_amdgcn_mov_dpp, so the
    // hazard is the compiler's problem, and it keeps the DPP path (plus the
    // row_xmask/permlanex16 form the reduce needs on GFX10+).

csrc/include/topk_gating_kernels.cuh:1486

  • [verified] This new gate covers topk <= 32, but the test's default top-k list is still only [1, 2, 4, 6, 8] and CI runs the file without extra arguments (.github/scripts/aiter_test.sh:83). Consequently the wave32/topk=16 or 32 dispatch boundaries changed here are not exercised by the default suite. Author must add explicit topk=16 and 32 tie/NaN cases (or wire equivalent CI arguments) before relying on this cap.
        if(topk <= 32 && row_cap >= 2 && num_experts <= 256 && num_tokens >= 4096)

op_tests/test_moe_topk_gating.py:776

  • [verified] The new wave-size-dependent cap has distinct behavior for topk > 8 (for example, wave32 topk=16 reduces the permitted rows to 2), but the default sweep still stops at 8, so the added tie/EP tests never exercise those dispatch paths. A regression that leaves TPW/RPW too large for topk=16 or 32 would be missed. Author must add a focused topk=16/32 case or an equivalent explicit dispatch test.
        default=["sigmoid", "softplus", "softmax", "nan", "ties", "eplb"],
        help="Comma-separated list of sections to run: "
        "sigmoid,softplus,softmax,nan,ties,eplb (default: all). "
        "The first three are named after a score function; nan, ties and eplb "
        "each sweep all score functions. --score-func is a deprecated alias.",

@zufayu
zufayu requested a review from junhaha666 August 25, 2026 01:22
yzhou103 and others added 5 commits August 25, 2026 06:56
A row with fewer valid (non-NaN) experts than topk cannot fill every slot,
so the kernels elect a sentinel for the remainder. That sentinel was carried
into the renorm sum as NaN (register kernels) or -Inf (smem kernels), and
fmaxf() then drops the sum to RENORM_SUM_FLOOR -- which rescales the row's
*valid* weights by ~1e20. One starved row therefore corrupted the experts it
did resolve, not just the slots it could not fill.

Weight an invalid expert 0 instead. The sum stays finite, valid experts keep
their renorm, and a row with no valid expert at all comes out as all-zero
weights, which is what RENORM_SUM_FLOOR already documents as its degenerate
case. Softmax in the prefill kernel needs no change: it overwrites the weight
array with normalized probabilities, where a NaN logit is already 0.

The nan section now also checks a starved row per config; without the kernel
change 480 of its configs fail.

Co-authored-by: Cursor <[email protected]>
The renorm check compared a raw float against a tolerance, but a NaN weight
makes that error NaN and `NaN > _WEIGHT_TOL` is false -- so exactly the runs
with invalid weights were reported as passing. Map non-finite to +inf.

The eplb section keeps only expert counts divisible by the EP size, and an
invocation that leaves none (e.g. --section eplb --num-experts 2) built an
empty DataFrame, whose missing "fused err" column raised KeyError instead of
skipping the inapplicable section.

Co-authored-by: Cursor <[email protected]>
The opt_n breakevens above the gate were measured on 64-lane waves, where
E=64 TPW=8 gives EPT = 64 / (64/8) = 8. On wave32 the same TPW halves
THREADS_PER_ROW, so EPT doubles to 16, the unrolled sort_network_desc
runs past the register budget and the kernel spills: 2096B scratch, 8159
scratch accesses, occupancy 8.

It is reached there, since row_cap >= 8 holds for topk <= 4 on wave32,
and the cost is not marginal. gfx1250, E=64, gate on versus the TPW=1 reg
kernel it now falls through to (sqrtsoftplus / sigmoid):

  T=4096   225.4 / 228.5 us  ->  3.09 / 3.05 us   (73x / 75x)
  T=8192   244.5 / 225.8 us  ->  3.77 / 3.65 us   (65x / 62x)
  T=16384  312.2 / 295.8 us  ->  5.13 / 4.73 us   (61x / 63x)

Same reason E=384 reg is wave64-only a few lines down. gfx950 keeps
opt_n: at EPT=8 it does not spill, and no shape there changes. The E=128
TPW=4 gate needs no guard, being gfx942-only already.

E=64 over T={4096,8192,16384} x topk={1,2,4,8} x {bf16,fp16} passes, 384
rows.

Co-authored-by: Cursor <[email protected]>
gfx9 needs 2 wait states between a VALU writing a VGPR and a DPP reading it.
The DPP is inside asm, so the hazard recognizer never counts them, and nothing
separates the first DPP from the VALU feeding it. Such a DPP returns the lane's
own value and the step becomes the identity: a wave64 chain absorbs one lost
step, a short one does not. On gfx950 the reduce came out wrong for thread_num
2, 4, 8 and 16 -- about half the lanes -- and correct at 32 and 64.
fused_qk_rmsnorm_group_quant and fused_qk_norm_rope_cache_quant both reach 16.

s_nop 1, not s_nop 0: LLVM emits s_nop 1 for every gfx9 target when it can see
the DPP, and both are one instruction.

The chain now sits in one asm block, so the compiler does not stack its own
inter-block s_nop on ours: +0.16% instructions rather than +0.30%. gfx10+ adds
no wait and saves a VGPR. Timing is unchanged within noise.
v_max_f32 is IEEE maxNum, so fmaxf(v, -INFINITY) gives -INFINITY for NaN and v
otherwise -- what the ::isnan() select did, -INFINITY included, without
v_cmp_o_f32 + v_cndmask. -376 instructions (-0.22%). Not a speedup: the scrub
was already free.

Only vals[] changes. orig[] keeps the explicit select; fmaxf(score, 0.0f) would
fold too, but only where score is non-negative.
Copilot AI review requested due to automatic review settings August 25, 2026 07:05
@yzhou103
yzhou103 force-pushed the fix_topk_gating_gfx1250 branch from 4fa32b2 to 862497a Compare August 25, 2026 07:05

Copilot AI 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.

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

Suppressed comments (3)

csrc/include/topk_gating_kernels.cuh:846

  • [verified] This invalidates row_chunk but leaves the corresponding row_orig intact. When a row has fewer valid experts than topk (for example, score_func="softmax", topk=2, and only expert 0 valid), the next scan sees only -INFINITY candidates but initializes local_orig from row_orig[0], so it emits the already-selected expert again with a nonzero weight instead of a zero sentinel. The new starved-row check only tests finiteness and will not catch this routing corruption. Author must clear the matching row_orig entry, or initialize local_orig only after finding a candidate, when invalidating the winner.
        if(lane_in_group == winner)
            row_chunk[best_idx - winner * VPT] = -INFINITY;

csrc/include/topk_gating_kernels.cuh:735

  • [verified] The NaN weight is zeroed only in the non-softmax load branch. In the softmax path, an all-NaN row is normalized with -INFINITY - (-INFINITY), so each NaN entry receives row_orig = 1 / num_experts; the later row_chunk = -INFINITY only excludes it from selection, not from the emitted weight. The first sentinel slot therefore gets a nonzero weight for an all-invalid row. Author must zero row_orig for NaN entries in the softmax normalization path (or force best_orig to zero whenever the elected score is non-finite).
                // NaN weight -> 0 so it cannot poison the renorm sum; see opt
                // kernel. Softmax needs no equivalent: it overwrites row_orig
                // with normalized probabilities below.
                row_orig[elt]  = ::isnan(score) ? 0.0f : score;

csrc/include/topk_gating_kernels.cuh:1165

  • [verified] The new ballot-based argmax path in topk_gating_kernel_smem_n is not exercised by the default sweep: E={64,128,256,384} returns through opt/opt_n or prefill_n before reaching smem_n; that fallback requires a non-special-cased expert count such as E=100 with T>=1024. A regression in this changed tie/clear logic can therefore pass all added tie and EPLB cases. Author must add a configuration that forces topk_gating_kernel_smem_n and assert its selected IDs and weights.
        // The clear below is keyed on max_idx, so the winner has to be uniform
        // across the group or every tied lane blanks a different expert.
        const int winner = subwarpArgmaxLane<THREADS_PER_ROW>(max_val);
        max_idx          = __shfl(max_idx, winner, THREADS_PER_ROW);

Comment thread op_tests/test_moe_topk_gating.py Resolved
A row whose every logit is NaN reduces to local_max == -Inf in the prefill
kernel's softmax block, so every diff is -Inf - -Inf = NaN and the +Inf special
case reads each one as ex = 1.0. The row normalizes to a uniform 1/E, which
row_orig keeps: forcing row_chunk back to -Inf only bars the expert from
selection, it does not unweight it. The merge then hands out topk full-weight
slots for a token with nothing to route, and because every selection score is
-Inf the tie ballot resolves to the same lane every round, so all of those slots
name expert 0.

The other paths already agree on 0 -- the smem kernels clamp the -Inf they
elect, and the register kernels zero the weight at load -- so softmax in prefill
was the one place where the same input answered differently depending on which
kernel the dispatcher picked. local_max is row-uniform and already reduced, so
scaling by 0 costs one select outside the VPT loop.

The starved check only asserted isfinite, which a uniform 1/E satisfies, and it
never looked at the ids. It now requires the no-valid-expert row to come out
all-zero, and gives the second poisoned row topk-1 valid experts so that
comparing the weighted ids as a set can fail on a sentinel that takes a slot or
duplicates a real expert.

Co-authored-by: Cursor <[email protected]>
Copilot AI review requested due to automatic review settings August 25, 2026 08:40

Copilot AI 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.

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

Suppressed comments (5)

csrc/include/topk_gating_kernels.cuh:800

  • [verified] The new local_max == -INFINITY branch conflates an all-NaN row with an all--Inf row. For softmax logits [-Inf, ..., -Inf] (for example, a fully masked row), this prefill path sets inv_sum=0 and returns zero weights, while topk_gating_kernel_smem_n and the generic kernel take the existing diff=NaN -> ex=1 path and return uniform nonzero weights. The same API therefore produces dispatch-dependent results. Author must choose the intended all--Inf behavior and apply it consistently to every softmax variant, with a regression case.
        float inv_sum = (local_max == -INFINITY)
                            ? 0.0f
                            : __builtin_amdgcn_rcpf(fmaxf(local_sum, RENORM_SUM_FLOOR));

csrc/include/topk_gating_kernels.cuh:994

  • [verified] This new sentinel conversion is only exercised by the generic shared-memory fallback, but every default expert count in test_moe_topk_gating.py (64, 128, 256, 384) has a specialized dispatch path, so the default sweep never reaches these lines. Add a non-specialized case such as num_experts=65 with an all-NaN or starved row to verify that this fallback writes zero weights and valid IDs.
        if(!::isfinite(max_val))
            max_val = 0.0f;

op_tests/test_moe_topk_gating.py:650

  • [verified] This tie test uses the kernel-produced IDs as indices before checking that they are valid. The regression this PR is meant to catch (for example, wave32 with E=64 and topk=8 on the old RPW=8 path) leaves slots 4..7 unwritten, so gather can receive arbitrary negative or out-of-range IDs and abort the CUDA test instead of recording a failed row. Author must range-check the IDs and use safe indices before computing dropped.
    dropped = int(((kth - sel.gather(1, topk_ids.long())) > _TIE_TOL).any(dim=1).sum())

op_tests/test_moe_topk_gating.py:733

  • [verified] The new EP test also assumes output IDs are valid: max_rank_share feeds them directly to torch.bincount. The out-of-range or garbage slots this PR is testing can yield negative IDs, causing bincount to raise before the mism/ep max share checks run. Author must guard invalid IDs before rank arithmetic and make invalid rows fail the metrics rather than crash.
    def max_rank_share(ids):
        ranks = ids.reshape(-1).long() // experts_per_rank
        counts = torch.bincount(ranks, minlength=ep_size)

op_tests/test_moe_topk_gating.py:302

  • [verified] These outputs are allocated with torch.empty, so if a multi-row kernel skips a slot the stale allocator value may still be finite and in range, allowing this starvation test to pass despite an unwritten output. Initialize weights with NaN and IDs with -1 before launch so any skipped slot is observable.
    topk_weights = torch.empty((num_tokens, topk), dtype=torch.float32, device="cuda")
    topk_ids = torch.empty((num_tokens, topk), dtype=torch.int32, device="cuda")

Comment thread op_tests/test_moe_topk_gating.py Resolved
The prefill guard keys on local_max == -INFINITY, which is any row with no
valid expert -- not only the all-NaN row the previous commit described. A row of
-Inf logits reaches it too, and since masking an expert out with -Inf is a
normal thing for a caller to do, that input is not a theoretical variant of the
other. It had the same bug: on gfx1250, E=64 K=4 bf16 softmax, every slot of an
all--Inf row weighed 2.5/64 = 0.0390625 before the guard and 0 after -- the same
uniform 1/E the all-NaN row produced. Nothing covered it, so it goes in as a
third poisoned row.

The dead rows are checked on weights only, because their sentinel ids are
allowed to repeat, and do: an all-NaN row emits [0,0,0,0], since forcing
row_chunk back to -Inf leaves the merge's clear nothing to advance past, while
an all--Inf row emits [0,1,2,3], its scrubbed score being 0.0 so the clear does
advance. A zero weight makes that inert for routing, but a consumer that
histograms ids without reading weights would count expert 0 topk times for one
all-NaN token, so it is a trade-off taken rather than an oversight.

Swept on gfx950 over E in {64,256,384} x T in {1,8,256,4096,16384} x K in
{1,4,8} x {fp16,fp32}: every dead row comes out all-zero with ids in [0,E) and
no non-finite weight, need_renorm either way.

Co-authored-by: Cursor <[email protected]>
Copilot AI review requested due to automatic review settings August 25, 2026 10:18

Copilot AI 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.

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

Suppressed comments (1)

csrc/include/topk_gating_kernels.cuh:1184

  • [verified] The same all--Inf softmax case is still normalized to uniform 1/E before this guard, so max_val is finite and the new zero-sentinel branch is bypassed. For example, num_experts=100, num_tokens=1024, topk=8 selects smem_n and emits nonzero weights for a fully masked row, while _starved_rows_ok requires zero weights. Author must guard the softmax normalization when local_max == -INFINITY in this fallback as well.
        if(!::isfinite(max_val))
            max_val = 0.0f;

Comment thread csrc/include/topk_gating_kernels.cuh Resolved
@junhaha666
junhaha666 merged commit 7f18469 into ROCm:main Aug 26, 2026
54 checks passed
junhaha666 pushed a commit that referenced this pull request Nov 17, 2026
…7922)

* [HIP] topk_gating: single-wave register kernel for wave32 (gfx1250)

On wave32, route topk <= 8 to a new kernel, topk_gating_kernel_opt_vwave:
one wave per token, no LDS, no barrier. Lane p holds WPT contiguous lists of
EPT experts (vector loads), sorts each with sort_network_desc, then picks
the top-k with one DPP max + ballot per pick, unrolled to 8.

- E=64/128/256: WPT=1, the reg kernel's layout and results, at every T.
- E=384: WPT=2 up to T=1024 (multiwave WPT=4 before).
- topk > 8, softmax and wave64 keep their kernels.

Ties: the winner is still the lowest lane (as since #4965), but lanes now map
to e % 64 for E=384 (was e % 128) and e % 32 for E=256 at T <= 256 (was
e % 256), so the expert picked among exactly equal scores can change there.
E=256 no longer changes tie order with the token count.

sort_network_desc and compute_score gain an opt-in select form (same result),
used by the new kernel and the reg kernel only; every other kernel's ISA is
unchanged on gfx950 and gfx1250.

Bit checks (12840 cases: E=64/128/256/384/512, topk 1-8, NaN/inf, ties,
bias, pad rows, shared expert, strided/misaligned, fp32 logits):
- gfx1250: identical to the original kernels with the dispatch moved to the
  new tie order; identical to HEAD except the tie cases above.
- gfx950: identical to HEAD.
op_tests/test_moe_topk_gating.py passes on gfx1250 and gfx950.

gfx1250, CUDA graph, us, topk=8 (before -> after):
  E=64   T=1 2.02->1.47  T=256 2.50->2.00  T=16384 6.52->4.86
  E=128  T=1 2.69->1.53  T=256 3.15->2.08  T=16384 7.93->5.56
  E=256  T=1 3.68->1.66  T=256 4.23->2.22  T=16384 11.28->7.17
  E=384  T=1 4.16->2.01  T=256 4.66->2.56  T=1024  5.09->3.02
gfx950: neutral to 5% faster (reg kernel E=128/256/384).
gfx1201 (wave32) is untested.

* topk_gating: scope the single-wave kernel to gfx1250 and the reg select sort to gfx950 / gfx1250

Address review:
- The single-wave kernel dispatches on gfx1250 only; other wave32 targets
  (gfx1201, ...) keep the multiwave / reg kernels as before this branch.
- The reg kernel's select-form sort compiles on gfx950 and gfx1250 only, where it
  was measured; gfx942 and gfx1201 ISA is identical to the base revision.
- Drop a duplicate #undef _CAS_DESC.
- op test: new "unaligned" section. Logits one element past an aligned base (odd
  row stride), aligned logits with an odd row stride, and a bias one element past
  an aligned base must route bit for bit as the aligned launch.

* topk_gating: cache the gfx1250 guard per device; skip an empty unaligned grid

Address review:
- topk_gating_vwave_arch() caches per HIP device, as get_warp_size_func() does,
  so a process that drives gfx1250 and a wave64 GPU never launches the 32-lane
  kernel on the wave64 one.
- op test: the unaligned section only sweeps T <= 1024; skip it when no requested
  token count qualifies (e.g. --num-tokens 4096) instead of indexing an empty frame.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants