Skip to content

CUDA: support duplicate expert ids in mul_mat_id - #26294

Closed
Nas01010101 wants to merge 6 commits into
ggml-org:masterfrom
Nas01010101:fix/mmid-duplicate-expert-ids-24591
Closed

Nas01010101 wants to merge 6 commits into
ggml-org:masterfrom
Nas01010101:fix/mmid-duplicate-expert-ids-24591

Conversation

@Nas01010101

@Nas01010101 Nas01010101 commented Jul 29, 2026 •

Copy link
Copy Markdown

Overview

Fixes #24591.

When a token's top-k list contains the same expert more than once, mul_mat_id on CUDA dropped or corrupted columns, which showed up as an illegal memory access in ggml_cuda_mul_mat_q.

This now builds on Johannes's fix from #30477 (kept as the first commit, with his authorship) and removes the n_expert_used it introduced:

  • mm_ids_helper: shared memory stays at one entry per token (n_tokens, as on master).Each token stores its first matching slot plus a count; duplicate slots are expanded only when writing out, using a prefix sum over the per-token counts. Without duplicates the write-out is the same as master

  • MMQ + MMF tiles: instead of launching ceil(ncols_max/J) column tiles per expert (mostly empty when ncols_max = ne12*n_expert_used), both kernels iterate over a packed tile index. A warp prefix sum over ceil(cnt_e/J) from expert_bounds maps tile -> (expert, jt), same idea as vLLM's moe_align_block_size. The host bound is ceil(n_cols/J) + min(n_experts, n_cols).

  • MMQ launch: when that bound has >= 90% wave efficiency, MoE uses the tiled launch like master (one block per tile, tiles past the last real one exit immediately). Otherwise it uses stream-k, which reads the real tile count on device before splitting work. Forcing stream-k for MoE was ~3% slower on gpt-oss, which is why the tiled path is kept.

  • MMF: the small-batch path loops over the rank of each match per token, so it handles duplicates and the return false; // FIXME is gone.

  • Tests: the #if 0 around the duplicate-id test-backend-ops cases is removed.

Additional information

RTX 3080 Laptop (sm_86, CUDA 12.4):

master #30477 this PR
test-backend-ops -o MUL_MAT_ID (dup tests on) 4 FAIL, then abort OK OK
full test-backend-ops 18551/18551
perf -o MUL_MAT_ID, time vs master (geomean, 132 cases) 1.00 1.21 0.99
OLMoE-1B-7B Q4_K_M pp512 / pp2048 (t/s) 8898 / 8621 6811 / 6846 8866 / 8574
gpt-oss-20b MXFP4 pp512 / pp2048 (t/s) 3559 / 3594 3108 / 3133 3594 / 3599
wikitext-2 PPL, 40 chunks: OLMoE / gpt-oss 11.8125 / 208.8274 11.8125 / 208.8274

I also ran MUL_MAT_ID and MUL_MAT with the MoE launch forced to tiled and forced to stream-k: both pass. Only tested on NVIDIA sm_86; the AMD path and 256-expert models are untested.

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: YES - I used Claude Opus 5.5 to help write some of the CUDA changes, tests and to run the benchmarks. I reviewed the code, I understand it, and all results come from real runs on my GPU.

@Nas01010101
Nas01010101 requested review from a team and ggerganov as code owners July 29, 2026 21:05
@github-actions github-actions Bot added testing Everything test related ggml changes relating to the ggml tensor library for machine learning CUDA Related to the CUDA backend labels Jul 29, 2026
@ggml-gh-bot

ggml-gh-bot Bot commented Jul 29, 2026

Copy link
Copy Markdown

Hi @Nas01010101, thanks for your contribution!

Per our contribution guidelines, the automated PR checker found the following issue(s) that need your attention:

  • Multiple open PRs from a new contributor: We limit new contributors (those without a previously merged PR) to 1 open PR at a time. You currently have 2 open PRs.

  • AI-generated content: While code is allowed to be generated by AI, please write the PR description and commit messages on your own without the help of AI.


Please note that maintainers reserve the right to make final decisions on PRs. If you believe there is a mistake, please comment below.

@am17an

am17an commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Initially I closed this PR because it seemed out of scope. But @ngxson's new changes require this fix, so opening it again.

@ngxson

ngxson commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

Related to #19182 where the model intentionally use duplicated expert, NOT an undesired behavior. CUDA is the only backend that doesn't support this case.

Measured: less than < 1% perf lost with this PR

llama-bench -m ../models/Qwen3.6-35B-A3B-UD-IQ2_M.gguf

master:
Device 0: NVIDIA GeForce RTX 5060 Ti, compute capability 12.0, VMM: yes, VRAM: 15849 MiB

model size params backend ngl test t/s
qwen35moe 35B.A3B IQ2_M - 2.7 bpw 10.72 GiB 34.66 B CUDA -1 pp512 2723.25 ± 12.76
qwen35moe 35B.A3B IQ2_M - 2.7 bpw 10.72 GiB 34.66 B CUDA -1 tg128 121.73 ± 0.40

