Skip to content

Title: CUDA: few-row MMQ for MUL_MAT_ID - #32065

Merged
anujj merged 4 commits into
ggml-org:masterfrom
anujj:anujj/few-row-mmid
Nov 17, 2026
Merged

anujj merged 4 commits into
ggml-org:masterfrom
anujj:anujj/few-row-mmid

Conversation

@anujj

@anujj anujj commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Overview

Follow-up to #31533 (now in master).

This PR extends the few-row kernel of #31533 to MUL_MAT_ID (MoE expert mat-muls) for 2-24 tokens.

Note: I plan to also add the gate + up + GLU fusion to the few-row kernel, for dense and MoE (as MMQ does since #29948). This will increase the gain further.

Implementation

  • mul_mat_q_few gets a has_ids flag: a block computes one expert with up to 8 of its (token, slot) entries. For short K (e.g. K = 512) the warps split the rows instead of K.

  • quantize_mmq_few_id_q8_1 builds this expert/entry table in shared memory and quantizes src1 in the same kernel. No host sync, so CUDA graphs keep working.

  • ggml_cuda_mul_mat_id uses MMVQ, then few-row, then MMQ, as ggml_cuda_mul_mat does. Few-row starts after the MMVQ batch limit (9 tokens on Ada and Blackwell) and at 2 tokens on DGX Spark. At 9-24 tokens the expert gate/up stay on the fused MMQ; few-row gate/up + GLU fusion is the next PR.

Performance

GPUs tested:

  • RTX 5090

  • DGX Spark GB10

Speed per pass (llama-bench)

llama-bench -m <model> -p 576 -n 0 -ub 4,8,12,16,18,24 -r 10 (DGX Spark: -ub 2,4,8,12,16,18,24 -r 5), master (2d8a32502) vs this PR, 2 alternating rounds. Speedup = master ms per pass / PR ms per pass, medians (some Qwen3.6-35B-A3B repeats on the RTX 5090 are 5-12% slow in both builds).

Qwen3.6-35B-A3B Q4_K_M:

GPU 2 4 8 12 16 18 24
RTX 5090 0.998 1.004 1.072 1.079 1.062 1.055
DGX Spark 1.029 1.057 1.099 1.043 1.032 1.029 1.020

Qwen3-30B-A3B Q4_K_M (its Q4_K expert down has K = 768, not a whole number of stages, so it stays on MMQ):

GPU 2 4 8 12 16 18 24
RTX 5090 0.990 0.999 1.003 1.006 0.999 1.010
DGX Spark 1.071 1.119 1.216 1.030 1.027 1.026 1.026

Dense models do not change: Qwen3.8-27B UD-Q4_K_M with this PR is 0.993-1.008x of master on the RTX 5090.

Accuracy

Wikitext-2 test, 12 chunks of 512 tokens. Reference: master logits at batch 512 (MMQ). KLD (measured before the rebase, with master = #31533; the rebase changes no kernel used here):

GPU, model ubatch master this PR
DGX Spark, Qwen3.6-35B-A3B 2 0.00487 0.00447
4 0.00478 0.00466
8 0.00443 0.00463
DGX Spark, Qwen3-30B-A3B 2 0.00297 0.00309
4 0.00302 0.00314
8 0.00317 0.00285
RTX 5090, Qwen3.6-35B-A3B 16 0.00598 0.00607
24 0.00580 0.00576

Testing

  • test-backend-ops -o "MUL_MAT.*" (includes MUL_MAT_ID, MUL_MAT_ID_SHARED, MUL_MAT_ID_FUSION and MUL_MAT_FUSION): 5597/5597 on the RTX 5090 and DGX Spark, with GGML_CUDA_PDL=1 and 0.

  • New cases: 18 MUL_MAT_ID cases (8 types x 2 shapes: K = 2048 where the warps split K, and K = 512 where they split the rows, with more than 8 tokens per expert and unaligned experts; strided experts; 128 experts) and 1 MoE gate/up fusion case at 8 tokens.

Requirements

@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 Nov 11, 2026
@anujj
anujj force-pushed the anujj/few-row-mmid branch from a8cbbe5 to 501669e Compare November 13, 2026 12:02
@anujj
anujj marked this pull request as ready for review November 13, 2026 12:28
@anujj
anujj requested review from a team and ggerganov as code owners November 13, 2026 12:28
@am17an

am17an commented Nov 14, 2026

Copy link
Copy Markdown
Contributor

changes look ok, automated review below

Tested on an RTX PRO 6000 (sm_120) with Qwen3.5-35B-A3B Q8_0.

I didn't find any correctness problems:

  • npairs_max is a valid upper bound on the pairs the quantizer writes.
  • Out-of-range ids are skipped, the same way mm_ids_helper skips them.
  • The kernel calls the PDL sync before it reads the pairs.
  • The row-split path clamps its tail rows correctly.
  • The fusion and dispatch changes agree with the gate. MMVQ and shared-expert fusion are skipped only where few-row takes the op, and ggml_cuda_mul_mat_id_needs_sync returns false there.

Tests:

  • All 5597 MUL_MAT and MUL_MAT_ID cases in test-backend-ops pass, both with the default PDL setting and with GGML_CUDA_PDL=0.
  • compute-sanitizer memcheck, racecheck and synccheck report nothing on the new cases.
  • On this GPU the MUL_MAT_ID gate starts at 9 tokens, so the 2-8 token range that DGX Spark uses never runs here. To cover it I forced the gate down to 2 tokens locally. Everything still passes with PDL on and off, and the run includes 44 few-row MUL_MAT_ID launches.
  • Perplexity over 12 chunks is the same on both builds: 6.9890 at -ub 16 and 6.9805 at -ub 512. nsys shows the few-row MUL_MAT_ID kernel running for the down projection at -ub 16.

llama-bench -p 576 -n 0 -ub 4,8,12,16,18,24 -r 10, median of 3 interleaved runs:

ub master t/s PR t/s speedup
4 764.6 760.4 0.99
8 1272.3 1262.4 0.99
12 1481.3 1515.9 1.02
16 1797.4 1836.8 1.02
18 2007.9 2037.0 1.01
24 2405.8 2441.1 1.01

At 4 and 8 tokens MMVQ still runs, so those differences are noise. At 12-24 tokens the gain is smaller than the 5090 Q4_K_M numbers in the description, though this is a different quant. With GGML_CUDA_PDL=0 at -ub 16, the down projection takes about 2% more kernel time with the PR (few-row kernel plus its quantize, compared with MMQ plus its helpers), and total GPU time is unchanged. So on this GPU the end-to-end gain probably comes from fewer launches and better overlap, not from a faster kernel.

Smaller things:

  • The PR title starts with a stray "Title: ".
  • Off Spark, the MUL_MAT_ID gate (get_mmvq_mmid_max_batch + 1) applies to every GPU from Ampere through Blackwell, but the description only shows 5090 and Spark numbers. A quick check on an Ampere or Ada card would help.
  • CI hasn't run yet, so I haven't seen the HIP and MUSA builds. The new quantizer is compiled on HIP, though the gate never launches it there.

@anujj

anujj commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor Author

Adding @ORippler and @gaugarg-nv also

I want to extend the few-row MMQ kernels to support NVFP4 once this change is merged.

@am17an

am17an commented Nov 15, 2026

Copy link
Copy Markdown
Contributor

NVFP4 + FP8 both are needed I think.

@anujj

anujj commented Nov 15, 2026

Copy link
Copy Markdown
Contributor Author

yes, will cover both in the next PR

@anujj

anujj commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review, guys!

@anujj
anujj merged commit 8777c0c into ggml-org:master Nov 17, 2026
31 of 32 checks passed
gabe-l-hart added a commit to gabe-l-hart/llama.cpp that referenced this pull request Nov 17, 2026
* origin/master: (138 commits)
qwen4exp : fix graph reallocation from the n-gram table scale (ggml-org#32483)
server : return 400 when grammar and ignore_eos are on (ggml-org#32377)
ggml-cuda: disable quantized matvec fusion on all Pascal GPUs (ggml-org#32239)
Title: CUDA: few-row MMQ for MUL_MAT_ID (ggml-org#32065)
ui: turn the live markdown preview off by default (ggml-org#32469)
CUDA: use block reductions for whole-row pool_1d (ggml-org#31855)
ggml : decode F8_E4M3 to fp32 without ldexpf (ggml-org#32477)
llama : keep the k-pool layout prefix on sequence edits (ggml-org#32137)
vocab : speed up PLaMo-2/3 tokenizer table build (ggml-org#32249)
convert : fix FP8 qwen4exp checkpoints (n-gram table scale, block-scaled FP8) (ggml-org#32476)
ui: Llama UI design system: tokens, surfaces and fonts (ggml-org#32468)
mtmd: support Minimax-Music3 (ggml-org#32435)
chat: add tts_dict for kokoro G2P template (ggml-org#32397)
Rotate K/V read order for better L2 cache hit rates (ggml-org#32407)
ui: turn conversation tabs off by default (ggml-org#32402)
ui: move Llama Chat to SvelteKit 3 and its built-in service worker (ggml-org#32463)
qwen3next : apply output projection weight scale (ggml-org#32393)
cuda : raise shared mem limit only for the launched kernel (ggml-org#32392)
nix: expose a SYCL package (ggml-org#31066)
vulkan: disable flip Flash Attention shader on AMD Windows due to a driver bug (ggml-org#32415)
...
dzannotti added a commit to halo-box/strix-llama.cpp that referenced this pull request Nov 17, 2026
Upstream: ggml-org/llama.cpp 08a9b35..8777c0c (4 commits)

Conflicts:
- ggml/src/ggml-cuda/ggml-cuda.cu: kept the fork MMB routed path and added upstream ggml-org#32065's few-row MMQ for MUL_MAT_ID after it, as in the dense path. The few-row gate returns 0 on every non-NVIDIA device (ampere_mma_available), so MoE dispatch on gfx1151 is unchanged.
- ggml/src/ggml-cuda/quantize.cu: kept the fork quantize_mmq_q8_1_swiglu_cuda and took upstream's quantize_mmq_few_store helper after it; the fork function gets its closing brace back at the junction.

Assisted-by: Claude Opus 5.5
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YKmjzcT1LTvKtbw9EzBVGE
Annieren pushed a commit to Annieren/llama.cpp-upstream that referenced this pull request Nov 23, 2026
* CUDA: few-row MMQ for MUL_MAT_ID

* CUDA: few-row MMQ for MUL_MAT_ID from 2 tokens on DGX Spark

* CUDA: few-row MUL_MAT_ID: one launcher, tighter pair count, more tests

* CUDA: few-row MUL_MAT_ID: dispatch order MMVQ, few-row, MMQ and review fixes
bobvious added a commit to bobvious/llama.cpp that referenced this pull request Nov 25, 2026
- cherry-pick fork/greedy-fastpath-20261120 (da4ad8beb, ebcfb697e)
- fix review finding: refuse fast path when typ_p < 1 (can drop max);
  top-n-sigma verified max-preserving, stays eligible
- apply 0001 (few-row MMQ gate, ggml-org#31533/ggml-org#32065) + 0002 (revert ggml-org#32407)
  from runs/upstream-merge-v072-20261117/patches (0003 test-only,
  does not apply to b12706 mmq-few.cu: skipped)

Co-Authored-By: Claude Code <[email protected]>
amangupta-tether added a commit to tetherto/qvac-fabric-llm.cpp that referenced this pull request Nov 26, 2026
CUDA : few-row MMQ for MUL_MAT_ID and Inkling 2 expert rows (port of ggml-org#32065)
Nindaleth pushed a commit to Nindaleth/llama.cpp that referenced this pull request Nov 26, 2026
* CUDA: few-row MMQ for MUL_MAT_ID

* CUDA: few-row MMQ for MUL_MAT_ID from 2 tokens on DGX Spark

* CUDA: few-row MUL_MAT_ID: one launcher, tighter pair count, more tests

* CUDA: few-row MUL_MAT_ID: dispatch order MMVQ, few-row, MMQ and review fixes
amangupta-tether added a commit to tetherto/qvac-fabric-llm.cpp that referenced this pull request Nov 26, 2026
…ggml-org#32704 to temp-12032) (#568)

* ggml: bound views by the bytes their strides reach (ggml-org#31584)

* ggml: bound views by the bytes their strides reach

A view was checked against its source with the size of a contiguous
tensor of the same shape, computed before its strides were set. Views
whose rows overlap failed that check although they stay inside their
source, and views with wider strides passed it while reaching past
the end. The view functions now pass their strides to the tensor
constructor, which checks the bytes they actually reach, like
ggml_nbytes. The conv windows of delta_net are created with all their
rows at once instead of being widened after the check.

* ggml: assert that a strided view starts from contiguous elements

The view functions set nb[0] to the type size, so the source must have
contiguous elements along dim 0 for the view to read them.

(cherry picked from commit bbb02c9)

Backport note: prerequisite of the Inkling 2 port. build_conv_state_store
(next commit) writes the conv rollback slots through a view with
overlapping rows, which the old contiguous-size check rejects. The
delta-net-base.cpp hunk is not taken: fabric's delta-net writes its conv
snapshots with one copy per slot and never builds that widened view.

* graph: store the MTP conv snapshots of every recurrent model in one set_rows (ggml-org#31660)

* graph: store the conv state of every rollback arch in one set_rows

The rollback slots of the causal conv history were written with one
copy per slot in qwen4exp, glm5-next, kimi-k3, bailingmoe3, lfm and
mamba2, while delta_net already wrote them with a single set_rows.
build_conv_state_store now does this for all of them: one copy without
rollback, otherwise one set_rows of the overlapping windows into the
min(n, n_rs_seq + 1) slots a rollback can read.

The slot order {n_rs_seq, ..., 0} is computed once per graph and each
conv layer takes a view of its tail. Its size does not depend on the
ubatch, so the reserved graph covers every ubatch shape, and the graph
input that held it is gone.

A model that is not causal never rolls back, so the context clamps
n_rs_seq to 0 for it, like for an arch without rollback support.

* nits: compute the conv slot order in the graph and keep the n_head name of bailingmoe3

* graph: build the conv slot order in each conv layer

The slot order {K-1, ..., 0} of the conv state store was one tensor
shared by every conv layer of the graph, built on the device of the
first one, so each layer on another device copied the view of its
tail. Each conv layer now builds its own order next to its set_rows,
and llm_graph_input_rs no longer holds it.

(cherry picked from commit 040ce19)

Backport note: partial pick, prerequisite of the Inkling 2 port. Only the
new llm_graph_context::build_conv_state_store helper is taken (Inkling 2's
short convolutions call it). The conversion of the existing recurrent
models (delta-net, qwen4exp, glm5-next, kimi-k3, bailingmoe3, lfm, mamba),
the s_slot_rev input removal and the non-causal n_rs_seq clamp are left
out: fabric's recurrent state code (deferred GDN commit, ragged ubatches,
per-slot conv snapshots, no s_slot_rev) has diverged from upstream here, so
those hunks conflict and would change the graphs of the existing models.

* feat: add Inkling 2 support (text + vision) (ggml-org#32217)

* convert : add Inkling2 text GGUF conversion

Assisted-by: Codex

* llama : implement Inkling2 text inference

Assisted-by: Codex

* tests : cover Inkling2 text support

Assisted-by: Codex

* conversion : dequantize packed Inkling2 experts in row chunks

Decode per-layer NVFP4 and MXFP8 schemes, validate companions, and use stored scale shapes with a warning for the declared MXFP8 [32,32] grid. Reorder packed w13 rows and their scale rows together. Keep normal GGUF outtype selection and 3D expert tensors.

Stream 128 rows per expert through LazyChunkedTensor. Real w13 (384x4608x4608) needs a 2.25 MiB F32 chunk instead of a 30.375 GiB expanded layer. Real-shaped sparse probes peak below 5.8 MiB of Python/NumPy chunk allocations, plus 5.2 MiB of callback metadata: budget about 16 MiB per projection including mapped pages, excluding runtime, other tensors and OS cache. Full-model chunk metadata is roughly 370 MiB.

Packed synthetic GGUF weights match the independent pinned vLLM decode bit-for-bit. CPU prefill/decode logits remain within 3.1e-6 absolute error, with 100% argmax agreement. Float fixtures, original-name conversion and CPU architecture checks pass. Real checkpoint conversion remains untested.

Assisted-by: Codex

* convert : add Inkling2 vision mmproj support

Assisted-by: Codex

* mtmd : implement Inkling2 still-image encoder

Assisted-by: Codex

* inkling2 : scope image loading

Assisted-by: Codex

* inkling2 : enable flash attention with folded bias and sinks

Assisted-by: Codex

* cuda : route per-head flash attention masks through vec

Assisted-by: Codex

* mtmd : support Inkling2 temporal frame means

Assisted-by: Codex

* style : restore shared image comment

Assisted-by: Codex

* tests : enlarge Inkling2 context fixture

Assisted-by: Codex

* inkling2 : load per-layer expert feed-forward widths

Assisted-by: Codex

* tests : add Inkling2 Metal fusion baselines

Assisted-by: Codex

* inkling2 : group and align registry entries

Assisted-by: Fable

* convert : regenerate the Inkling2 tokenizer hash with the update script

Assisted-by: Fable

* conversion : revert the print_registered_models change

Assisted-by: Fable

* conversion : sort the Inkling2 model map entries

Assisted-by: Fable

* convert : map Inkling2 vision checkpoint names in the tensor table

Assisted-by: Fable

* convert : map Inkling2 text checkpoint names in the tensor table

Assisted-by: Fable

* tests : document the Inkling2 packed expert conversion test

Assisted-by: Fable

* tests : cover Inkling2 checkpoint and transformers tensor names

Assisted-by: Fable

* llama : place Inkling2 fields and list entries by file convention

Assisted-by: Fable

* gguf-py : align Inkling2 tensor mapping comments

Assisted-by: Fable

* mtmd : place Inkling2 entries by file convention

Assisted-by: Fable

* tests : place Inkling2 cases after the existing ones

Assisted-by: Fable

* cuda : index per-head flash attention masks in the tile and mma kernels

Assisted-by: Claude
Claude-Session: https://claude.ai/code/session_01GbYSza1yxgmTz8wdr6uV8Q

* inkling2 : project the relative bias before the gather, drop arch branches

Assisted-by: Claude
Claude-Session: https://claude.ai/code/session_01GbYSza1yxgmTz8wdr6uV8Q

* convert : require Inkling2 hparams, add inkling2 pre-tokenizer

Assisted-by: Claude
Claude-Session: https://claude.ai/code/session_01GbYSza1yxgmTz8wdr6uV8Q

* mtmd : cap Inkling2 image size, drop video frame averaging

Assisted-by: Claude
Claude-Session: https://claude.ai/code/session_01GbYSza1yxgmTz8wdr6uV8Q

* inkling2 : fix CI build, Meta device assert and Windows conversion test

Assisted-by: Claude

* tests : use the default sliding window for the Inkling2 test model

Assisted-by: Claude

* simplify mtmd part

* give _v arch for vision

* remove alpha channel handling, it should be a follow up

* explicit rule about audio + vision models

* add audio support

* rm audio

* rm gguf mtmd rope base

* address review comment

* nits

* do not normalize embd from mtmd

---------

Co-authored-by: Xuan Son Nguyen <[email protected]>
(cherry picked from commit 5c008e0)

Backport notes (temp-12032 conflict resolution):
- Adjacency conflicts with models upstream added after b12032 (ricursive,
  metis16, kimi-k31, chatterbox, ...): kept fabric's lines, added only the
  Inkling 2 lines.
- llama-graph build_attn: fabric reads the mask from .cnv (aliases .raw except
  for dflash); the new kq_mask parameter falls back to .cnv.
- llama-graph build_moe_ffn: expert_weights_norm_eps branch placed before
  fabric's training_ctx branch, so inference matches upstream.
- test-backend-ops: mask_heads appended after fabric's n_sparse_mask / scale /
  packed_window ctor arguments.
- tools/mtmd: temp-12032 predates the mtmd refactor (upstream 7d7f028), so
  the mtmd-graph.cpp / mtmd-model.cpp / mtmd-subcontext.cpp hunks are placed
  verbatim at the equivalent spots of clip.cpp (mtmd-impl.h -> clip-impl.h,
  mtmd-model.h -> clip-model.h). The README-dev.md line is dropped: it extends
  a "Structure" section that only exists after that refactor. API renames
  follow in a separate commit.

* fabric: adapt Inkling 2 to the temp-12032 graph and mtmd APIs

temp-12032 predates two upstream refactors that the Inkling 2 commit
builds on; pulling them in would touch 170+ and 90+ files, so the new
code is renamed to the pre-refactor API instead. No behaviour change.

- llm_graph_context still takes the model as a constructor argument
  (upstream e0f96a1 made it a member): graph(model, params) and
  make_unique<graph>(*this, params).
- mtmd is still clip-based (upstream 7d7f028 moved it to mtmd_*):
  mtmd_graph -> clip_graph, mtmd_layer -> clip_layer,
  mtmd_image_u8/f32 -> clip_image_u8/f32, MTMD_ALIGN -> CLIP_ALIGN,
  mtmd_format -> string_format, models.v.get() -> ctx_v, also in the new
  test-mtmd-impl case (mtmd_hparams / mtmd_image_size -> clip_*).
- test-backend-ops: fabric's test_flash_attn_ext takes n_sparse_mask,
  scale and packed_window where upstream has q_head_padding, so the new
  per-head-mask cases pass the defaults for those before mask_heads.
- mtmd-image.cpp: drop the trailing blank line left by the relocation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* chat: fix inkling 2 begin/end of image tokens placement (ggml-org#32294)

* chat: fix inkling 2 begin/end of image tokens placement

* add test

(cherry picked from commit dd099a6)

Backport notes (temp-12032 conflict resolution): chat.cpp keeps fabric's
thinking_forced_open block before the new split_media call; parsers.h keeps
fabric's workaround namespace; mtmd.cpp keeps the ctx_v argument of the
pre-refactor mtmd API.

* jinja: support json sort_keys=true (ggml-org#32366)

(cherry picked from commit e1925b3)

* chat : implement inkling parser (ggml-org#32381)

(cherry picked from commit 4ddf2b9)

Backport note (temp-12032 conflict resolution): chat.cpp keeps fabric's
thinking_forced_open block; only the split_media call is removed.

* convert: Fix inkling 2 mmproj conversion (ggml-org#32430)

(cherry picked from commit d998c67)

* llama: fixes for Inkling 2 attention mask (ggml-org#32429)

* llama : give Inkling2 its own relative-position attention input

The Inkling2 graph built its flash attention mask from the hybrid iswa
input and passed it to build_attn through a new kq_mask argument. That
argument let a caller pair its own dense mask with the kv_rows of
llm_graph_input_attn_kv_iswa, whose mask follows the per-sequence cell
lists whenever kv_rows is enabled.

Add llm_graph_input_attn_rel_pos instead. It owns dense KQ masks and the
query-to-cell distances, fills both from the same cells, and its
build_attn overload adds the per-head bias to its own mask and never
passes kv_rows. The iswa build_attn is back to its previous signature;
its body moves to build_attn_iswa_impl, which both overloads call.

Inkling2 now folds the per-query sink into the bias with and without
flash attention, so build_attn_mha no longer needs the per-query sink
path.

Assisted-By: Claude Opus 5.5 <[email protected]>

* inkling2 : make the expert weight scale and final logit softcap optional

Load both keys as optional and skip them when they are zero, as other
models do, instead of rejecting zero at load.

Assisted-By: Claude Opus 5.5 <[email protected]>

* llama : build kv_rows masks for the hybrid iswa memory

llm_graph_input_mem_hybrid_iswa checked its masks with
can_reuse_attn_mask, which expects kv_rows whenever they are enabled,
but built them dense. With a unified cache and flash attention the
check always failed, and hybrid iswa models (LFM2, LFM3, Inkling2)
never reused a graph. Build the masks with build_attn_inp_attn_mask,
like the plain iswa input.

Assisted-By: Claude Opus 5.5 <[email protected]>

* llama : make the relative-position input a hybrid iswa input

Address review: llm_graph_input_mem_hybrid_iswa_rel derives from
llm_graph_input_mem_hybrid_iswa and owns the attention and recurrent
inputs, so Inkling2 builds one memory input instead of two. Its
attention input is built with dense masks, can_reuse checks them as
dense, and its build_attn asserts that the mask has no kv_rows (TODO:
a kv_rows variant). build_attn_iswa_impl is now a static helper.

Assisted-By: Claude Opus 5.5 <[email protected]>

* llama : compose the hybrid iswa rel input, format inkling2

Address review: llm_graph_input_mem_hybrid_iswa_rel owns its attention
and recurrent inputs like the other composite inputs instead of deriving
from llm_graph_input_mem_hybrid_iswa.

Format src/models/inkling2.cpp like the other model sources: grouped
and aligned key and tensor loading, descriptive per-layer names, blank
lines and section comments between the steps, and cb() names for the
intermediate tensors. The graph is unchanged.

Assisted-By: Claude Opus 5.5 <[email protected]>
(cherry picked from commit 8af68d4)

Backport notes (temp-12032 conflict resolution):
- build_attn_iswa_impl keeps fabric's slicing of a dense mask that is wider
  than the K view; the iswa build_attn passes fabric's .cnv mask.
- inkling2.cpp keeps the (model, params) graph constructor of temp-12032.

* fabric: fill the Inkling 2 recurrent inputs with the fabric helpers

llm_graph_input_mem_hybrid_iswa_rel (upstream 8af68d4) copies the
upstream recurrent-state input code. On temp-12032 the recurrent inputs
also carry the deferred GDN copy indices, the moved-state range and the
ragged-ubatch offsets, so set_input() and can_reuse() do what fabric's
llm_graph_input_mem_hybrid_iswa does: llm_graph_set_input_rs() and the
moved-range / in-place / ragged checks. Same as the non-rel hybrid iswa
input; no change for upstream-shaped batches.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* model : load ffn_gate_up_exps scales (ggml-org#32657)

* model: load `ffn_gate_up_exps` scales

The generic scale pass loads per-expert scales for ffn_gate_exps,
ffn_up_exps and ffn_down_exps but not for the merged ffn_gate_up_exps.
Load ~ffn_gate_up_exps_s there~ and expose it as ffn_up_exps_s ~when the layer
has no separate up tensor,~ since build_moe_ffn applies up_exps_s to the
merged gate_up output. Inkling 2 now passes the expert scales to
build_moe_ffn like the other MoE models.

* Update src/llama-model.cpp

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* Update src/llama-model.h

Co-authored-by: Sigbjørn Skjæret <[email protected]>

---------

Co-authored-by: Sigbjørn Skjæret <[email protected]>
(cherry picked from commit a1f4222)

* model : Inkling 2 Mini (ggml-org#32694)

* Conversion

* Separate model_type

* Add gate_rank to allow building from metadata while testing

* Base model

* Loop graph

* Support the new is_varloop attribute

* Adopt naming scheme from ggml-org#32588

* Rename to varying

(cherry picked from commit 29b52d3)

Backport notes (temp-12032 conflict resolution): adjacency conflicts with
models upstream added after b12032 (domyn-edge, metis16, zaya1, kokoro):
kept fabric's lines, added only the Inkling 2 Mini lines. The graph
constructor is adapted to the temp-12032 API in the next commit.

* fabric: adapt the Inkling 2 Mini graphs to the temp-12032 graph API

Upstream 29b52d3 splits the Inkling 2 graph into build_inputs(),
build_layer() and build_output() members that read `model`, which
upstream llm_graph_context holds since e0f96a1. temp-12032 still
passes the model to the graph constructor, so the Inkling 2 graph keeps
it in a `model` member (as fabric's bailingmoe3 graph does) and the
Inkling 2 / Inkling 2 loop constructors and build_arch_graph() pass it
through. No behaviour change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* model : inkling2_loop share the loop slots after the scale pass (ggml-org#32704)

The loop slots copied the physical layers at the end of load_arch_tensors,
before the generic pass attaches the optional .scale tensors, so the later
passes through the core ran NVFP4 experts without their per-expert scales.
Add an optional post_arch_tensors hook that runs after the scale pass and
share the slots there.

(cherry picked from commit 690b87d)

* CUDA : fused row L2 clip for Inkling 2

Inkling 2 clips the rows of Q, K and the relative-position queries to an
L2 norm with 8 or 9 ops (the optional per-channel scale MUL, SQR, SUM_ROWS,
SQRT, SCALE, FILL, DIV, CLAMP, MUL), three times per layer visit: on
Inkling 2 Mini that is 144 chains and about 1250 small kernels per token.
ggml_cuda_try_fuse now runs such a chain as one kernel (one warp per row),
and the NVRTC fusion planner leaves the chains to it.

test-backend-ops: L2_CLIP cases with the Q, K and relative-query shapes.

Assisted-by: Claude Opus 5.5

* CUDA : L2 clip fusion skips in-place intermediates, x may alias dst

An in-place node inside the chain changes what the graph computes: with
ggml_fill_inplace the FILL overwrites the norm before the DIV reads it, so
the graph gives x * clamp(1) while the kernel gave the clipped rows. The
matcher now rejects the chain when any intermediate node is in place.

The output may be x itself (the last MUL in place), so x is no longer
__restrict__ in the kernel.

test-backend-ops gets an in-place FILL case, which must not fuse (it failed
with the fusion before), and a case whose output is written over the input.

Assisted-by: Claude Opus 5.5

* Merge pull request #573 from tetherto/gb10-moe-mmq-temp-12032

CUDA : MMQ for MoE batches that pick many experts on DGX Spark

* Merge pull request #579 from tetherto/inkling2-fewrow-moe-temp-12032

CUDA : few-row MMQ for MUL_MAT_ID and Inkling 2 expert rows (port of ggml-org#32065)

* model : Inkling 2 Mini mix() weighted sum with the scores as src0 (port of ggml-org#32855) (#581)

* model : Inkling 2 Mini mix() weighted sum with the scores as src0

The weighted sum over the depth states has K = # of states so the old operand order ran one small mat-vec per token. Putting scores first makes n_embd the long dimension and speeds up prefill by 14-18% on MI300X and 25-37% on B200.

(cherry picked from commit 357a9ee)

* model : keep the old mix() operand order when the model runs on the CPU

The scores as src0 make n_embd the long dimension of the weighted sum, which
is faster on GPUs, but on the CPU the subgraph took 1.5-1.9x as long (review
of this PR, Core Ultra 7 155H). When no layer is offloaded and the output is
on the CPU, mix() builds the former graph again: one mat-vec per token with
the states as src0.

A partly offloaded model keeps the swap everywhere. Choosing per layer was
slower than both orders with 12 of 24 layers on the GPU (DGX Spark: pp512
487 t/s against 507 with the old order and 536 with the swap), as the loop
slots and the physical layers whose weights they share can sit on different
devices.

Assisted-by: Claude Opus 5.5

---------

Co-authored-by: Eddie Zhou <[email protected]>

* ggml-backend, llama : copy shared MoE weights again for each split that reads them (#588)

With op offload, llama's copy callback uploads only the experts that the ids
of the split's first MUL_MAT_ID select. The scheduler lists a host weight as
an input only of the first split that reads it on a backend, and later
splits reuse that copy. When several MUL_MAT_IDs share an expert weight
(Inkling 2 runs its core layers again in later passes, each with its own
routing), the later ones read experts that were never uploaded: any partial
offload of Inkling 2 Mini gave NaN perplexity, also on upstream master.

The scheduler now lists such a weight again for every later split that reads
it as src0 of a MUL_MAT_ID while a copy callback is set, and the callback
keeps track of the experts it uploaded in the current graph compute, so a
later split uploads only the experts that are still missing.

Assisted-by: Claude Opus 5.5

* ci : HIP VGPR check ignores the flash attention kernels under their new signature

ggml-org#32429 (Inkling 2 attention mask) widened the mask's head stride nb32 of the
flash attention kernels from int32 to int64, which changes their mangled
names from ...iiiiil to ...iiiill. The 88 flash attention kernels the check
already ignores no longer matched, so ubuntu-22-hip-quality-check reported
31 known gfx908 spills on #568, every one an entry of the list under the old
signature. The entries now use the new signature, as upstream's copy of the
script does.

Assisted-by: Claude Opus 5.5

* ggml-webgpu : flash attention does not support a mask per head

ggml-org#32429 lets the flash attention mask carry a plane per head or head group
(mask->ne[2] > 1, broadcast over heads like ne[3] over sequences) for Inkling
2's relative-position bias, and test-backend-ops gained mask_heads cases. The
WebGPU shaders read one mask plane per sequence, so they applied head 0's plane
to every head: all 50 FLASH_ATTN_EXT cases with mask_heads 2, 4 or 8 failed on
gpu-webgpu-apple and gpu-webgpu-nvidia, and inkling2_loop missed the
test-llama-archs tolerance on webgpu-nvidia (1.08e-4). supports_op now declines
such masks, so the op runs on another backend.

Assisted-by: Claude Opus 5.5

* tests : re-record the Metal fusion baseline for the Inkling 2 port

The metal job failed test-fusion with 8 rows on #568:

- ggml-org#32657 creates ffn_gate_up_exps.scale (as ffn_up_exps_s) for layers with
  merged gate/up experts. test-llama-archs builds its models with every
  optional tensor, so the generated cohere2moe, hy_v3, qwen35moe, qwen3next
  and qwen4exp models now carry the scale and build_moe_ffn multiplies the
  merged MUL_MAT_ID output by it. The Metal MUL_MAT_ID+GLU decode fusion
  only matches MUL_MAT_ID -> VIEW -> VIEW -> GLU, and silu(s*g)*(s*u) cannot
  be folded, so those 5 rows no longer occur. GGUFs without the optional
  scale build the old graph and keep the fusion; models with it are NVFP4,
  which the fusion does not take anyway.
- The inkling2 rows were recorded on a tree with a Metal top-k fusion that
  #568 does not have; the same scale pass adds MUL_MAT_ID+MUL for Inkling 2.

Re-recorded on the M3 Ultra with the CI flags: 534 ok, 0 failed on #568's
head and on #568 merged with the current temp-12032.

Assisted-by: Claude Opus 5.5

---------

Co-authored-by: Pascal <[email protected]>
Co-authored-by: Piotr Wilkin (ilintar) <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Xuan-Son Nguyen <[email protected]>
Co-authored-by: Aldehir Rojas <[email protected]>
Co-authored-by: Bartowski <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: Sigbjørn Skjæret <[email protected]>
Co-authored-by: Pedro Cuenca <[email protected]>
Co-authored-by: Aman Gupta <[email protected]>
Co-authored-by: Eddie Zhou <[email protected]>
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.

4 participants