Skip to content

vulkan: optimize expert selection in topk_moe - #33170

Open
Winamin wants to merge 5 commits into
ggml-org:masterfrom
Winamin:master
Open

Winamin wants to merge 5 commits into
ggml-org:masterfrom
Winamin:master

Conversation

@Winamin

@Winamin Winamin commented Nov 27, 2026 •

Copy link
Copy Markdown

Overview

When selecting a small number of experts, the Kth score is found with a subgroup bitonic sort. Candidates that can reach it are shortlisted, and the shortlist is then sorted to pick the winners. Ties are broken by ascending expert ID. Weights follow their experts through the shortlist; ranking uses score + bias when a bias is present, while the emitted weight is the unbiased score.

Fast path conditions:

  1. Scores are finite.
  2. The expert field size is a power of two, between 32 and 1024.
  3. K is between 4 and the subgroup width (32).
  4. At least K and at most one subgroup of candidates reach the Kth score.

The sort loops are unrolled over the 32-lane subgroup. Inputs that do not meet these conditions fall back to the existing round-robin selection path. The regular Top-K path is unchanged: each round first selects the winning expert by score and ID, then reads its weight once within the subgroup.

Additional information

The measurement method is the time cost of a single call of the independent Vulkan topk_moe shader.

Experts / K RTX 5060 Ti, upstream → current AMD iGPU 2-CU, upstream → current
64 / 8 2.54 → 2.43 49.48 → 42.53
288 / 8 13.20 → 4.84 132.60 → 107.18
384 / 6 15.66 → 4.94 153.86 → 97.87
512 / 8 4.32 → 4.44 87.88 → 115.12
896 / 16 123.15 → 17.09 1097.69 → 262.85
1024 / 16 17.96 → 8.98 227.93 → 278.15

Requirements

@Winamin
Winamin requested a review from a team as a code owner November 27, 2026 04:59
@github-actions github-actions Bot added Vulkan Issues specific to the Vulkan backend ggml changes relating to the ggml tensor library for machine learning labels Nov 27, 2026
@0cc4m

0cc4m commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

Please undo all the reformatting, leave only actual changes. Stick to repo code style.

@Winamin

Winamin commented Nov 27, 2026

Copy link
Copy Markdown
Author

Please undo all the reformatting, leave only actual changes. Stick to repo code style.

Done.

@jeffbolznv

Copy link
Copy Markdown
Contributor

Which models benefit from this?

@Winamin

Winamin commented Nov 27, 2026 •

Copy link
Copy Markdown
Author

Such as Kimi K3 (top-16) directly hits the Bitonic Sort fast path. Non-power-of-2 models benefit from the regular Top-K path via:

· Unrolled static indices: prevent compiler register spilling to Local Memory.
· Minimal shuffle (score/id only): reduce register pressure and branch divergence.
· Single weight fetch: extract the winner's weight once post-reduction.

@jeffbolznv

Copy link
Copy Markdown
Contributor

Codex tells me that Kimi K3 would not hit the new fast paths. Can you help explain the discrepancy?

Any idea why the Radeon timings are so slow? I've never seen this op be very expensive in any of the models I've run.

@0cc4m

0cc4m commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

"AMD Radeon Graphics" suggests a weaker iGPU, but doesn't say which one. @Winamin What CPU is it?

@Winamin

Winamin commented Nov 27, 2026

Copy link
Copy Markdown
Author

Currently, Kimi K3 is rejected at the code level because K != N (896 experts). The current check is K == N. However, the current acceleration is supported, it's just that there is a problem in the code I wrote. Also, the current AMD test is on a 9600X iGPU.

@0cc4m

0cc4m commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

Yeah, that's a 2-CU minimal desktop iGPU, so slow is expected.

@Winamin

Winamin commented Nov 27, 2026

Copy link
Copy Markdown
Author