PR:
Device 0: NVIDIA GeForce RTX 5060 Ti, compute capability 12.0, VMM: yes, VRAM: 15849 MiB

model size params backend ngl test t/s
qwen35moe 35B.A3B IQ2_M - 2.7 bpw 10.72 GiB 34.66 B CUDA -1 pp512 2700.81 ± 11.67
qwen35moe 35B.A3B IQ2_M - 2.7 bpw 10.72 GiB 34.66 B CUDA -1 tg128 121.66 ± 0.42

ngxson
ngxson previously approved these changes Aug 7, 2026

@ngxson ngxson left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@am17an feel free to merge when you're ready, thanks.

@am17an

am17an commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

@ggml-org/ggml-cuda any objections to this?

@am17an

am17an commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

/bot review

@ggml-gh-bot

ggml-gh-bot Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Automated code review

I've completed the static review. Here are my findings.

Code review: CUDA fix duplicate expert id compaction in mul_mat_id (#26294)

Checklists run: Scope/quick-reject gate, Security, ggml/backend, General. (No new model/arch, public API, server, or multimodal paths touched.)

The core algorithmic change is correct: replacing the per-token warp_reduce_any (0/1 "any lane matched") with an inclusive warp scan gives each duplicated use its own rank within the token (rank_in_token), and broadcasting the last lane's inclusive sum gives the correct per-token match count for the cross-token scan and the running it_compact increment. The shuffle idiom matches the existing cross-token scan a few lines below. The logic is sound for all specialized n_expert_used values (2/4/6/8/16/32), including the neu_padded=8 padding for the 6-expert case.

Blocking

(point 1) Shared-memory store buffer can overflow once duplicates are counted. launch_mm_ids_helper allocates dynamic shared memory of exactly n_tokens * sizeof(mm_ids_helper_store) (mmid.cu:147), and the whole compaction design is built on the invariant that a single expert is used at most once per token (so a per-expert compact count never exceeds n_tokens). The old buggy warp_reduce_any undercount happened to keep it_compact <= n_tokens, which masked this. Your fix makes it_compact correctly count every duplicate use, so a single expert selected more than n_tokens times now writes past the end of store:

  • write: store[it_compact + it_compact_add_lower + rank_in_token] (mmid.cu:98)
  • read-back: for (itc = ...; itc < it_compact; ...) store[itc] (mmid.cu:108)

This is reachable in exactly the degenerate-routing domain the PR targets: e.g. one expert that is the top pick for all n_tokens tokens plus a single duplicate on one token yields n_tokens + 1 entries -> off-by-one write beyond the block's dynamic shared-memory allocation. The new regression test (n_tokens=9, one duplicate) does not exercise this because the duplicated expert is hit only ~1-2 times, well under 9. Since the downstream global buffers (ids_dst_compact_dev, sized n_tokens*n_expert_used in mmf.cu:79) already handle the full slot count, the shared-mem store is the only buffer still assuming the no-duplicate invariant. This needs a concrete decision before merge: size store for the true per-expert maximum (and reconcile with smpbo limits), sanitize/dedupe the ids upstream, or document+enforce the invariant. The current state trades a dropped-entry corruption for a shared-memory OOB write.

Will slow the review

(point 2) The generic fallback path is still buggy. mm_ids_helper<0> (the default case in ggml_cuda_launch_mm_ids_helper, used for any n_expert_used not in {2,4,6,8,16,32}) still uses warp_reduce_any and writes only store[it_compact] per token (mmid.cu:54-58). It therefore retains the exact duplicate-drop bug this PR fixes for the specialized paths. Real models use values in the specialized set, so this is likely acceptable as a follow-up, but it should be acknowledged (either fix it symmetrically or add a comment noting the generic path assumes distinct ids).

(point 3) Test coverage gap. The new case covers only n_used=6 (specialized path). There's no case for the generic path, and none that would trigger the (point 1) overflow. At minimum, consider a small case with a popular expert plus a duplicate to guard the buffer bound; once the generic path is addressed, add a n_used outside {2,4,6,8,16,32} case too.

Nits

(point 4) duplicated_id is not included in test_mul_mat_id::vars() (test-backend-ops.cpp:4439), so the injected-duplicate case is indistinguishable from a normal Q8_0/144/6 case in failure logs. Add it to VARS_TO_STR8.

(point 5) The two new comments in mmid.cu are slightly verbose (they restate the scan mechanics). The first line ("A token can use the same expert more than once, so count how many times...") earns its place; the second ("The prefix sum gives each use of the expert its own slot, the last thread has the total for this token") mostly restates the code. Consider trimming the second.

(point 6) AI disclosure: the PR description discloses AI assistance and references an Assisted-by: trailer, which satisfies the AGENTS.md requirement. No Co-authored-by: present. Good.

This review was generated automatically by pi coding agent using zai-org/GLM-5.2. It may contain mistakes. Maintainers make the final call.

@ngxson
ngxson dismissed their stale review August 8, 2026 10:18

validated on #19182 , still not fixed the problem

@ORippler ORippler left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At the very least, we have to be consistent between templated and non-templated versions of mm_ids_helper. Beyond that, I don't understand when/why we would want to route a token to the same expert multiple times. In what models do we generate selected experts by means other than ggml_argsort_top_k? AI tells me it could be done in DSV4 (@am17an please confirm if this is a valid use-case)

@am17an

am17an commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

It's the longcat models I think

@ORippler

Copy link
Copy Markdown
Collaborator

Related to #19182 where the model intentionally use duplicated expert, NOT an undesired behavior. CUDA is the only backend that doesn't support this case.

Hmm I see. We can merge this one then once we are consistent between templated and non-templated versions of mm_ids_helper in the CUDA backend (@Nas01010101 please implement this + add an associated test to test-backend-ops)

@Nas01010101

Copy link
Copy Markdown
Author

Tested on RTX 3080 Laptop (CUDA 12.9). Found a third instance of the same bug: ggml_cuda_mul_mat_id's host-side sorted fallback had a break after the first matching slot, aborting at GGML_ASSERT(ids_to_sorted_host.size() == ne_get_rows). Fixed in 60fd1f1. With both fixes: 872/872 MUL_MAT_ID, 13571/13571 full suite on CUDA0.

Comment thread ggml/src/ggml-cuda/mmid.cu Resolved
Comment thread ggml/src/ggml-cuda/mmid.cu Resolved
@Nas01010101
Nas01010101 force-pushed the fix/mmid-duplicate-expert-ids-24591 branch from 60fd1f1 to f3ff969 Compare September 4, 2026 04:16

@am17an am17an 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.

@JohannesGaessler this PR fixes the currently failing CI. Can you take a look?

@JohannesGaessler

Copy link
Copy Markdown
Contributor

I had seen this PR in my backlog but at a glance it seemed overengineered. I'll take a look.

@JohannesGaessler

Copy link
Copy Markdown
Contributor

There are edge cases that cannot be fixed simply by modifying mmid.cu. The MMQ code implicitly assumes that each expert cannot occur more than once per token position via mmq_args::ncols_max.

@Nas01010101 Nas01010101 changed the title CUDA: fix duplicate expert id compaction in mul_mat_id (#24591) CUDA: support duplicate expert ids in mul_mat_id Oct 17, 2026
@Nas01010101

Copy link
Copy Markdown
Author

There are edge cases that cannot be fixed simply by modifying mmid.cu. The MMQ code implicitly assumes that each expert cannot occur more than once per token position via mmq_args::ncols_max.

Hi Johannes Thanks for looking into this. I tried fixing the two perf issues from #30477 on top of your commit:

  1. helper smem stays at n_tokens (one entry per token plus a count, duplicates expanded at write-out)
  2. MMQ/MMF only launch the tiles each expert actually needs (packed tile index instead of ceil(ncols_max/J) per expert) MMF handles duplicates too, so it doesn't need to be disabled. On a 3080 Laptop the dup tests pass, MUL_MAT_ID perf is 0.99x master (CUDA: fix duplicate expert IDs #30477: 1.21x), OLMoE/gpt-oss pp is at master speed, and PPL is identical. Details in the PR description.

Pushing it here. Feel free to fold whatever is useful into #30477 instead, I'm fine closing this one.

@Nas01010101
Nas01010101 force-pushed the fix/mmid-duplicate-expert-ids-24591 branch from f3ff969 to ef88eb1 Compare October 17, 2026 18:23
@JohannesGaessler

Copy link
Copy Markdown
Contributor

Let's close this PR then.

ArtomYuan added a commit to ArtomYuan/strix.cpp that referenced this pull request Oct 18, 2026
When a token's top-k list contains the same expert more than once,
mul_mat_id dropped or corrupted columns; on the quantized path this showed
up as an illegal memory access inside quantize_mmq_q8_1.

Ports the upstream fix (PR #26294, which builds on #30477):
- mm_ids_helper keeps shared memory at one entry per token and stores a
  first-match plus a count; duplicate slots are expanded at write-out via
  a prefix sum over per-token counts (no extra shared memory).
- MMQ/MMF tiles address columns through the packed-tile mapping instead
  of launching ceil(ncols_max/J) mostly-empty tiles per expert.
- The host fallback no longer breaks at the first match.

Two adaptations for this fork:
- GGML_USE_HIP: the new ntx <= 65535 assert guards the CUDA grid.y limit;
  ROCm accepts larger grids (a 65625-tile case is legal here).
- Rebased onto the ROCmFPX MMQ/MMF specializations.

Verification: MUL_MAT_ID 953/953 (was: GPU hang); full suite 18781/18785
(the 4 failures are the documented f16-KV deep-context precision edges,
same as stock); MUL_MAT rocmfp4 24/24, rocmfpx 61/61; dense end-to-end
pp2048 709.9 t/s (-1.5%, noise band), pp16384 610.1 (-0.6%), tg256 14.03
unchanged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CUDA Related to the CUDA backend ggml changes relating to the ggml tensor library for machine learning testing Everything test related

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Misc. bug: Passing non-unique ids to CUDA ggml_mul_mat_id() implementation results in crash

5 participants