Currently, Kimi K3 is rejected at the code level because K != N (896 experts). The current check is K == N. However, the current acceleration is supported, it's just that there is a problem in the code I wrote. Also, the current AMD test is on a 9600X iGPU.

What I mean is the sorting algorithm can do this. The current guard blocks this case outright. Supporting models like Kimi K3 requires a top-K variant. This variant adds no extra cost and may even be lighter than the current path, as we avoid the repeated O(K·N) reduction loop. @jeffbolznv

When selecting a small number of experts with a 32-lane subgroup and a power-of-two expert field of up to 1024, find the Kth score with a subgroup sort, shortlist the candidates that can reach it, then sort the shortlist to pick the winners. Fall back to the reduction loop when scores are non-finite or the shortlist does not fit in a subgroup.

For the remaining cases, pick the next expert first, then fetch its weight once instead of carrying it through every reduction step.
@Winamin Winamin changed the title vulkan: optimize full expert selection in topk_moe vulkan: optimize expert selection in topk_moe Nov 27, 2026
@Winamin

Winamin commented Nov 27, 2026

Copy link
Copy Markdown
Author
image

@jeffbolznv Updated.The 896/16 config (Kimi K3's routing shape) now hits the fast path: −94% vs upstream 9d6f04f — synthetic shader benchmark, not a Kimi K3 model run.

The measurement method is a single call to the Vulkan topk_moe shader time, 512 tokens/dispatch, RTX 5060 Ti, 32-lane. 82 configs, 0 mismatches. Negative = faster.
384/6 −71%, 288/8 −65%, 512/8 −26%.
Small K (N≤128, K≤4) regresses 7–10% from the added branch; routing is ~0.13% of model time.

Comment on lines +139 to +141
// The Kth lane maximum is a lower bound for the Kth expert.
best = sort_expert_lanes(best, lane);
const uvec3 cutoff = subgroupShuffle(best, n_expert_used - 1);

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

The Kth lane maximum is a lower bound for the Kth expert. Sorting the 32 lane maxima gives a cutoff; candidates below it are dropped before the final sort. This replaces the O(K·N) repeated reduction with one O(N) scan plus two subgroup sorts.

@7eks

7eks commented Nov 29, 2026

Copy link
Copy Markdown

On RDNA3 with RADV the new fast path never runs. The pipeline gets WARP_SIZE = device->subgroup_size, which is 64 there, so the WARP_SIZE == 32 check is always false. Inkling 2 Mini (128 experts, top-8) on a 7900 XTX gives output identical to master (KLD 0) and the same tg (51.2 vs 51.2 t/s). With RADV_PERFTEST=cswave32 the reported subgroup size is still 64, so it doesn't help either.

ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][use_push], "topk_moe_f32_"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 4, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<<i, use_push}, 1, true, true, device->subgroup_size);

if (WARP_SIZE == 32 && n_experts_spec <= 1024 && n_expert_used >= WARP_SIZE / 4 && n_expert_used <= WARP_SIZE / 2) {

RDNA has subgroup size control with minSubgroupSize 32, and the backend already asks for wave32 on AMD in a few places, for example for the coopmat1 flash attention:

// RDNA3.5 preferred wave32 here
const bool cm1_use_wave32 = device->vendor_id == VK_VENDOR_ID_AMD &&
device->subgroup_size_control &&
device->subgroup_min_size <= 32 && device->subgroup_max_size >= 32;
const uint32_t cm1_sg = cm1_use_wave32 ? 32 : device->subgroup_size;

Creating the topk_moe pipeline with a required subgroup size of 32 when that is available might be enough to get the fast path on AMD. I can test it on the XTX if you push it.

Written with Claude Opus 5.5

@Winamin

Winamin commented Nov 30, 2026

Copy link
Copy Markdown
Author

I've pushed a new commit to explicitly request minSubgroupSize = 32 for the topk_moe pipeline.

Commit link: 510d4b0

This should finally allow the Bitonic Sort fast path to trigger on your RDNA3 setup with RADV. @7eks, ready for your 7900 XTX test whenever you are.

@7eks

7eks commented Nov 30, 2026

Copy link
Copy Markdown

Thanks for the quick update. Tested 3d525e2 merged onto master 779b413 on the 7900 XTX (RADV, Mesa 26.2.5). The wave32 pipeline is used now and the sort path runs on RDNA3. Results are correct:

  • test-backend-ops TOPK_MOE passes on the XTX and on a 780M iGPU. I added local cases for 64/128/256/512/1024 experts with top-8/12/16 at 1, 22 and 513 rows, and all 1364 cases pass in five runs with fresh random data.
  • A GGML_VULKAN_CHECK_RESULTS build, extended to also compare the selected ids, matches the CPU for both ids and weights in every layer of gemma-4-26B-A4B (128 experts, top-8), for prompt and decode rows.
  • KLD against master is at the noise floor of each model. Inkling 2 Mini (128 experts, sigmoid + bias, with vulkan: update topk_moe to handle bias rather than clamp #32957 stacked so it fuses) gives 0.0020, against 0.0021 for master at -ub 256 vs 512. K2-Horizon 36B-A4B (100 experts, so it takes the fallback path) gives 0.0094, against 0.0103. Qwen3.8-Flash-Next Q2_0 (512 experts, top-10, the sort path's own range) gives 0.0064, against 0.0069.

No speed change on this card. On Gemma 4, decode topk_moe is 3.55 us per call before and after. At pp512 the call goes from 3.8 to 4.4 us, and with the sort path disabled it is back at 3.8 us. End to end it's flat. Gemma 4 tg128 is 135.8 vs 135.3 t/s. K2-Horizon is 103.4 vs 103.8 tg128 and 2679 vs 2679 pp512. Qwen3.8-Flash-Next, with half of its experts offloaded to the iGPU, is 20.2 vs 20.25 tg64, and its topk_moe call is 22.1 vs 22.2 us.

Written with Claude Opus 5.5

@0cc4m

0cc4m commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

You put benchmark numbers for cases > 512 which will never currently fuse in the Vulkan backend, because num_topk_moe_pipelines is still 10. That's rather misleading, I assume you tested outside the backend?

@Winamin

Winamin commented Dec 2, 2026

Copy link
Copy Markdown
Author

In the current PR commit, the expert count ( n_experts_spec ) is fetched directly from the backend via  constant_id , ensuring full compatibility with the existing pipeline limits.

This benchmark measures the maximum capability of the operator, targeting the scenario where 16 experts are selected at a time. For models within the backend pipeline limits and with fewer than 512 experts, the actual gains per operator remain substantial.

@Winamin

Winamin commented Dec 2, 2026

Copy link
Copy Markdown
Author

Baseline commit 01d5774
PR commit 8d3676d

This table reports a standalone Vulkan microbenchmark of the fused Top-K MoE shader. Both versions receive identical synthetic FP32 router logits and, where applicable, identical routing biases. Each case uses the model's expert count, K, gating function, and normalization settings. The token count is the number of rows processed in one dispatch.

Each pair runs both shaders, with the order alternating between pairs. Vulkan GPU timestamps bracket a block of repeated dispatches, including the compute barrier after each dispatch. The elapsed time is divided by the number of dispatches. Both GPUs used 64 dispatches per block, with 16 warmup pairs and 49 measured pairs. For this benchmark, both commits were run with Wave32 on both GPUs.

Each cell shows the median dispatch time as baseline -> PR, followed by the reduction in parentheses. The reduction is 100 * (1 - PR median / baseline median).

RTX 5060 Ti

Routing configuration Experts K 512 tokens 2048 tokens
gpt-oss-20b 32 4 1.933 -> 1.621 us (16.1%) 4.287 -> 2.796 us (34.8%)
gpt-oss-120b 128 4 2.042 -> 1.834 us (10.2%) 4.516 -> 3.747 us (17.0%)
MiniMax-M3 128 4 0.997 -> 0.807 us (19.1%) 3.289 -> 2.723 us (17.2%)
Nemotron 3 Nano 128 6 1.246 -> 1.004 us (19.4%) 4.563 -> 3.372 us (26.1%)
DeepSeek-V4-Flash 256 6 3.531 -> 2.817 us (20.2%) 8.672 -> 7.816 us (9.9%)
DeepSeek-V4.1-Flash 384 6 12.505 -> 3.388 us (72.9%) 48.340 -> 12.643 us (73.8%)
Qwen3.5-35B-A3B 256 8 3.845 -> 2.692 us (30.0%) 9.547 -> 5.995 us (37.2%)
GLM-5.2 256 8 3.838 -> 2.603 us (32.2%) 9.355 -> 5.635 us (39.8%)
GLM-5.3-Flash 288 8 15.589 -> 4.225 us (72.9%) 43.410 -> 9.876 us (77.2%)
Step-3.7-Flash 288 8 11.216 -> 2.629 us (76.6%) 43.401 -> 9.869 us (77.3%)
Qwen3-Next-80B-A3B 512 10 3.488 -> 2.112 us (39.4%) 13.131 -> 8.021 us (38.9%)
Tencent Hy4-Flash 512 16 5.115 -> 2.116 us (58.6%) 19.639 -> 7.995 us (59.3%)

Ryzen 5 9600X Radeon iGPU, Wave32 for both commits

Routing configuration Experts K 512 tokens 2048 tokens
gpt-oss-20b 32 4 26.446 -> 17.471 us (33.9%) 98.776 -> 62.869 us (36.4%)
gpt-oss-120b 128 4 32.101 -> 25.398 us (20.9%) 122.206 -> 95.309 us (22.0%)
MiniMax-M3 128 4 30.603 -> 23.876 us (22.0%) 115.279 -> 88.329 us (23.4%)
Nemotron 3 Nano 128 6 42.546 -> 31.439 us (26.1%) 162.749 -> 118.049 us (27.5%)
DeepSeek-V4-Flash 256 6 63.973 -> 53.946 us (15.7%) 249.180 -> 208.961 us (16.1%)
DeepSeek-V4.1-Flash 384 6 158.899 -> 109.208 us (31.3%) 610.176 -> 424.697 us (30.4%)
Qwen3.5-35B-A3B 256 8 70.078 -> 35.868 us (48.8%) 272.736 -> 135.484 us (50.3%)
GLM-5.2 256 8 70.294 -> 37.304 us (46.9%) 272.897 -> 131.653 us (51.8%)
GLM-5.3-Flash 288 8 144.961 -> 92.797 us (36.0%) 557.360 -> 358.215 us (35.7%)
Step-3.7-Flash 288 8 145.095 -> 92.906 us (36.0%) 557.493 -> 358.544 us (35.7%)
Qwen3-Next-80B-A3B 512 10 101.064 -> 74.237 us (26.5%) 394.941 -> 286.478 us (27.5%)
Tencent Hy4-Flash 512 16 151.581 -> 75.052 us (50.5%) 592.847 -> 289.894 us (51.1%)

Written with Codex

@jeffbolznv

Copy link
Copy Markdown
Contributor

This seems like a lot of complexity for a fusion that I haven't seen cost a lot in absolute time on real models. Do you have any real end-to-end perf data?

@0cc4m

0cc4m commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

I did already test end-to-end too and saw no difference.

@Winamin

Winamin commented Dec 2, 2026 •

Copy link
Copy Markdown
Author

I can only say that this part does not have much impact on end-to-end, but the improvement is steady.

@Winamin

Winamin commented Dec 2, 2026

Copy link
Copy Markdown
Author

In the OLMoE-1B-7B-0924-Instruct, it's more about improving low-end devices

GPU Test Baseline (tok/s) PR (tok/s) Paired change PR faster
RTX 5060 Ti pp2048 12,185.13 12,291.28 +0.35% 3/6
RTX 5060 Ti tg128 343.54 344.28 +0.16% 4/6
Ryzen 5 9600X Radeon iGPU pp2048 191.77 192.24 +0.17% 6/6
Ryzen 5 9600X Radeon iGPU tg128 34.87 35.14 +0.85% 5/6

Each card alternated running 6 sets of A/B

@Winamin

Winamin commented Dec 2, 2026 •

Copy link
Copy Markdown
Author

I believe this tradeoff is acceptable. We get consistent routing kernel speedups, at the cost of substantial additional complexity.

@Winamin

Winamin commented Dec 3, 2026

Copy link
Copy Markdown
Author

This PR optimizes fused Vulkan Top-K MoE dispatch while keeping the pipeline limit at 10. Shader microbenchmarks show substantial gains for large-expert prefill, while full-model gains remain small.

Model: Qwen3.5-35B-A3B Q3_K_S, 256 experts, K=8, all 41 layers GPU-offloaded. Each case used a separate llama-bench process with -r 1 and 6 alternating A/B pairs. Baseline: 01d5774; PR: 8d3676d.

The small end-to-end changes are consistent with the measured Top-K share of GPU time: 0.04–0.05% at prefill and 0.36–0.42% at TG128 on RTX 5060 Ti. On the Radeon iGPU, the baseline uses Wave64 and the PR uses Wave32, reducing the share from 0.14–0.21% to 0.01–0.02% at prefill and from 0.72% to 0.19% at TG128.

GPU pp512 pp2048 tg128
RTX 5060 Ti -0.25% +0.37% +0.62%
Radeon 9600X iGPU +0.27% +0.12% +0.54%

Written with Codex


So the small end-to-end improvement is expected. Top-k routing accounts for only a small portion of total inference time, and we are close to the practical limit with this optimization.
@0cc4m

Replace the top8, shortlist sort and full sort paths and the uvec3 bitonic
helpers with one integer key shortlist path plus a single argmax loop for the
cases it rejects. The shortlist is sorted with a lane bitonic sort on packed
keys.

Output is unchanged (TOPK_MOE passes on RTX 5060 Ti and on a Radeon 9600X
iGPU) and timings are equal or better for most expert/k setups.
@Winamin

Winamin commented Dec 3, 2026 •

Copy link
Copy Markdown
Author

9409bb5d3

Mechanism: build order-preserving integer keys from the (optionally biased) scores, take the k-th largest lane maximum as a cutoff, compact experts at or above it into shared memory, then sort the shortlist with a lane bitonic sort on packed key + inverted slot so equal scores keep the lower expert ID.

One argmax loop remains for k < 4, k > 32, rows where the shortlist does not fit in one warp, and cases where adjacent packed score keys collide. Padding experts get key 0 and never pass the cutoff. The shortlist path needs wave32, which the pipeline already requests for this shader.

vs master: +125 / -92 across the two files.

vs the previous commit: 496 → 252 lines. The top8 path, separate shortlist sort, full sort, and uvec3 bitonic helpers are gone.

Performance at 512 experts vs the previous commit: 26% faster across k = 1 to 64. k=8 is the only cell that goes the other way (+9%), where the old top8 shortcut was cheaper.

Performance at 512 experts vs master: 27% faster across the same k range. Only k=1 is slower (+14%), and that cell is dispatch bound.

TOPK_MOE passes on both an RTX 5060 Ti and a 9600X iGPU.

@Winamin

Winamin commented Dec 3, 2026

Copy link
Copy Markdown
Author

Could you both take another look at the latest version when you have time? thanks! @jeffbolznv @0cc4m

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

ggml changes relating to the ggml tensor library for machine learning Vulkan Issues specific to the Vulkan backend

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants