Skip to content

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

Merged
ngxson merged 42 commits into
masterfrom
pwilkin/inkling2
Nov 14, 2026
Merged

ngxson merged 42 commits into
masterfrom
pwilkin/inkling2

Conversation

@pwilkin

@pwilkin pwilkin commented Nov 13, 2026

Copy link
Copy Markdown
Member

Overview

This adds pure Inkling 2 support (conversion + model), without the DSpark speculator that will be a separate PR stacked on top of this.

Additional information

No operator changes were needed in this implementation.

Requirements

Comment thread src/llama-kv-cache.cpp Resolved
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
Comment thread ggml/src/ggml-cuda/fattn.cu Resolved
Comment thread tests/test_conversion_fp8.py Resolved
@pwilkin
pwilkin added this pull request to stack #32222 November 13, 2026 16:55
@github-actions github-actions Bot added model Model specific testing Everything test related ggml changes relating to the ggml tensor library for machine learning mtmd Related to multimodal functionality (video/image/audio) labels Nov 13, 2026
ByCzech pushed a commit to ByCzech/llama.cpp that referenced this pull request Nov 21, 2026
Backport ggml-org ggml-org#32217, ggml-org#32429, ggml-org#32657, ggml-org#32694 and the merged ggml-org#32704 scale-sharing fix onto b12359.2. Include required sorted JSON (ggml-org#32366), image block placement (ggml-org#32294) and the dedicated Inkling chat parser (ggml-org#32381). Keep the existing graph budget implementation and add a three-pass scaled-expert fixture.

Assisted-by: Codex
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Nov 21, 2026
… derived kq mask

Re-based onto a691b23.  Upstream ggml-org#29510 (flash_attn_ext_rows, the kv_rows unified-KV
form) and the llm_attn_mask refactor meet this block in 9 files / 48 hunks.

Resolutions worth knowing:
- the kernel signatures carry both parameters (upstream's `KV_rows` then our
  `kq_blocks`); the loaders take upstream's kv_rows `indices` with our native-KV
  arguments; the C-tile sizing keeps the delivery's fp32-aware expression under
  upstream's renamed `AMD_WMMA_256B_AVAILABLE` (256B == RDNA3).
- the derived kq mask MOVED ABI: upstream's kv_rows took src[5], which the derived
  form had been using, so cell_pos/tok_lo/tok_hi are now src[6], src[7], src[8]
  (ggml.c, ggml-cpu/ops.cpp, the CUDA launcher, and both fattn.cu predicates).
  Before the move the derived probe resolved to "not supported" and every batch
  silently fell back to the packed mask.
- the rotation constants are no longer filled per ubatch: upstream ggml-org#31073 keeps them
  on the GPU and consumes them at graph-build time (get_k_rot()), so the block's
  set_input_k_rot/v_rot calls and their declarations (removed from the base by
  upstream) are dropped.
- input classes use upstream's llm_attn_mask (raw/rows) instead of the separate
  kq_mask/kq_mask_cnv members; the derived registration hangs off the dense branch of
  build_attn_inp_attn_mask, which is now a graph-context member so it can add inputs.
  The two compact forms are mutually exclusive and the flash-attention build emits one
  op (kv_rows XOR derived XOR plain).

Validated: build green; derived kq mask enabled ("derived kq mask flash attention
enabled"); derived vs LLAMA_KQ_MASK_DERIVED=0 byte-identical at a 4096-ctx prefill
(149 chars, sha 30c7fc8705a6); q8_0 KV runs with flash attention.

r268 amendment (contributor PR ggml-org#303, `overdoingism`): the launchers' GQA choice asks the ONE mask
predicate.  `ggml_cuda_flash_attn_ext_has_mask()` moves from fattn.cu to fattn-common.cuh (ahead of
the fattn-rdna.cuh include), and both the RDNA band predicate and the tile ncols2 dispatch
(launch_fattn_tile_switch_ncols2) call it instead of asking `src[5]` (the kv_rows form) alone.  Since
upstream ggml-org#29510 took src[5] for kv_rows and moved this block's derived form to src[6..8], a derived op
took the ncols2 = 1 variants on every layout where the tile kernel is the chosen one (RDNA2,
RDNA3_0/RDNA3_5 heads above their WMMA cap, GGML_CUDA_FA_WMMA_256=0): a kernel selection that depended
on which mask form the graph used, plus a GGML_ABORT for the DKQ 320/576 tile instances, which have no
non-GQA arm.  The band hunk is inert by construction (a derived batch is always > 8 tokens, the band
requires <= 8) and is carried so the two sites cannot drift apart again.  Measured (gfx1201, tile
launcher forced with GGML_CUDA_FA_WMMA_MAX_HEAD): all-logits byte-identical to the packed arm and to
r267 on head 256/gqa 4 and head 128/gqa 8 (ncols2 4 and 8 vs 1), pp512 +0.6-1.0 % and +1.3 %, 27B
coherence d45e2221805a unchanged.  tests/test-backend-ops.cpp gains the head-512 aligned derived case
that reaches the tile GQA dispatch on a cap-320 layout (and is the MMA arm on gfx1201).

r308 amendment (field report, gfx1151): the kv_rows probe now REQUIRES the node (`require_observed`), because
its probe graph can be built on a shape that never creates one.  The reserve/probe context carries
`n_kv = kv->get_size()` (the whole PADDED cache extent), and a model's decode arm may depend on that extent
rather than on the used depth: qwen4exp (QSA) decodes dense only while `n_kv < qsa_dense_decode_until`, which
is 32768 on gfx1151.  At `-c 32768` (or any larger ctx, including the model dir's `-c 163840`) the probe
therefore took the SPARSE QSA arm, which builds no rows node at all, so nothing was verified and "Flash
Attention over K/V rows enabled" was logged.  No kernel outside NVIDIA turing-MMA reads the rows form (the
kv_rows branch of ggml_cuda_get_best_fattn_kernel returns NONE on every AMD arch), so the scheduler then
placed every joint attention layer on the CPU backend, silently: on an APU (shared host/device pool) it is a
correctness-preserving but ~3x decode loss, not a fault or a copy storm.

Measured (Strix Halo, gfx1151, the model dir's own flags, `--kv-unified`, ONE active slot, 15.5K depth):
- plain decode `-c 32768`: 25 backend splits in the decode graph and **11.0 t/s**, against **32.5 t/s** with
  `LLAMA_KV_ROWS_DISABLE=1` and 32.5 t/s for `--no-kv-unified`; prefill unaffected (1318 vs 1341 t/s), text
  identical in every arm (the CPU rows FA is correct -- this is a performance defect).
- MTP `draft-mtp n3` with the separate Flash-Next MTP GGUF at `-c 32768`: **18.7 -> 62.4-65.0 t/s
  (3.3-3.5x)**, because the verify band (`n_tokens <= max(8, n_rs_batch)`) takes the same dense arm, so every
  verify step built the rows form too -- and the drafter's own unified context was in the same state.
With the flag the target context reads "was not used in the probe graph, set to disabled", the drafter's
context declines by placement (its one layer IS the rows node), and every graph reads `splits = 1`.

Arches that cannot reach it, verified with the flag in place (the same placement path the fix leaves alone):
gfx1100 (RDNA3_0) and gfx1201 (RDNA4) have `qsa_dense_decode_until` unbounded, so their probe always reaches
the dense arm and declines by placement -- exercised on gfx1151 by forcing that policy
(`LLAMA_QSA_DENSE_DECODE_UNTIL=1000000000`), with and without the drafter: placement decline, `splits = 1`,
60.9 t/s with MTP; and a non-QSA model cannot reach the vacuity at all (Qwen3.6-35B-A3B Q8_0 and Qwen3.8-27B
Q8_0, both with embedded MTP: the node is observed, placed on the CPU, declined, `splits = 1`, 90.2 / 21.9
t/s decode, unchanged by the flag).  An explicit `LLAMA_QSA_DENSE_DECODE_UNTIL` below the context reproduces
the vacuity on ANY arch, which the flag also closes.  A probe that cannot verify an op must disable it,
exactly like the derived kq mask probe next to it.

NOTE FOR THE NEXT EDITOR: `llm_fused_op_probe` is initialized POSITIONALLY -- the `/*.field =*/` designators
in this file are comments, not C++20 designated initializers.  Adding `/*.require_observed =*/ true` as the
fourth value initializes `n_seqs`, leaves the flag false, and measures nothing (the first cut of this
amendment did exactly that); the initializer now lists every field through `require_observed` in struct
order and carries that warning next to it.

r314 (contributor PR ggml-org#329, @overdoingism): the band also takes 128-dim heads whose GQA ratio is not a multiple
of 8 -- ratios 5, 6, 7 and 9..12 (the generic dispatch folds the largest power of two dividing the ratio, so an
odd ratio folds NOTHING and a GQA 7 decode reads each K/V head once per query head).  The predicate, the
`ncols2` dispatch (the 32-column block for every query width: no 64-column band row and no fetch-ahead for this
head size) and the band's 2-D path compiled into the existing 128-dim `ncols1 <= 4` instances -- no new config
rows and no new instances.

Two things were changed from the submission, and both are gated:

* It is **on where it pays, not unconditionally**.  The band adds a fixed per-layer cost (the packed-mask
  prepass and the P = nsm fixup combine) and its round-robin split leaves most blocks idle on a short cache, so
  it only wins once folding ceil(ratio/ncols2_tile) tile passes into ceil(ratio/8) band passes is amortized over
  enough KV cells.  `ggml_cuda_fattn_band_wmma_h128_applies()` tests `K->ne[1] * passes_saved >= 20000`, which
  is the measured crossover of the class (band/tile per-op at the decode width: ratio 5 crosses at 4096 cells,
  ratio 7 at 4096, ratio 10 at 8192, ratio 12 at 32768 -- table in the helper), and **the test is the layer's
  CACHE SIZE, never the used length**: K is a permuted view of the KV cache, so `K->ne[1]` is fixed for the run,
  while a verify batch moves the used length by up to W-1 rows and a length-keyed test would select a different
  kernel for a decode step and its own verify batch.  This matters most on a sliding-window/hybrid model, whose
  windowed layers hold `n_swa + n_ubatch` cells for the whole run: unconditional, the band cost ricursive 65B
  (64 of 80 layers windowed at 1024) 4.5-5.8 % of decode at d0..d32K; with the work gate it is 0 % at d0/d4K and
  -0.5..-0.9 % at d16K/d32K, while a non-SWA 128-dim model at a real context keeps the band everywhere.
  `GGML_HIP_FA_BAND_WMMA_H128`: unset = auto (the work gate), 0 = off (kill switch), 1 = forced on for every
  shape the predicate reaches (the measurement arm); `GGML_HIP_FA_BAND_H128_MIN_WORK` is the tuning constant.
* The 2-D launch is guarded on the compiled instance (`Q->ne[0] == 256 || ncols1 <= 4`) in `launch_fattn`, so a
  128-dim op can never be launched with gridDim.y = P against an instance whose band fast path is compiled out.

Tests: 384 cases -- ratios 5/6/7/12 on 8 and 4 K/V heads, query widths 1..16, q8_0/f16 at kv 512/1024/4096
(a 256-cell masked group at 4096) for the dispatch/tile arm, plus q8_0/f16/bf16 at kv 32768 (past the gate for
every ratio) for the band itself, which is also the band's first bf16 oracle for this head size.

r315 (`TODO` ggml-org#345): the 256-dim head class gets the same work gate.  The band has been a published default
for head 256 since r6 and it is measured to lose on this box's weight-bound decode arms: per op (gfx1201,
head 256, 4 K/V heads, band / tile, the best P of 4/8/16/32/64) GQA 6 at the decode width reads 2.64 (q8_0) /
1.96 (f16) at 512 cells, 2.13 / 1.59 at 1024, 1.30 / 1.89 at 2048, 1.26 / 1.48 at 4096, 0.96 / 1.09 at 8192
and 0.66 / 1.10 at 32768, and end to end (3 GPUs, `-sm tensor`, tg64 against `GGML_HIP_FA_BAND_WMMA=0`) the
27B Q8_0 loses 4.6 % at d0, 35B-A3B Q8_0 9.8 % at d0 and 2.7 % at d8192, Flash-Next GSQ-IQ3_XXS 4.0 % / 2.7 %,
plus 4.7 % on the 27B's `draft-mtp n3` arm.

The gate is `ggml_cuda_fattn_band_wmma_h256_applies()`:
`K->ne[1] * max(passes_saved, 1) >= GGML_HIP_FA_BAND_H256_MIN_WORK` (default 20000), i.e. band from 10000
cells for GQA 6 (3 -> 1 passes) and from 20000 for GQA 8 and GQA 12.  The `max(..., 1)` floor is what handles
a ratio that already folds whole outside the band (GQA 8: the tile kernel's ncols2 is 8 there too, so the band
saves no passes at all) -- it is gated by cells alone instead of being disabled for the whole class, which
would throw away the deep verify widths where it measures 0.45 at 8192 cells.  Per-op crossover of the class
at the decode width is 4-10k cells and at verify widths 1-2k, so 20000 (the 128-dim arm's constant) is on the
conservative side.

Measured with the gate: 27B tg64 44.20 / 44.84 / 44.38 / 43.48 / 41.91 -> 46.13 / 45.65 / 45.18 / 43.55 / 41.90
t/s at d0 / 4K / 8K / 16K / 32K (+4.4 / +1.8 / +1.8 / 0.0 / 0.0 %), 35B-A3B 130.12 / 134.63 -> 139.72 / 138.82
(+7.4 / +3.1 %), Flash-Next 72.04 / 72.70 -> 74.25 / 74.35 (+3.1 / +2.3 %); the deep arm that keeps the band
is unchanged (27B, MTP n7 at a 20.5K prompt, 79.0 -> 78.9 t/s, where the band is +6.7 % over the tile kernel),
and the 27B's `draft-mtp n3` arm at a 5.4K prompt is -1.1 % (the band is worth ~1 % there).  Every changed arm
reproduces the PREVIOUS build's all-tile arm byte for byte -- 35B-A3B `265c381dbc11`; the four MTP axes
`7dca501eeb0e` (R), `759c1a4515c6` (R draft), `fcc0bdeb636b` (P), `eb89102cb7d8` (C), `a87c4318b649` (K).

Corrected here: r314's claim that `K->ne[1]` at the FA op is the layer's KV CACHE SIZE is wrong -- it is the
PADDED USED LENGTH (measured on the 27B at `-c 8192`: 256 at d0, 5376 -> 5632 while generating, 8192 only
during a prompt ubatch or in the graph-RESERVATION pass, whose context sets n_kv = kv->get_size()).  That does
not change r314's measurements -- its d0 row reads 0.0 %, which only a used-length key produces -- and it is
the right attribute to price the crossover with, since it is the number of KV iterations the kernel executes.
What it does mean is that a verify batch can straddle a 256-cell padding boundary and take the other kernel
family for that ONE step: `test-logits-width-probe` at P=9980 (W=1..4 on the tile kernel, W=5..8 on the band)
FAILs with maxdiff 0.327, while every arm with a constant family passes with maxdiff 0.  Accepted and recorded
(`GREEDY-PURITY.md` 96/97) -- keying the gate on the cache size instead would band a shallow context on a large
`-c` and reintroduce exactly these losses.

`TODO` ggml-org#345 route (b) (adaptive `P = min(nsm, ceil(cells/nbatch_fa))`) is refuted and not implemented: at depth
there are no idle blocks to remove (32768 cells / 64 = 512 iterations against P = 32 = nsm), and at a short
cache the idle blocks cost nothing (a block that owns no iteration writes a neutral partial and exits) while a
smaller P serialises the KV iterations -- 512 cells with P = 8 measures 52.6 us against 31.1 for P = 16.
P = 16 is the optimum in 30 of the 36 measured rows; the quantized default P = nsm is 10-20 % off it at most
sizes, which is a separate tuning item (it moves every banded model's numerics).

r316 (TODO ggml-org#346 closed) -- the band's fixup period P stops depending on the K/V type: P = max(2, nsm/2) for
EVERY type now (nsm 32 -> 16), so `ggml_cuda_fattn_band_wmma_two_byte()` and the launcher's P fallback are gone
and `GGML_HIP_FA_BAND_WMMA_SPLIT` stays as the tuning override.  A sweep of the 256-dim class
(`GGML_HIP_FA_BAND_WMMA_SPLIT` 8/16/24/32/48/64/96 x kv 512-102400 x n_q 1/8, q8_0, medians of 3,
test-backend-ops perf) puts the DECODE width's optimum at 16 for both type families and the VERIFY widths' at 8,
so one constant cannot serve both and 16 is the compromise the widths force: P 16 beats the old quantized
default 32 by 5-14 % at kv 16384-102400 (92.9 against 99.5 us at kv 16384/n_q 1, 151.2 against 163.9 at 32768,
425.0 against 447.5 at 102400, 279.7 against 318.4 at 32768/n_q 8) and only loses at the short caches every band
gate keeps off (1024 cells/n_q 1: P 16 55.0 against P 32 42.6 -- measured and recorded, unreachable).  The
long-standing comment claim that the verify cost is "flat for P 48..96 at kv 20K..200K" does not reproduce on
this kernel (verify widths are monotone in P; what is flat is the decode width above P 24) and was replaced.

End to end (3 GPU `-sm tensor`, q8_0 K/V, `ROCBLAS_USE_HIPBLASLT=0`): plain 27B tg64 43.66 / 42.45 t/s at
d16384 / d32768 against 43.53 / 42.62 (noise -- a 27B Q8_0 decode is at the DRAM roof), Ripple-65B 26.07 / 25.41
against 25.96 / 25.44 (noise), and the attention-bound arm that pays: 27B `draft-mtp n7` on the 20.5K prose
prompt 88.91 against 75.83 t/s (+17.2 %, of which ~4.5 %/step is the kernel and the rest the acceptance re-roll a
numeric-order change always carries) and 79.00 against 74.91 at ~10.5K (+5.5 %).  P 8 wins the op-level verify
rows but loses every e2e arm (40.86 t/s at d32768, 75.68 on the 20.5K arm), so it was not taken.

Correctness and purity: `test-backend-ops -o FLASH_ATTN_EXT` 7381/7381 in four arms (default, H256+H128 forced,
`WMMA=0`, `WMMA=2`); `test-logits-width-probe` width purity PASS maxdiff 0 on 37 arms (both head classes, q8_0 /
f16 / bf16, one GPU plus `SPLIT=tensor` and `SPLIT=layer`, P 3584 / 4096 / 10240 -- a constant P cannot
straddle); prefill KLD 0.000000 / 100.000 % at the canonical point, and the family-switch point 0.002733 /
99.243 % (27B) and 0.000823 / 98.981 % (Ripple-65B) against same-kernel controls of 0.004182 / 98.822 % and
0.004133 / 97.772 %.  The four MTP axes are byte-identical to r315 on bf16 K/V (R `7dca501eeb0e` /
`759c1a4515c6`, P `fcc0bdeb636b`, C `eb89102cb7d8`, K `a87c4318b649`, acceptance 348/486, 357/460, 368/427,
372/375 reproduced exactly) and the q8_0 arms carry the same acceptance as r315's own (P-independent: the four
axes sit below the band gate and never reach it).  Every text arm that moved -- 27B q8_0 at a 21K prompt
`f7d157b1e07e` -> `774d1c325068` -- reproduces the previous build's `GGML_HIP_FA_BAND_WMMA_SPLIT=16` arm byte for
byte, and `SPLIT=32` still reproduces the old default.  The 128-dim gate's decisions are unchanged in cell terms
and every one of them is still on the right side of the measured crossover with P 16 (ratio 10: 4096 cells 1.06
loss, 8192 0.88 win; ratio 5: 8192 0.62; ratio 7: 4096 0.60; ratio 12: 8192 1.06 tile, 32768 0.91 band).

Records: `INVARIANTS.md` r316, `GREEDY-PURITY.md` 98, `benchmarks/2026-11-18-band-fixup-period.md`,
`MANIFESTS.md` gate 05, `patches/README.md` block 05, `ENVIRONMENT.md` 8, `TODO.md` (ggml-org#346 deleted).

(r328 re-base) 7 conflicted files / 22 regions.  The maintainer's decision (`DECISIONS.md` D16, option 2) is
that the delivery's FA iteration model wins: upstream 054a1ba (ggml-org#32407, "rotate K/V read order") rewrites
`flash_attn_ext_f16_process_tile` as a contiguous run plus a rotated remainder (nkb_pre/nkb_post, kb0_max
wrap-around), while this block rewrites the same loop as a strided band (kb0_step, a kq_blocks bitmap skip, a
neutral partial for a band block that owns no iteration, and the RDNA4 fetch-ahead ring).  Those are different
partitions of the same work, so a merge would be a third model; the rotation is NOT carried (no nkb_pre,
nkb_post, kb0_max or kb0_rot survives; every kb0_next in the tree is the delivery's own fetch-ahead).

What IS taken from upstream, because it is unrelated to the rotation:
- ggml-org#32217 (Inkling 2) per-head masks: the `+ nb32*(zt_Q % ne32)` term at the three mask-pointer sites of the
  MMA kernel, the `mask` tensor declaration in the tile launcher, and the `mask->ne[2] == 1` conjunct unioned
  into our derived-mask predicate in fattn-tile.cuh and both fattn.cu sites.
- ggml-org#31617's typed warp masks: the seven raw __shfl[_xor]_sync(0xFFFFFFFF, ...) calls in the band code become
  ggml_cuda_shfl_xor / ggml_cuda_shfl (HIP now static_asserts a 64-bit mask).
- build_inp_mem_hybrid_iswa_rel and the build_attn_inp_attn_mask refactor, called through the delivery's
  derived-mask signatures (build_attn_inp_kq_mask(mctx, ubatch, cparams, allow_derived)).
- the FA op-test parameters (n_kv_max, q_head_padding, mask_heads) unioned with derived/derived_hole/mask_hole.
nb32 stays int32_t (upstream widened it to int64_t; the delivery's kernels are the ones in the tree, so the
typedef and the kernels are kept consistent rather than half-widened).

Verified: 4B coherence 100 chars sha=1c5d32ac537d (unchanged); test-backend-ops -o FLASH_ATTN_EXT 7428/7428
with 0 failures, 2/2 backends -- the whole FA matrix, which is the oracle the combined-model option would have
needed at every step; and the block's own switch is non-vacuous on the path it exists for (q8_0 KV,
GGML_CUDA_FA_KV_NATIVE=1 88.6 t/s decode vs 83.9 staged, +5.6 %, identical text 71 chars sha=1de99b7e6ee6;
f16 KV is a wash, as expected -- staging only costs anything for a quantized cache).
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Nov 22, 2026
… derived kq mask

Re-based onto a691b23.  Upstream ggml-org#29510 (flash_attn_ext_rows, the kv_rows unified-KV
form) and the llm_attn_mask refactor meet this block in 9 files / 48 hunks.

Resolutions worth knowing:
- the kernel signatures carry both parameters (upstream's `KV_rows` then our
  `kq_blocks`); the loaders take upstream's kv_rows `indices` with our native-KV
  arguments; the C-tile sizing keeps the delivery's fp32-aware expression under
  upstream's renamed `AMD_WMMA_256B_AVAILABLE` (256B == RDNA3).
- the derived kq mask MOVED ABI: upstream's kv_rows took src[5], which the derived
  form had been using, so cell_pos/tok_lo/tok_hi are now src[6], src[7], src[8]
  (ggml.c, ggml-cpu/ops.cpp, the CUDA launcher, and both fattn.cu predicates).
  Before the move the derived probe resolved to "not supported" and every batch
  silently fell back to the packed mask.
- the rotation constants are no longer filled per ubatch: upstream ggml-org#31073 keeps them
  on the GPU and consumes them at graph-build time (get_k_rot()), so the block's
  set_input_k_rot/v_rot calls and their declarations (removed from the base by
  upstream) are dropped.
- input classes use upstream's llm_attn_mask (raw/rows) instead of the separate
  kq_mask/kq_mask_cnv members; the derived registration hangs off the dense branch of
  build_attn_inp_attn_mask, which is now a graph-context member so it can add inputs.
  The two compact forms are mutually exclusive and the flash-attention build emits one
  op (kv_rows XOR derived XOR plain).

Validated: build green; derived kq mask enabled ("derived kq mask flash attention
enabled"); derived vs LLAMA_KQ_MASK_DERIVED=0 byte-identical at a 4096-ctx prefill
(149 chars, sha 30c7fc8705a6); q8_0 KV runs with flash attention.

r268 amendment (contributor PR ggml-org#303, `overdoingism`): the launchers' GQA choice asks the ONE mask
predicate.  `ggml_cuda_flash_attn_ext_has_mask()` moves from fattn.cu to fattn-common.cuh (ahead of
the fattn-rdna.cuh include), and both the RDNA band predicate and the tile ncols2 dispatch
(launch_fattn_tile_switch_ncols2) call it instead of asking `src[5]` (the kv_rows form) alone.  Since
upstream ggml-org#29510 took src[5] for kv_rows and moved this block's derived form to src[6..8], a derived op
took the ncols2 = 1 variants on every layout where the tile kernel is the chosen one (RDNA2,
RDNA3_0/RDNA3_5 heads above their WMMA cap, GGML_CUDA_FA_WMMA_256=0): a kernel selection that depended
on which mask form the graph used, plus a GGML_ABORT for the DKQ 320/576 tile instances, which have no
non-GQA arm.  The band hunk is inert by construction (a derived batch is always > 8 tokens, the band
requires <= 8) and is carried so the two sites cannot drift apart again.  Measured (gfx1201, tile
launcher forced with GGML_CUDA_FA_WMMA_MAX_HEAD): all-logits byte-identical to the packed arm and to
r267 on head 256/gqa 4 and head 128/gqa 8 (ncols2 4 and 8 vs 1), pp512 +0.6-1.0 % and +1.3 %, 27B
coherence d45e2221805a unchanged.  tests/test-backend-ops.cpp gains the head-512 aligned derived case
that reaches the tile GQA dispatch on a cap-320 layout (and is the MMA arm on gfx1201).

r308 amendment (field report, gfx1151): the kv_rows probe now REQUIRES the node (`require_observed`), because
its probe graph can be built on a shape that never creates one.  The reserve/probe context carries
`n_kv = kv->get_size()` (the whole PADDED cache extent), and a model's decode arm may depend on that extent
rather than on the used depth: qwen4exp (QSA) decodes dense only while `n_kv < qsa_dense_decode_until`, which
is 32768 on gfx1151.  At `-c 32768` (or any larger ctx, including the model dir's `-c 163840`) the probe
therefore took the SPARSE QSA arm, which builds no rows node at all, so nothing was verified and "Flash
Attention over K/V rows enabled" was logged.  No kernel outside NVIDIA turing-MMA reads the rows form (the
kv_rows branch of ggml_cuda_get_best_fattn_kernel returns NONE on every AMD arch), so the scheduler then
placed every joint attention layer on the CPU backend, silently: on an APU (shared host/device pool) it is a
correctness-preserving but ~3x decode loss, not a fault or a copy storm.

Measured (Strix Halo, gfx1151, the model dir's own flags, `--kv-unified`, ONE active slot, 15.5K depth):
- plain decode `-c 32768`: 25 backend splits in the decode graph and **11.0 t/s**, against **32.5 t/s** with
  `LLAMA_KV_ROWS_DISABLE=1` and 32.5 t/s for `--no-kv-unified`; prefill unaffected (1318 vs 1341 t/s), text
  identical in every arm (the CPU rows FA is correct -- this is a performance defect).
- MTP `draft-mtp n3` with the separate Flash-Next MTP GGUF at `-c 32768`: **18.7 -> 62.4-65.0 t/s
  (3.3-3.5x)**, because the verify band (`n_tokens <= max(8, n_rs_batch)`) takes the same dense arm, so every
  verify step built the rows form too -- and the drafter's own unified context was in the same state.
With the flag the target context reads "was not used in the probe graph, set to disabled", the drafter's
context declines by placement (its one layer IS the rows node), and every graph reads `splits = 1`.

Arches that cannot reach it, verified with the flag in place (the same placement path the fix leaves alone):
gfx1100 (RDNA3_0) and gfx1201 (RDNA4) have `qsa_dense_decode_until` unbounded, so their probe always reaches
the dense arm and declines by placement -- exercised on gfx1151 by forcing that policy
(`LLAMA_QSA_DENSE_DECODE_UNTIL=1000000000`), with and without the drafter: placement decline, `splits = 1`,
60.9 t/s with MTP; and a non-QSA model cannot reach the vacuity at all (Qwen3.6-35B-A3B Q8_0 and Qwen3.8-27B
Q8_0, both with embedded MTP: the node is observed, placed on the CPU, declined, `splits = 1`, 90.2 / 21.9
t/s decode, unchanged by the flag).  An explicit `LLAMA_QSA_DENSE_DECODE_UNTIL` below the context reproduces
the vacuity on ANY arch, which the flag also closes.  A probe that cannot verify an op must disable it,
exactly like the derived kq mask probe next to it.

NOTE FOR THE NEXT EDITOR: `llm_fused_op_probe` is initialized POSITIONALLY -- the `/*.field =*/` designators
in this file are comments, not C++20 designated initializers.  Adding `/*.require_observed =*/ true` as the
fourth value initializes `n_seqs`, leaves the flag false, and measures nothing (the first cut of this
amendment did exactly that); the initializer now lists every field through `require_observed` in struct
order and carries that warning next to it.

r314 (contributor PR ggml-org#329, @overdoingism): the band also takes 128-dim heads whose GQA ratio is not a multiple
of 8 -- ratios 5, 6, 7 and 9..12 (the generic dispatch folds the largest power of two dividing the ratio, so an
odd ratio folds NOTHING and a GQA 7 decode reads each K/V head once per query head).  The predicate, the
`ncols2` dispatch (the 32-column block for every query width: no 64-column band row and no fetch-ahead for this
head size) and the band's 2-D path compiled into the existing 128-dim `ncols1 <= 4` instances -- no new config
rows and no new instances.

Two things were changed from the submission, and both are gated:

* It is **on where it pays, not unconditionally**.  The band adds a fixed per-layer cost (the packed-mask
  prepass and the P = nsm fixup combine) and its round-robin split leaves most blocks idle on a short cache, so
  it only wins once folding ceil(ratio/ncols2_tile) tile passes into ceil(ratio/8) band passes is amortized over
  enough KV cells.  `ggml_cuda_fattn_band_wmma_h128_applies()` tests `K->ne[1] * passes_saved >= 20000`, which
  is the measured crossover of the class (band/tile per-op at the decode width: ratio 5 crosses at 4096 cells,
  ratio 7 at 4096, ratio 10 at 8192, ratio 12 at 32768 -- table in the helper), and **the test is the layer's
  CACHE SIZE, never the used length**: K is a permuted view of the KV cache, so `K->ne[1]` is fixed for the run,
  while a verify batch moves the used length by up to W-1 rows and a length-keyed test would select a different
  kernel for a decode step and its own verify batch.  This matters most on a sliding-window/hybrid model, whose
  windowed layers hold `n_swa + n_ubatch` cells for the whole run: unconditional, the band cost ricursive 65B
  (64 of 80 layers windowed at 1024) 4.5-5.8 % of decode at d0..d32K; with the work gate it is 0 % at d0/d4K and
  -0.5..-0.9 % at d16K/d32K, while a non-SWA 128-dim model at a real context keeps the band everywhere.
  `GGML_HIP_FA_BAND_WMMA_H128`: unset = auto (the work gate), 0 = off (kill switch), 1 = forced on for every
  shape the predicate reaches (the measurement arm); `GGML_HIP_FA_BAND_H128_MIN_WORK` is the tuning constant.
* The 2-D launch is guarded on the compiled instance (`Q->ne[0] == 256 || ncols1 <= 4`) in `launch_fattn`, so a
  128-dim op can never be launched with gridDim.y = P against an instance whose band fast path is compiled out.

Tests: 384 cases -- ratios 5/6/7/12 on 8 and 4 K/V heads, query widths 1..16, q8_0/f16 at kv 512/1024/4096
(a 256-cell masked group at 4096) for the dispatch/tile arm, plus q8_0/f16/bf16 at kv 32768 (past the gate for
every ratio) for the band itself, which is also the band's first bf16 oracle for this head size.

r315 (`TODO` ggml-org#345): the 256-dim head class gets the same work gate.  The band has been a published default
for head 256 since r6 and it is measured to lose on this box's weight-bound decode arms: per op (gfx1201,
head 256, 4 K/V heads, band / tile, the best P of 4/8/16/32/64) GQA 6 at the decode width reads 2.64 (q8_0) /
1.96 (f16) at 512 cells, 2.13 / 1.59 at 1024, 1.30 / 1.89 at 2048, 1.26 / 1.48 at 4096, 0.96 / 1.09 at 8192
and 0.66 / 1.10 at 32768, and end to end (3 GPUs, `-sm tensor`, tg64 against `GGML_HIP_FA_BAND_WMMA=0`) the
27B Q8_0 loses 4.6 % at d0, 35B-A3B Q8_0 9.8 % at d0 and 2.7 % at d8192, Flash-Next GSQ-IQ3_XXS 4.0 % / 2.7 %,
plus 4.7 % on the 27B's `draft-mtp n3` arm.

The gate is `ggml_cuda_fattn_band_wmma_h256_applies()`:
`K->ne[1] * max(passes_saved, 1) >= GGML_HIP_FA_BAND_H256_MIN_WORK` (default 20000), i.e. band from 10000
cells for GQA 6 (3 -> 1 passes) and from 20000 for GQA 8 and GQA 12.  The `max(..., 1)` floor is what handles
a ratio that already folds whole outside the band (GQA 8: the tile kernel's ncols2 is 8 there too, so the band
saves no passes at all) -- it is gated by cells alone instead of being disabled for the whole class, which
would throw away the deep verify widths where it measures 0.45 at 8192 cells.  Per-op crossover of the class
at the decode width is 4-10k cells and at verify widths 1-2k, so 20000 (the 128-dim arm's constant) is on the
conservative side.

Measured with the gate: 27B tg64 44.20 / 44.84 / 44.38 / 43.48 / 41.91 -> 46.13 / 45.65 / 45.18 / 43.55 / 41.90
t/s at d0 / 4K / 8K / 16K / 32K (+4.4 / +1.8 / +1.8 / 0.0 / 0.0 %), 35B-A3B 130.12 / 134.63 -> 139.72 / 138.82
(+7.4 / +3.1 %), Flash-Next 72.04 / 72.70 -> 74.25 / 74.35 (+3.1 / +2.3 %); the deep arm that keeps the band
is unchanged (27B, MTP n7 at a 20.5K prompt, 79.0 -> 78.9 t/s, where the band is +6.7 % over the tile kernel),
and the 27B's `draft-mtp n3` arm at a 5.4K prompt is -1.1 % (the band is worth ~1 % there).  Every changed arm
reproduces the PREVIOUS build's all-tile arm byte for byte -- 35B-A3B `265c381dbc11`; the four MTP axes
`7dca501eeb0e` (R), `759c1a4515c6` (R draft), `fcc0bdeb636b` (P), `eb89102cb7d8` (C), `a87c4318b649` (K).

Corrected here: r314's claim that `K->ne[1]` at the FA op is the layer's KV CACHE SIZE is wrong -- it is the
PADDED USED LENGTH (measured on the 27B at `-c 8192`: 256 at d0, 5376 -> 5632 while generating, 8192 only
during a prompt ubatch or in the graph-RESERVATION pass, whose context sets n_kv = kv->get_size()).  That does
not change r314's measurements -- its d0 row reads 0.0 %, which only a used-length key produces -- and it is
the right attribute to price the crossover with, since it is the number of KV iterations the kernel executes.
What it does mean is that a verify batch can straddle a 256-cell padding boundary and take the other kernel
family for that ONE step: `test-logits-width-probe` at P=9980 (W=1..4 on the tile kernel, W=5..8 on the band)
FAILs with maxdiff 0.327, while every arm with a constant family passes with maxdiff 0.  Accepted and recorded
(`GREEDY-PURITY.md` 96/97) -- keying the gate on the cache size instead would band a shallow context on a large
`-c` and reintroduce exactly these losses.

`TODO` ggml-org#345 route (b) (adaptive `P = min(nsm, ceil(cells/nbatch_fa))`) is refuted and not implemented: at depth
there are no idle blocks to remove (32768 cells / 64 = 512 iterations against P = 32 = nsm), and at a short
cache the idle blocks cost nothing (a block that owns no iteration writes a neutral partial and exits) while a
smaller P serialises the KV iterations -- 512 cells with P = 8 measures 52.6 us against 31.1 for P = 16.
P = 16 is the optimum in 30 of the 36 measured rows; the quantized default P = nsm is 10-20 % off it at most
sizes, which is a separate tuning item (it moves every banded model's numerics).

r316 (TODO ggml-org#346 closed) -- the band's fixup period P stops depending on the K/V type: P = max(2, nsm/2) for
EVERY type now (nsm 32 -> 16), so `ggml_cuda_fattn_band_wmma_two_byte()` and the launcher's P fallback are gone
and `GGML_HIP_FA_BAND_WMMA_SPLIT` stays as the tuning override.  A sweep of the 256-dim class
(`GGML_HIP_FA_BAND_WMMA_SPLIT` 8/16/24/32/48/64/96 x kv 512-102400 x n_q 1/8, q8_0, medians of 3,
test-backend-ops perf) puts the DECODE width's optimum at 16 for both type families and the VERIFY widths' at 8,
so one constant cannot serve both and 16 is the compromise the widths force: P 16 beats the old quantized
default 32 by 5-14 % at kv 16384-102400 (92.9 against 99.5 us at kv 16384/n_q 1, 151.2 against 163.9 at 32768,
425.0 against 447.5 at 102400, 279.7 against 318.4 at 32768/n_q 8) and only loses at the short caches every band
gate keeps off (1024 cells/n_q 1: P 16 55.0 against P 32 42.6 -- measured and recorded, unreachable).  The
long-standing comment claim that the verify cost is "flat for P 48..96 at kv 20K..200K" does not reproduce on
this kernel (verify widths are monotone in P; what is flat is the decode width above P 24) and was replaced.

End to end (3 GPU `-sm tensor`, q8_0 K/V, `ROCBLAS_USE_HIPBLASLT=0`): plain 27B tg64 43.66 / 42.45 t/s at
d16384 / d32768 against 43.53 / 42.62 (noise -- a 27B Q8_0 decode is at the DRAM roof), Ripple-65B 26.07 / 25.41
against 25.96 / 25.44 (noise), and the attention-bound arm that pays: 27B `draft-mtp n7` on the 20.5K prose
prompt 88.91 against 75.83 t/s (+17.2 %, of which ~4.5 %/step is the kernel and the rest the acceptance re-roll a
numeric-order change always carries) and 79.00 against 74.91 at ~10.5K (+5.5 %).  P 8 wins the op-level verify
rows but loses every e2e arm (40.86 t/s at d32768, 75.68 on the 20.5K arm), so it was not taken.

Correctness and purity: `test-backend-ops -o FLASH_ATTN_EXT` 7381/7381 in four arms (default, H256+H128 forced,
`WMMA=0`, `WMMA=2`); `test-logits-width-probe` width purity PASS maxdiff 0 on 37 arms (both head classes, q8_0 /
f16 / bf16, one GPU plus `SPLIT=tensor` and `SPLIT=layer`, P 3584 / 4096 / 10240 -- a constant P cannot
straddle); prefill KLD 0.000000 / 100.000 % at the canonical point, and the family-switch point 0.002733 /
99.243 % (27B) and 0.000823 / 98.981 % (Ripple-65B) against same-kernel controls of 0.004182 / 98.822 % and
0.004133 / 97.772 %.  The four MTP axes are byte-identical to r315 on bf16 K/V (R `7dca501eeb0e` /
`759c1a4515c6`, P `fcc0bdeb636b`, C `eb89102cb7d8`, K `a87c4318b649`, acceptance 348/486, 357/460, 368/427,
372/375 reproduced exactly) and the q8_0 arms carry the same acceptance as r315's own (P-independent: the four
axes sit below the band gate and never reach it).  Every text arm that moved -- 27B q8_0 at a 21K prompt
`f7d157b1e07e` -> `774d1c325068` -- reproduces the previous build's `GGML_HIP_FA_BAND_WMMA_SPLIT=16` arm byte for
byte, and `SPLIT=32` still reproduces the old default.  The 128-dim gate's decisions are unchanged in cell terms
and every one of them is still on the right side of the measured crossover with P 16 (ratio 10: 4096 cells 1.06
loss, 8192 0.88 win; ratio 5: 8192 0.62; ratio 7: 4096 0.60; ratio 12: 8192 1.06 tile, 32768 0.91 band).

Records: `INVARIANTS.md` r316, `GREEDY-PURITY.md` 98, `benchmarks/2026-11-18-band-fixup-period.md`,
`MANIFESTS.md` gate 05, `patches/README.md` block 05, `ENVIRONMENT.md` 8, `TODO.md` (ggml-org#346 deleted).

(r328 re-base) 7 conflicted files / 22 regions.  The maintainer's decision (`DECISIONS.md` D16, option 2) is
that the delivery's FA iteration model wins: upstream 054a1ba (ggml-org#32407, "rotate K/V read order") rewrites
`flash_attn_ext_f16_process_tile` as a contiguous run plus a rotated remainder (nkb_pre/nkb_post, kb0_max
wrap-around), while this block rewrites the same loop as a strided band (kb0_step, a kq_blocks bitmap skip, a
neutral partial for a band block that owns no iteration, and the RDNA4 fetch-ahead ring).  Those are different
partitions of the same work, so a merge would be a third model; the rotation is NOT carried (no nkb_pre,
nkb_post, kb0_max or kb0_rot survives; every kb0_next in the tree is the delivery's own fetch-ahead).

What IS taken from upstream, because it is unrelated to the rotation:
- ggml-org#32217 (Inkling 2) per-head masks: the `+ nb32*(zt_Q % ne32)` term at the three mask-pointer sites of the
  MMA kernel, the `mask` tensor declaration in the tile launcher, and the `mask->ne[2] == 1` conjunct unioned
  into our derived-mask predicate in fattn-tile.cuh and both fattn.cu sites.
- ggml-org#31617's typed warp masks: the seven raw __shfl[_xor]_sync(0xFFFFFFFF, ...) calls in the band code become
  ggml_cuda_shfl_xor / ggml_cuda_shfl (HIP now static_asserts a 64-bit mask).
- build_inp_mem_hybrid_iswa_rel and the build_attn_inp_attn_mask refactor, called through the delivery's
  derived-mask signatures (build_attn_inp_kq_mask(mctx, ubatch, cparams, allow_derived)).
- the FA op-test parameters (n_kv_max, q_head_padding, mask_heads) unioned with derived/derived_hole/mask_hole.
nb32 stays int32_t (upstream widened it to int64_t; the delivery's kernels are the ones in the tree, so the
typedef and the kernels are kept consistent rather than half-widened).

Verified: 4B coherence 100 chars sha=1c5d32ac537d (unchanged); test-backend-ops -o FLASH_ATTN_EXT 7428/7428
with 0 failures, 2/2 backends -- the whole FA matrix, which is the oracle the combined-model option would have
needed at every step; and the block's own switch is non-vacuous on the path it exists for (q8_0 KV,
GGML_CUDA_FA_KV_NATIVE=1 88.6 t/s decode vs 83.9 staged, +5.6 %, identical text 71 chars sha=1de99b7e6ee6;
f16 KV is a wash, as expected -- staging only costs anything for a quantized cache).
ethgr0wth added a commit to aiassistsecure/llama.cpp that referenced this pull request Nov 22, 2026
Brings in the merged Inkling 2 implementation: PR ggml-org#32217 (text + vision, mmproj converter), PR ggml-org#32694 (inkling2_loop arch), PR ggml-org#32704 (loop scale fix). The draft PR ggml-org#32695 code merged in 862fdcb is superseded by upstream's merged implementation on every Inkling file. Mark's patches preserved: imagine-v9 tokenizer fix (conversion/base.py, content-merged with upstream), Muse Glimmer chat template (common/chat.cpp, common/parsers/muse-glimmer.cpp).
bong-water-water-bong pushed a commit to 1bit-MONSTER/llama.cpp that referenced this pull request Nov 22, 2026
…2_loop), ported from upstream

conversion/inkling2.py from ggml-org/llama.cpp at 5bacb7c (ggml-org#32217, ggml-org#32694), without the
vision (mmproj) class; the gguf-py keys, writer methods, tensors and name mappings it uses
(text only), and the inkling2 pre-tokenizer hash. The NVFP4/MXFP8 experts are dequantized
in the converter.

Checked on strixhalo: thinkingmachines/Inkling-2-Mini (sha 65e60f51) -> --outtype q8_0
gives the same metadata and 664 of 704 tensors byte-identical to ggml-org's Q8_0 (d57542f8);
the 40 that differ are the NVFP4 expert tensors, within one Q8_0 step (max |d| 0.3-0.5 %
of the tensor max), the MXFP8 experts are identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
bong-water-water-bong pushed a commit to 1bit-MONSTER/llama.cpp that referenced this pull request Nov 22, 2026
…inkling2 model-saver keys (from upstream ggml-org#32217, ggml-org#32694)

test-llama-archs -a '^inkling2' on CPU: inkling2 NMSE 0 + roundtrip OK, inkling2_loop NMSE 0
(roundtrip skipped: the loop arch is not savable, as upstream).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
bong-water-water-bong pushed a commit to 1bit-MONSTER/llama.cpp that referenced this pull request Nov 22, 2026
…rted from upstream

Ported from ggml-org/llama.cpp ggml-org#32217 (Inkling 2), ggml-org#32429 (attention mask),
ggml-org#32694 (Inkling 2 Mini, looped), ggml-org#32704 (loop slots after the scale pass),
ggml-org#32799 (ignore_merges) and ggml-org#32381 (Inkling chat parser), at upstream 5bacb7c.

Adapted to this fork: the graph takes the model by reference; the relative
position bias goes through build_attn's kq_b (pre-divided by kq_scale, since
build_attn_mha adds kq_b before soft_max_ext scales); the short-conv state is
stored with this fork's n_rs_seq slot layout; the lm_head accumulates in F32
via ggml_prec_set_acc. The relative-position input is a subclass of the
hybrid iSWA input. Vision (mtmd) and the converter are not part of this.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
bong-water-water-bong pushed a commit to 1bit-MONSTER/llama.cpp that referenced this pull request Nov 22, 2026
…2_loop), ported from upstream

conversion/inkling2.py from ggml-org/llama.cpp at 5bacb7c (ggml-org#32217, ggml-org#32694), without the
vision (mmproj) class; the gguf-py keys, writer methods, tensors and name mappings it uses
(text only), and the inkling2 pre-tokenizer hash. The NVFP4/MXFP8 experts are dequantized
in the converter.

Checked on strixhalo: thinkingmachines/Inkling-2-Mini (sha 65e60f51) -> --outtype q8_0
gives the same metadata and 664 of 704 tensors byte-identical to ggml-org's Q8_0 (d57542f8);
the 40 that differ are the NVFP4 expert tensors, within one Q8_0 step (max |d| 0.3-0.5 %
of the tensor max), the MXFP8 experts are identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
bong-water-water-bong pushed a commit to 1bit-MONSTER/llama.cpp that referenced this pull request Nov 22, 2026
…inkling2 model-saver keys (from upstream ggml-org#32217, ggml-org#32694)

test-llama-archs -a '^inkling2' on CPU: inkling2 NMSE 0 + roundtrip OK, inkling2_loop NMSE 0
(roundtrip skipped: the loop arch is not savable, as upstream).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
bong-water-water-bong added a commit to 1bit-MONSTER/llama.cpp that referenced this pull request Nov 23, 2026
…onverter, ported from upstream (engine#3328) (#489)

* model: Inkling 2 / Inkling 2 Mini (inkling2, inkling2_loop), text, ported from upstream

Ported from ggml-org/llama.cpp ggml-org#32217 (Inkling 2), ggml-org#32429 (attention mask),
ggml-org#32694 (Inkling 2 Mini, looped), ggml-org#32704 (loop slots after the scale pass),
ggml-org#32799 (ignore_merges) and ggml-org#32381 (Inkling chat parser), at upstream 5bacb7c.

Adapted to this fork: the graph takes the model by reference; the relative
position bias goes through build_attn's kq_b (pre-divided by kq_scale, since
build_attn_mha adds kq_b before soft_max_ext scales); the short-conv state is
stored with this fork's n_rs_seq slot layout; the lm_head accumulates in F32
via ggml_prec_set_acc. The relative-position input is a subclass of the
hybrid iSWA input. Vision (mtmd) and the converter are not part of this.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* convert: Inkling 2 / Inkling 2 Mini text converter (inkling2, inkling2_loop), ported from upstream

conversion/inkling2.py from ggml-org/llama.cpp at 5bacb7c (ggml-org#32217, ggml-org#32694), without the
vision (mmproj) class; the gguf-py keys, writer methods, tensors and name mappings it uses
(text only), and the inkling2 pre-tokenizer hash. The NVFP4/MXFP8 experts are dequantized
in the converter.

Checked on strixhalo: thinkingmachines/Inkling-2-Mini (sha 65e60f51) -> --outtype q8_0
gives the same metadata and 664 of 704 tensors byte-identical to ggml-org's Q8_0 (d57542f8);
the 40 that differ are the NVFP4 expert tensors, within one Q8_0 step (max |d| 0.3-0.5 %
of the tensor max), the MXFP8 experts are identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tests: test-llama-archs rows for inkling2 and inkling2_loop, and the inkling2 model-saver keys (from upstream ggml-org#32217, ggml-org#32694)

test-llama-archs -a '^inkling2' on CPU: inkling2 NMSE 0 + roundtrip OK, inkling2_loop NMSE 0
(roundtrip skipped: the loop arch is not savable, as upstream).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tests: Inkling chat-parser cases and templates (from upstream ggml-org#32381); jinja: tojson sort_keys=true (upstream ggml-org#32366)

The Inkling 2 Mini chat template renders tool specs with tojson(sort_keys=true), which this
fork's jinja threw on ('tojson sort_keys=true not implemented'), so any request with tools
failed. test-chat (all tests passed, Inkling templates included) and test-jinja pass on CPU.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* model: load ffn_gate_up_exps scales and pass the expert scales in Inkling 2 (upstream ggml-org#32657)

The generic scale pass loaded per-expert .scale tensors for ffn_gate_exps, ffn_up_exps and ffn_down_exps but not for
the merged ffn_gate_up_exps, so NVFP4 GGUFs with merged experts did not load: unsloth's Mainline_Support
Inkling-2-Mini-UD-Q4_K_XL (sha e6427665, NVFP4 experts on layers 0-19) failed with 'done_getting_tensors: wrong number
of tensors; expected 744, got 724' (strixhalo). Load it as ffn_up_exps_s (build_moe_ffn applies up_exps_s to the
merged gate_up output) and pass the scales to build_moe_ffn from the Inkling 2 graph.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* convert: Inkling 2 experts kept native NVFP4 (INKLING2_NVFP4_NATIVE=1), from upstream ggml-org#32786

Opt-in, same switch as the open upstream PR: the checkpoint's NVFP4 experts are repacked into ggml block_nvfp4
(E2M1 codes and E4M3 block scales unchanged, value j paired with j+8 per 16-group, gate/up rows de-interleaved) with
the per-expert amax/denominator as the .scale tensor, instead of being dequantized and quantized again. Without
the switch nothing changes.

Checked on strixhalo: thinkingmachines/Inkling-2-Mini (sha 65e60f51), INKLING2_NVFP4_NATIVE=1 --outtype q8_0 ->
744 tensors, 17.6 GB; all 88 expert tensors (NVFP4 weights + F32 scales on layers 0-19, Q8_0 for the MXFP8 layers
20-23) are byte-identical to unsloth's Mainline_Support Inkling-2-Mini-UD-Q4_K_XL (sha e6427665), whose KLD vs HF
bf16 is 0.0045 (Q8_0: 0.0043). tests/test_inkling2_nvfp4.py: 3 tests OK.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: bong-water-water-bong <bong-water-water-bong@1bit.gg>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
timothybrush pushed a commit to timothybrush/subtitleedit that referenced this pull request Nov 24, 2026
Picks up Inkling 2 support (ggml-org/llama.cpp#32217, merged after
b12360). Asset names and both CUDA runtime redistributables are
unchanged. The macOS llama-server executables are byte-identical to
b12360, so those executable lists repeat the b12360 hash.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Nov 25, 2026
… derived kq mask

Re-based onto a691b23.  Upstream ggml-org#29510 (flash_attn_ext_rows, the kv_rows unified-KV
form) and the llm_attn_mask refactor meet this block in 9 files / 48 hunks.

Resolutions worth knowing:
- the kernel signatures carry both parameters (upstream's `KV_rows` then our
  `kq_blocks`); the loaders take upstream's kv_rows `indices` with our native-KV
  arguments; the C-tile sizing keeps the delivery's fp32-aware expression under
  upstream's renamed `AMD_WMMA_256B_AVAILABLE` (256B == RDNA3).
- the derived kq mask MOVED ABI: upstream's kv_rows took src[5], which the derived
  form had been using, so cell_pos/tok_lo/tok_hi are now src[6], src[7], src[8]
  (ggml.c, ggml-cpu/ops.cpp, the CUDA launcher, and both fattn.cu predicates).
  Before the move the derived probe resolved to "not supported" and every batch
  silently fell back to the packed mask.
- the rotation constants are no longer filled per ubatch: upstream ggml-org#31073 keeps them
  on the GPU and consumes them at graph-build time (get_k_rot()), so the block's
  set_input_k_rot/v_rot calls and their declarations (removed from the base by
  upstream) are dropped.
- input classes use upstream's llm_attn_mask (raw/rows) instead of the separate
  kq_mask/kq_mask_cnv members; the derived registration hangs off the dense branch of
  build_attn_inp_attn_mask, which is now a graph-context member so it can add inputs.
  The two compact forms are mutually exclusive and the flash-attention build emits one
  op (kv_rows XOR derived XOR plain).

Validated: build green; derived kq mask enabled ("derived kq mask flash attention
enabled"); derived vs LLAMA_KQ_MASK_DERIVED=0 byte-identical at a 4096-ctx prefill
(149 chars, sha 30c7fc8705a6); q8_0 KV runs with flash attention.

r268 amendment (contributor PR ggml-org#303, `overdoingism`): the launchers' GQA choice asks the ONE mask
predicate.  `ggml_cuda_flash_attn_ext_has_mask()` moves from fattn.cu to fattn-common.cuh (ahead of
the fattn-rdna.cuh include), and both the RDNA band predicate and the tile ncols2 dispatch
(launch_fattn_tile_switch_ncols2) call it instead of asking `src[5]` (the kv_rows form) alone.  Since
upstream ggml-org#29510 took src[5] for kv_rows and moved this block's derived form to src[6..8], a derived op
took the ncols2 = 1 variants on every layout where the tile kernel is the chosen one (RDNA2,
RDNA3_0/RDNA3_5 heads above their WMMA cap, GGML_CUDA_FA_WMMA_256=0): a kernel selection that depended
on which mask form the graph used, plus a GGML_ABORT for the DKQ 320/576 tile instances, which have no
non-GQA arm.  The band hunk is inert by construction (a derived batch is always > 8 tokens, the band
requires <= 8) and is carried so the two sites cannot drift apart again.  Measured (gfx1201, tile
launcher forced with GGML_CUDA_FA_WMMA_MAX_HEAD): all-logits byte-identical to the packed arm and to
r267 on head 256/gqa 4 and head 128/gqa 8 (ncols2 4 and 8 vs 1), pp512 +0.6-1.0 % and +1.3 %, 27B
coherence d45e2221805a unchanged.  tests/test-backend-ops.cpp gains the head-512 aligned derived case
that reaches the tile GQA dispatch on a cap-320 layout (and is the MMA arm on gfx1201).

r308 amendment (field report, gfx1151): the kv_rows probe now REQUIRES the node (`require_observed`), because
its probe graph can be built on a shape that never creates one.  The reserve/probe context carries
`n_kv = kv->get_size()` (the whole PADDED cache extent), and a model's decode arm may depend on that extent
rather than on the used depth: qwen4exp (QSA) decodes dense only while `n_kv < qsa_dense_decode_until`, which
is 32768 on gfx1151.  At `-c 32768` (or any larger ctx, including the model dir's `-c 163840`) the probe
therefore took the SPARSE QSA arm, which builds no rows node at all, so nothing was verified and "Flash
Attention over K/V rows enabled" was logged.  No kernel outside NVIDIA turing-MMA reads the rows form (the
kv_rows branch of ggml_cuda_get_best_fattn_kernel returns NONE on every AMD arch), so the scheduler then
placed every joint attention layer on the CPU backend, silently: on an APU (shared host/device pool) it is a
correctness-preserving but ~3x decode loss, not a fault or a copy storm.

Measured (Strix Halo, gfx1151, the model dir's own flags, `--kv-unified`, ONE active slot, 15.5K depth):
- plain decode `-c 32768`: 25 backend splits in the decode graph and **11.0 t/s**, against **32.5 t/s** with
  `LLAMA_KV_ROWS_DISABLE=1` and 32.5 t/s for `--no-kv-unified`; prefill unaffected (1318 vs 1341 t/s), text
  identical in every arm (the CPU rows FA is correct -- this is a performance defect).
- MTP `draft-mtp n3` with the separate Flash-Next MTP GGUF at `-c 32768`: **18.7 -> 62.4-65.0 t/s
  (3.3-3.5x)**, because the verify band (`n_tokens <= max(8, n_rs_batch)`) takes the same dense arm, so every
  verify step built the rows form too -- and the drafter's own unified context was in the same state.
With the flag the target context reads "was not used in the probe graph, set to disabled", the drafter's
context declines by placement (its one layer IS the rows node), and every graph reads `splits = 1`.

Arches that cannot reach it, verified with the flag in place (the same placement path the fix leaves alone):
gfx1100 (RDNA3_0) and gfx1201 (RDNA4) have `qsa_dense_decode_until` unbounded, so their probe always reaches
the dense arm and declines by placement -- exercised on gfx1151 by forcing that policy
(`LLAMA_QSA_DENSE_DECODE_UNTIL=1000000000`), with and without the drafter: placement decline, `splits = 1`,
60.9 t/s with MTP; and a non-QSA model cannot reach the vacuity at all (Qwen3.6-35B-A3B Q8_0 and Qwen3.8-27B
Q8_0, both with embedded MTP: the node is observed, placed on the CPU, declined, `splits = 1`, 90.2 / 21.9
t/s decode, unchanged by the flag).  An explicit `LLAMA_QSA_DENSE_DECODE_UNTIL` below the context reproduces
the vacuity on ANY arch, which the flag also closes.  A probe that cannot verify an op must disable it,
exactly like the derived kq mask probe next to it.

NOTE FOR THE NEXT EDITOR: `llm_fused_op_probe` is initialized POSITIONALLY -- the `/*.field =*/` designators
in this file are comments, not C++20 designated initializers.  Adding `/*.require_observed =*/ true` as the
fourth value initializes `n_seqs`, leaves the flag false, and measures nothing (the first cut of this
amendment did exactly that); the initializer now lists every field through `require_observed` in struct
order and carries that warning next to it.

r314 (contributor PR ggml-org#329, @overdoingism): the band also takes 128-dim heads whose GQA ratio is not a multiple
of 8 -- ratios 5, 6, 7 and 9..12 (the generic dispatch folds the largest power of two dividing the ratio, so an
odd ratio folds NOTHING and a GQA 7 decode reads each K/V head once per query head).  The predicate, the
`ncols2` dispatch (the 32-column block for every query width: no 64-column band row and no fetch-ahead for this
head size) and the band's 2-D path compiled into the existing 128-dim `ncols1 <= 4` instances -- no new config
rows and no new instances.

Two things were changed from the submission, and both are gated:

* It is **on where it pays, not unconditionally**.  The band adds a fixed per-layer cost (the packed-mask
  prepass and the P = nsm fixup combine) and its round-robin split leaves most blocks idle on a short cache, so
  it only wins once folding ceil(ratio/ncols2_tile) tile passes into ceil(ratio/8) band passes is amortized over
  enough KV cells.  `ggml_cuda_fattn_band_wmma_h128_applies()` tests `K->ne[1] * passes_saved >= 20000`, which
  is the measured crossover of the class (band/tile per-op at the decode width: ratio 5 crosses at 4096 cells,
  ratio 7 at 4096, ratio 10 at 8192, ratio 12 at 32768 -- table in the helper), and **the test is the layer's
  CACHE SIZE, never the used length**: K is a permuted view of the KV cache, so `K->ne[1]` is fixed for the run,
  while a verify batch moves the used length by up to W-1 rows and a length-keyed test would select a different
  kernel for a decode step and its own verify batch.  This matters most on a sliding-window/hybrid model, whose
  windowed layers hold `n_swa + n_ubatch` cells for the whole run: unconditional, the band cost ricursive 65B
  (64 of 80 layers windowed at 1024) 4.5-5.8 % of decode at d0..d32K; with the work gate it is 0 % at d0/d4K and
  -0.5..-0.9 % at d16K/d32K, while a non-SWA 128-dim model at a real context keeps the band everywhere.
  `GGML_HIP_FA_BAND_WMMA_H128`: unset = auto (the work gate), 0 = off (kill switch), 1 = forced on for every
  shape the predicate reaches (the measurement arm); `GGML_HIP_FA_BAND_H128_MIN_WORK` is the tuning constant.
* The 2-D launch is guarded on the compiled instance (`Q->ne[0] == 256 || ncols1 <= 4`) in `launch_fattn`, so a
  128-dim op can never be launched with gridDim.y = P against an instance whose band fast path is compiled out.

Tests: 384 cases -- ratios 5/6/7/12 on 8 and 4 K/V heads, query widths 1..16, q8_0/f16 at kv 512/1024/4096
(a 256-cell masked group at 4096) for the dispatch/tile arm, plus q8_0/f16/bf16 at kv 32768 (past the gate for
every ratio) for the band itself, which is also the band's first bf16 oracle for this head size.

r315 (`TODO` ggml-org#345): the 256-dim head class gets the same work gate.  The band has been a published default
for head 256 since r6 and it is measured to lose on this box's weight-bound decode arms: per op (gfx1201,
head 256, 4 K/V heads, band / tile, the best P of 4/8/16/32/64) GQA 6 at the decode width reads 2.64 (q8_0) /
1.96 (f16) at 512 cells, 2.13 / 1.59 at 1024, 1.30 / 1.89 at 2048, 1.26 / 1.48 at 4096, 0.96 / 1.09 at 8192
and 0.66 / 1.10 at 32768, and end to end (3 GPUs, `-sm tensor`, tg64 against `GGML_HIP_FA_BAND_WMMA=0`) the
27B Q8_0 loses 4.6 % at d0, 35B-A3B Q8_0 9.8 % at d0 and 2.7 % at d8192, Flash-Next GSQ-IQ3_XXS 4.0 % / 2.7 %,
plus 4.7 % on the 27B's `draft-mtp n3` arm.

The gate is `ggml_cuda_fattn_band_wmma_h256_applies()`:
`K->ne[1] * max(passes_saved, 1) >= GGML_HIP_FA_BAND_H256_MIN_WORK` (default 20000), i.e. band from 10000
cells for GQA 6 (3 -> 1 passes) and from 20000 for GQA 8 and GQA 12.  The `max(..., 1)` floor is what handles
a ratio that already folds whole outside the band (GQA 8: the tile kernel's ncols2 is 8 there too, so the band
saves no passes at all) -- it is gated by cells alone instead of being disabled for the whole class, which
would throw away the deep verify widths where it measures 0.45 at 8192 cells.  Per-op crossover of the class
at the decode width is 4-10k cells and at verify widths 1-2k, so 20000 (the 128-dim arm's constant) is on the
conservative side.

Measured with the gate: 27B tg64 44.20 / 44.84 / 44.38 / 43.48 / 41.91 -> 46.13 / 45.65 / 45.18 / 43.55 / 41.90
t/s at d0 / 4K / 8K / 16K / 32K (+4.4 / +1.8 / +1.8 / 0.0 / 0.0 %), 35B-A3B 130.12 / 134.63 -> 139.72 / 138.82
(+7.4 / +3.1 %), Flash-Next 72.04 / 72.70 -> 74.25 / 74.35 (+3.1 / +2.3 %); the deep arm that keeps the band
is unchanged (27B, MTP n7 at a 20.5K prompt, 79.0 -> 78.9 t/s, where the band is +6.7 % over the tile kernel),
and the 27B's `draft-mtp n3` arm at a 5.4K prompt is -1.1 % (the band is worth ~1 % there).  Every changed arm
reproduces the PREVIOUS build's all-tile arm byte for byte -- 35B-A3B `265c381dbc11`; the four MTP axes
`7dca501eeb0e` (R), `759c1a4515c6` (R draft), `fcc0bdeb636b` (P), `eb89102cb7d8` (C), `a87c4318b649` (K).

Corrected here: r314's claim that `K->ne[1]` at the FA op is the layer's KV CACHE SIZE is wrong -- it is the
PADDED USED LENGTH (measured on the 27B at `-c 8192`: 256 at d0, 5376 -> 5632 while generating, 8192 only
during a prompt ubatch or in the graph-RESERVATION pass, whose context sets n_kv = kv->get_size()).  That does
not change r314's measurements -- its d0 row reads 0.0 %, which only a used-length key produces -- and it is
the right attribute to price the crossover with, since it is the number of KV iterations the kernel executes.
What it does mean is that a verify batch can straddle a 256-cell padding boundary and take the other kernel
family for that ONE step: `test-logits-width-probe` at P=9980 (W=1..4 on the tile kernel, W=5..8 on the band)
FAILs with maxdiff 0.327, while every arm with a constant family passes with maxdiff 0.  Accepted and recorded
(`GREEDY-PURITY.md` 96/97) -- keying the gate on the cache size instead would band a shallow context on a large
`-c` and reintroduce exactly these losses.

`TODO` ggml-org#345 route (b) (adaptive `P = min(nsm, ceil(cells/nbatch_fa))`) is refuted and not implemented: at depth
there are no idle blocks to remove (32768 cells / 64 = 512 iterations against P = 32 = nsm), and at a short
cache the idle blocks cost nothing (a block that owns no iteration writes a neutral partial and exits) while a
smaller P serialises the KV iterations -- 512 cells with P = 8 measures 52.6 us against 31.1 for P = 16.
P = 16 is the optimum in 30 of the 36 measured rows; the quantized default P = nsm is 10-20 % off it at most
sizes, which is a separate tuning item (it moves every banded model's numerics).

r316 (TODO ggml-org#346 closed) -- the band's fixup period P stops depending on the K/V type: P = max(2, nsm/2) for
EVERY type now (nsm 32 -> 16), so `ggml_cuda_fattn_band_wmma_two_byte()` and the launcher's P fallback are gone
and `GGML_HIP_FA_BAND_WMMA_SPLIT` stays as the tuning override.  A sweep of the 256-dim class
(`GGML_HIP_FA_BAND_WMMA_SPLIT` 8/16/24/32/48/64/96 x kv 512-102400 x n_q 1/8, q8_0, medians of 3,
test-backend-ops perf) puts the DECODE width's optimum at 16 for both type families and the VERIFY widths' at 8,
so one constant cannot serve both and 16 is the compromise the widths force: P 16 beats the old quantized
default 32 by 5-14 % at kv 16384-102400 (92.9 against 99.5 us at kv 16384/n_q 1, 151.2 against 163.9 at 32768,
425.0 against 447.5 at 102400, 279.7 against 318.4 at 32768/n_q 8) and only loses at the short caches every band
gate keeps off (1024 cells/n_q 1: P 16 55.0 against P 32 42.6 -- measured and recorded, unreachable).  The
long-standing comment claim that the verify cost is "flat for P 48..96 at kv 20K..200K" does not reproduce on
this kernel (verify widths are monotone in P; what is flat is the decode width above P 24) and was replaced.

End to end (3 GPU `-sm tensor`, q8_0 K/V, `ROCBLAS_USE_HIPBLASLT=0`): plain 27B tg64 43.66 / 42.45 t/s at
d16384 / d32768 against 43.53 / 42.62 (noise -- a 27B Q8_0 decode is at the DRAM roof), Ripple-65B 26.07 / 25.41
against 25.96 / 25.44 (noise), and the attention-bound arm that pays: 27B `draft-mtp n7` on the 20.5K prose
prompt 88.91 against 75.83 t/s (+17.2 %, of which ~4.5 %/step is the kernel and the rest the acceptance re-roll a
numeric-order change always carries) and 79.00 against 74.91 at ~10.5K (+5.5 %).  P 8 wins the op-level verify
rows but loses every e2e arm (40.86 t/s at d32768, 75.68 on the 20.5K arm), so it was not taken.

Correctness and purity: `test-backend-ops -o FLASH_ATTN_EXT` 7381/7381 in four arms (default, H256+H128 forced,
`WMMA=0`, `WMMA=2`); `test-logits-width-probe` width purity PASS maxdiff 0 on 37 arms (both head classes, q8_0 /
f16 / bf16, one GPU plus `SPLIT=tensor` and `SPLIT=layer`, P 3584 / 4096 / 10240 -- a constant P cannot
straddle); prefill KLD 0.000000 / 100.000 % at the canonical point, and the family-switch point 0.002733 /
99.243 % (27B) and 0.000823 / 98.981 % (Ripple-65B) against same-kernel controls of 0.004182 / 98.822 % and
0.004133 / 97.772 %.  The four MTP axes are byte-identical to r315 on bf16 K/V (R `7dca501eeb0e` /
`759c1a4515c6`, P `fcc0bdeb636b`, C `eb89102cb7d8`, K `a87c4318b649`, acceptance 348/486, 357/460, 368/427,
372/375 reproduced exactly) and the q8_0 arms carry the same acceptance as r315's own (P-independent: the four
axes sit below the band gate and never reach it).  Every text arm that moved -- 27B q8_0 at a 21K prompt
`f7d157b1e07e` -> `774d1c325068` -- reproduces the previous build's `GGML_HIP_FA_BAND_WMMA_SPLIT=16` arm byte for
byte, and `SPLIT=32` still reproduces the old default.  The 128-dim gate's decisions are unchanged in cell terms
and every one of them is still on the right side of the measured crossover with P 16 (ratio 10: 4096 cells 1.06
loss, 8192 0.88 win; ratio 5: 8192 0.62; ratio 7: 4096 0.60; ratio 12: 8192 1.06 tile, 32768 0.91 band).

Records: `INVARIANTS.md` r316, `GREEDY-PURITY.md` 98, `benchmarks/2026-11-18-band-fixup-period.md`,
`MANIFESTS.md` gate 05, `patches/README.md` block 05, `ENVIRONMENT.md` 8, `TODO.md` (ggml-org#346 deleted).

(r328 re-base) 7 conflicted files / 22 regions.  The maintainer's decision (`DECISIONS.md` D16, option 2) is
that the delivery's FA iteration model wins: upstream 054a1ba (ggml-org#32407, "rotate K/V read order") rewrites
`flash_attn_ext_f16_process_tile` as a contiguous run plus a rotated remainder (nkb_pre/nkb_post, kb0_max
wrap-around), while this block rewrites the same loop as a strided band (kb0_step, a kq_blocks bitmap skip, a
neutral partial for a band block that owns no iteration, and the RDNA4 fetch-ahead ring).  Those are different
partitions of the same work, so a merge would be a third model; the rotation is NOT carried (no nkb_pre,
nkb_post, kb0_max or kb0_rot survives; every kb0_next in the tree is the delivery's own fetch-ahead).

What IS taken from upstream, because it is unrelated to the rotation:
- ggml-org#32217 (Inkling 2) per-head masks: the `+ nb32*(zt_Q % ne32)` term at the three mask-pointer sites of the
  MMA kernel, the `mask` tensor declaration in the tile launcher, and the `mask->ne[2] == 1` conjunct unioned
  into our derived-mask predicate in fattn-tile.cuh and both fattn.cu sites.
- ggml-org#31617's typed warp masks: the seven raw __shfl[_xor]_sync(0xFFFFFFFF, ...) calls in the band code become
  ggml_cuda_shfl_xor / ggml_cuda_shfl (HIP now static_asserts a 64-bit mask).
- build_inp_mem_hybrid_iswa_rel and the build_attn_inp_attn_mask refactor, called through the delivery's
  derived-mask signatures (build_attn_inp_kq_mask(mctx, ubatch, cparams, allow_derived)).
- the FA op-test parameters (n_kv_max, q_head_padding, mask_heads) unioned with derived/derived_hole/mask_hole.
nb32 stays int32_t (upstream widened it to int64_t; the delivery's kernels are the ones in the tree, so the
typedef and the kernels are kept consistent rather than half-widened).

Verified: 4B coherence 100 chars sha=1c5d32ac537d (unchanged); test-backend-ops -o FLASH_ATTN_EXT 7428/7428
with 0 failures, 2/2 backends -- the whole FA matrix, which is the oracle the combined-model option would have
needed at every step; and the block's own switch is non-vacuous on the path it exists for (q8_0 KV,
GGML_CUDA_FA_KV_NATIVE=1 88.6 t/s decode vs 83.9 staged, +5.6 %, identical text 71 chars sha=1de99b7e6ee6;
f16 KV is a wash, as expected -- staging only costs anything for a quantized cache).
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Nov 25, 2026
… derived kq mask

Re-based onto a691b23.  Upstream ggml-org#29510 (flash_attn_ext_rows, the kv_rows unified-KV
form) and the llm_attn_mask refactor meet this block in 9 files / 48 hunks.

Resolutions worth knowing:
- the kernel signatures carry both parameters (upstream's `KV_rows` then our
  `kq_blocks`); the loaders take upstream's kv_rows `indices` with our native-KV
  arguments; the C-tile sizing keeps the delivery's fp32-aware expression under
  upstream's renamed `AMD_WMMA_256B_AVAILABLE` (256B == RDNA3).
- the derived kq mask MOVED ABI: upstream's kv_rows took src[5], which the derived
  form had been using, so cell_pos/tok_lo/tok_hi are now src[6], src[7], src[8]
  (ggml.c, ggml-cpu/ops.cpp, the CUDA launcher, and both fattn.cu predicates).
  Before the move the derived probe resolved to "not supported" and every batch
  silently fell back to the packed mask.
- the rotation constants are no longer filled per ubatch: upstream ggml-org#31073 keeps them
  on the GPU and consumes them at graph-build time (get_k_rot()), so the block's
  set_input_k_rot/v_rot calls and their declarations (removed from the base by
  upstream) are dropped.
- input classes use upstream's llm_attn_mask (raw/rows) instead of the separate
  kq_mask/kq_mask_cnv members; the derived registration hangs off the dense branch of
  build_attn_inp_attn_mask, which is now a graph-context member so it can add inputs.
  The two compact forms are mutually exclusive and the flash-attention build emits one
  op (kv_rows XOR derived XOR plain).

Validated: build green; derived kq mask enabled ("derived kq mask flash attention
enabled"); derived vs LLAMA_KQ_MASK_DERIVED=0 byte-identical at a 4096-ctx prefill
(149 chars, sha 30c7fc8705a6); q8_0 KV runs with flash attention.

r268 amendment (contributor PR ggml-org#303, `overdoingism`): the launchers' GQA choice asks the ONE mask
predicate.  `ggml_cuda_flash_attn_ext_has_mask()` moves from fattn.cu to fattn-common.cuh (ahead of
the fattn-rdna.cuh include), and both the RDNA band predicate and the tile ncols2 dispatch
(launch_fattn_tile_switch_ncols2) call it instead of asking `src[5]` (the kv_rows form) alone.  Since
upstream ggml-org#29510 took src[5] for kv_rows and moved this block's derived form to src[6..8], a derived op
took the ncols2 = 1 variants on every layout where the tile kernel is the chosen one (RDNA2,
RDNA3_0/RDNA3_5 heads above their WMMA cap, GGML_CUDA_FA_WMMA_256=0): a kernel selection that depended
on which mask form the graph used, plus a GGML_ABORT for the DKQ 320/576 tile instances, which have no
non-GQA arm.  The band hunk is inert by construction (a derived batch is always > 8 tokens, the band
requires <= 8) and is carried so the two sites cannot drift apart again.  Measured (gfx1201, tile
launcher forced with GGML_CUDA_FA_WMMA_MAX_HEAD): all-logits byte-identical to the packed arm and to
r267 on head 256/gqa 4 and head 128/gqa 8 (ncols2 4 and 8 vs 1), pp512 +0.6-1.0 % and +1.3 %, 27B
coherence d45e2221805a unchanged.  tests/test-backend-ops.cpp gains the head-512 aligned derived case
that reaches the tile GQA dispatch on a cap-320 layout (and is the MMA arm on gfx1201).

r308 amendment (field report, gfx1151): the kv_rows probe now REQUIRES the node (`require_observed`), because
its probe graph can be built on a shape that never creates one.  The reserve/probe context carries
`n_kv = kv->get_size()` (the whole PADDED cache extent), and a model's decode arm may depend on that extent
rather than on the used depth: qwen4exp (QSA) decodes dense only while `n_kv < qsa_dense_decode_until`, which
is 32768 on gfx1151.  At `-c 32768` (or any larger ctx, including the model dir's `-c 163840`) the probe
therefore took the SPARSE QSA arm, which builds no rows node at all, so nothing was verified and "Flash
Attention over K/V rows enabled" was logged.  No kernel outside NVIDIA turing-MMA reads the rows form (the
kv_rows branch of ggml_cuda_get_best_fattn_kernel returns NONE on every AMD arch), so the scheduler then
placed every joint attention layer on the CPU backend, silently: on an APU (shared host/device pool) it is a
correctness-preserving but ~3x decode loss, not a fault or a copy storm.

Measured (Strix Halo, gfx1151, the model dir's own flags, `--kv-unified`, ONE active slot, 15.5K depth):
- plain decode `-c 32768`: 25 backend splits in the decode graph and **11.0 t/s**, against **32.5 t/s** with
  `LLAMA_KV_ROWS_DISABLE=1` and 32.5 t/s for `--no-kv-unified`; prefill unaffected (1318 vs 1341 t/s), text
  identical in every arm (the CPU rows FA is correct -- this is a performance defect).
- MTP `draft-mtp n3` with the separate Flash-Next MTP GGUF at `-c 32768`: **18.7 -> 62.4-65.0 t/s
  (3.3-3.5x)**, because the verify band (`n_tokens <= max(8, n_rs_batch)`) takes the same dense arm, so every
  verify step built the rows form too -- and the drafter's own unified context was in the same state.
With the flag the target context reads "was not used in the probe graph, set to disabled", the drafter's
context declines by placement (its one layer IS the rows node), and every graph reads `splits = 1`.

Arches that cannot reach it, verified with the flag in place (the same placement path the fix leaves alone):
gfx1100 (RDNA3_0) and gfx1201 (RDNA4) have `qsa_dense_decode_until` unbounded, so their probe always reaches
the dense arm and declines by placement -- exercised on gfx1151 by forcing that policy
(`LLAMA_QSA_DENSE_DECODE_UNTIL=1000000000`), with and without the drafter: placement decline, `splits = 1`,
60.9 t/s with MTP; and a non-QSA model cannot reach the vacuity at all (Qwen3.6-35B-A3B Q8_0 and Qwen3.8-27B
Q8_0, both with embedded MTP: the node is observed, placed on the CPU, declined, `splits = 1`, 90.2 / 21.9
t/s decode, unchanged by the flag).  An explicit `LLAMA_QSA_DENSE_DECODE_UNTIL` below the context reproduces
the vacuity on ANY arch, which the flag also closes.  A probe that cannot verify an op must disable it,
exactly like the derived kq mask probe next to it.

NOTE FOR THE NEXT EDITOR: `llm_fused_op_probe` is initialized POSITIONALLY -- the `/*.field =*/` designators
in this file are comments, not C++20 designated initializers.  Adding `/*.require_observed =*/ true` as the
fourth value initializes `n_seqs`, leaves the flag false, and measures nothing (the first cut of this
amendment did exactly that); the initializer now lists every field through `require_observed` in struct
order and carries that warning next to it.

r314 (contributor PR ggml-org#329, @overdoingism): the band also takes 128-dim heads whose GQA ratio is not a multiple
of 8 -- ratios 5, 6, 7 and 9..12 (the generic dispatch folds the largest power of two dividing the ratio, so an
odd ratio folds NOTHING and a GQA 7 decode reads each K/V head once per query head).  The predicate, the
`ncols2` dispatch (the 32-column block for every query width: no 64-column band row and no fetch-ahead for this
head size) and the band's 2-D path compiled into the existing 128-dim `ncols1 <= 4` instances -- no new config
rows and no new instances.

Two things were changed from the submission, and both are gated:

* It is **on where it pays, not unconditionally**.  The band adds a fixed per-layer cost (the packed-mask
  prepass and the P = nsm fixup combine) and its round-robin split leaves most blocks idle on a short cache, so
  it only wins once folding ceil(ratio/ncols2_tile) tile passes into ceil(ratio/8) band passes is amortized over
  enough KV cells.  `ggml_cuda_fattn_band_wmma_h128_applies()` tests `K->ne[1] * passes_saved >= 20000`, which
  is the measured crossover of the class (band/tile per-op at the decode width: ratio 5 crosses at 4096 cells,
  ratio 7 at 4096, ratio 10 at 8192, ratio 12 at 32768 -- table in the helper), and **the test is the layer's
  CACHE SIZE, never the used length**: K is a permuted view of the KV cache, so `K->ne[1]` is fixed for the run,
  while a verify batch moves the used length by up to W-1 rows and a length-keyed test would select a different
  kernel for a decode step and its own verify batch.  This matters most on a sliding-window/hybrid model, whose
  windowed layers hold `n_swa + n_ubatch` cells for the whole run: unconditional, the band cost ricursive 65B
  (64 of 80 layers windowed at 1024) 4.5-5.8 % of decode at d0..d32K; with the work gate it is 0 % at d0/d4K and
  -0.5..-0.9 % at d16K/d32K, while a non-SWA 128-dim model at a real context keeps the band everywhere.
  `GGML_HIP_FA_BAND_WMMA_H128`: unset = auto (the work gate), 0 = off (kill switch), 1 = forced on for every
  shape the predicate reaches (the measurement arm); `GGML_HIP_FA_BAND_H128_MIN_WORK` is the tuning constant.
* The 2-D launch is guarded on the compiled instance (`Q->ne[0] == 256 || ncols1 <= 4`) in `launch_fattn`, so a
  128-dim op can never be launched with gridDim.y = P against an instance whose band fast path is compiled out.

Tests: 384 cases -- ratios 5/6/7/12 on 8 and 4 K/V heads, query widths 1..16, q8_0/f16 at kv 512/1024/4096
(a 256-cell masked group at 4096) for the dispatch/tile arm, plus q8_0/f16/bf16 at kv 32768 (past the gate for
every ratio) for the band itself, which is also the band's first bf16 oracle for this head size.

r315 (`TODO` ggml-org#345): the 256-dim head class gets the same work gate.  The band has been a published default
for head 256 since r6 and it is measured to lose on this box's weight-bound decode arms: per op (gfx1201,
head 256, 4 K/V heads, band / tile, the best P of 4/8/16/32/64) GQA 6 at the decode width reads 2.64 (q8_0) /
1.96 (f16) at 512 cells, 2.13 / 1.59 at 1024, 1.30 / 1.89 at 2048, 1.26 / 1.48 at 4096, 0.96 / 1.09 at 8192
and 0.66 / 1.10 at 32768, and end to end (3 GPUs, `-sm tensor`, tg64 against `GGML_HIP_FA_BAND_WMMA=0`) the
27B Q8_0 loses 4.6 % at d0, 35B-A3B Q8_0 9.8 % at d0 and 2.7 % at d8192, Flash-Next GSQ-IQ3_XXS 4.0 % / 2.7 %,
plus 4.7 % on the 27B's `draft-mtp n3` arm.

The gate is `ggml_cuda_fattn_band_wmma_h256_applies()`:
`K->ne[1] * max(passes_saved, 1) >= GGML_HIP_FA_BAND_H256_MIN_WORK` (default 20000), i.e. band from 10000
cells for GQA 6 (3 -> 1 passes) and from 20000 for GQA 8 and GQA 12.  The `max(..., 1)` floor is what handles
a ratio that already folds whole outside the band (GQA 8: the tile kernel's ncols2 is 8 there too, so the band
saves no passes at all) -- it is gated by cells alone instead of being disabled for the whole class, which
would throw away the deep verify widths where it measures 0.45 at 8192 cells.  Per-op crossover of the class
at the decode width is 4-10k cells and at verify widths 1-2k, so 20000 (the 128-dim arm's constant) is on the
conservative side.

Measured with the gate: 27B tg64 44.20 / 44.84 / 44.38 / 43.48 / 41.91 -> 46.13 / 45.65 / 45.18 / 43.55 / 41.90
t/s at d0 / 4K / 8K / 16K / 32K (+4.4 / +1.8 / +1.8 / 0.0 / 0.0 %), 35B-A3B 130.12 / 134.63 -> 139.72 / 138.82
(+7.4 / +3.1 %), Flash-Next 72.04 / 72.70 -> 74.25 / 74.35 (+3.1 / +2.3 %); the deep arm that keeps the band
is unchanged (27B, MTP n7 at a 20.5K prompt, 79.0 -> 78.9 t/s, where the band is +6.7 % over the tile kernel),
and the 27B's `draft-mtp n3` arm at a 5.4K prompt is -1.1 % (the band is worth ~1 % there).  Every changed arm
reproduces the PREVIOUS build's all-tile arm byte for byte -- 35B-A3B `265c381dbc11`; the four MTP axes
`7dca501eeb0e` (R), `759c1a4515c6` (R draft), `fcc0bdeb636b` (P), `eb89102cb7d8` (C), `a87c4318b649` (K).

Corrected here: r314's claim that `K->ne[1]` at the FA op is the layer's KV CACHE SIZE is wrong -- it is the
PADDED USED LENGTH (measured on the 27B at `-c 8192`: 256 at d0, 5376 -> 5632 while generating, 8192 only
during a prompt ubatch or in the graph-RESERVATION pass, whose context sets n_kv = kv->get_size()).  That does
not change r314's measurements -- its d0 row reads 0.0 %, which only a used-length key produces -- and it is
the right attribute to price the crossover with, since it is the number of KV iterations the kernel executes.
What it does mean is that a verify batch can straddle a 256-cell padding boundary and take the other kernel
family for that ONE step: `test-logits-width-probe` at P=9980 (W=1..4 on the tile kernel, W=5..8 on the band)
FAILs with maxdiff 0.327, while every arm with a constant family passes with maxdiff 0.  Accepted and recorded
(`GREEDY-PURITY.md` 96/97) -- keying the gate on the cache size instead would band a shallow context on a large
`-c` and reintroduce exactly these losses.

`TODO` ggml-org#345 route (b) (adaptive `P = min(nsm, ceil(cells/nbatch_fa))`) is refuted and not implemented: at depth
there are no idle blocks to remove (32768 cells / 64 = 512 iterations against P = 32 = nsm), and at a short
cache the idle blocks cost nothing (a block that owns no iteration writes a neutral partial and exits) while a
smaller P serialises the KV iterations -- 512 cells with P = 8 measures 52.6 us against 31.1 for P = 16.
P = 16 is the optimum in 30 of the 36 measured rows; the quantized default P = nsm is 10-20 % off it at most
sizes, which is a separate tuning item (it moves every banded model's numerics).

r316 (TODO ggml-org#346 closed) -- the band's fixup period P stops depending on the K/V type: P = max(2, nsm/2) for
EVERY type now (nsm 32 -> 16), so `ggml_cuda_fattn_band_wmma_two_byte()` and the launcher's P fallback are gone
and `GGML_HIP_FA_BAND_WMMA_SPLIT` stays as the tuning override.  A sweep of the 256-dim class
(`GGML_HIP_FA_BAND_WMMA_SPLIT` 8/16/24/32/48/64/96 x kv 512-102400 x n_q 1/8, q8_0, medians of 3,
test-backend-ops perf) puts the DECODE width's optimum at 16 for both type families and the VERIFY widths' at 8,
so one constant cannot serve both and 16 is the compromise the widths force: P 16 beats the old quantized
default 32 by 5-14 % at kv 16384-102400 (92.9 against 99.5 us at kv 16384/n_q 1, 151.2 against 163.9 at 32768,
425.0 against 447.5 at 102400, 279.7 against 318.4 at 32768/n_q 8) and only loses at the short caches every band
gate keeps off (1024 cells/n_q 1: P 16 55.0 against P 32 42.6 -- measured and recorded, unreachable).  The
long-standing comment claim that the verify cost is "flat for P 48..96 at kv 20K..200K" does not reproduce on
this kernel (verify widths are monotone in P; what is flat is the decode width above P 24) and was replaced.

End to end (3 GPU `-sm tensor`, q8_0 K/V, `ROCBLAS_USE_HIPBLASLT=0`): plain 27B tg64 43.66 / 42.45 t/s at
d16384 / d32768 against 43.53 / 42.62 (noise -- a 27B Q8_0 decode is at the DRAM roof), Ripple-65B 26.07 / 25.41
against 25.96 / 25.44 (noise), and the attention-bound arm that pays: 27B `draft-mtp n7` on the 20.5K prose
prompt 88.91 against 75.83 t/s (+17.2 %, of which ~4.5 %/step is the kernel and the rest the acceptance re-roll a
numeric-order change always carries) and 79.00 against 74.91 at ~10.5K (+5.5 %).  P 8 wins the op-level verify
rows but loses every e2e arm (40.86 t/s at d32768, 75.68 on the 20.5K arm), so it was not taken.

Correctness and purity: `test-backend-ops -o FLASH_ATTN_EXT` 7381/7381 in four arms (default, H256+H128 forced,
`WMMA=0`, `WMMA=2`); `test-logits-width-probe` width purity PASS maxdiff 0 on 37 arms (both head classes, q8_0 /
f16 / bf16, one GPU plus `SPLIT=tensor` and `SPLIT=layer`, P 3584 / 4096 / 10240 -- a constant P cannot
straddle); prefill KLD 0.000000 / 100.000 % at the canonical point, and the family-switch point 0.002733 /
99.243 % (27B) and 0.000823 / 98.981 % (Ripple-65B) against same-kernel controls of 0.004182 / 98.822 % and
0.004133 / 97.772 %.  The four MTP axes are byte-identical to r315 on bf16 K/V (R `7dca501eeb0e` /
`759c1a4515c6`, P `fcc0bdeb636b`, C `eb89102cb7d8`, K `a87c4318b649`, acceptance 348/486, 357/460, 368/427,
372/375 reproduced exactly) and the q8_0 arms carry the same acceptance as r315's own (P-independent: the four
axes sit below the band gate and never reach it).  Every text arm that moved -- 27B q8_0 at a 21K prompt
`f7d157b1e07e` -> `774d1c325068` -- reproduces the previous build's `GGML_HIP_FA_BAND_WMMA_SPLIT=16` arm byte for
byte, and `SPLIT=32` still reproduces the old default.  The 128-dim gate's decisions are unchanged in cell terms
and every one of them is still on the right side of the measured crossover with P 16 (ratio 10: 4096 cells 1.06
loss, 8192 0.88 win; ratio 5: 8192 0.62; ratio 7: 4096 0.60; ratio 12: 8192 1.06 tile, 32768 0.91 band).

Records: `INVARIANTS.md` r316, `GREEDY-PURITY.md` 98, `benchmarks/2026-11-18-band-fixup-period.md`,
`MANIFESTS.md` gate 05, `patches/README.md` block 05, `ENVIRONMENT.md` 8, `TODO.md` (ggml-org#346 deleted).

(r328 re-base) 7 conflicted files / 22 regions.  The maintainer's decision (`DECISIONS.md` D16, option 2) is
that the delivery's FA iteration model wins: upstream 054a1ba (ggml-org#32407, "rotate K/V read order") rewrites
`flash_attn_ext_f16_process_tile` as a contiguous run plus a rotated remainder (nkb_pre/nkb_post, kb0_max
wrap-around), while this block rewrites the same loop as a strided band (kb0_step, a kq_blocks bitmap skip, a
neutral partial for a band block that owns no iteration, and the RDNA4 fetch-ahead ring).  Those are different
partitions of the same work, so a merge would be a third model; the rotation is NOT carried (no nkb_pre,
nkb_post, kb0_max or kb0_rot survives; every kb0_next in the tree is the delivery's own fetch-ahead).

What IS taken from upstream, because it is unrelated to the rotation:
- ggml-org#32217 (Inkling 2) per-head masks: the `+ nb32*(zt_Q % ne32)` term at the three mask-pointer sites of the
  MMA kernel, the `mask` tensor declaration in the tile launcher, and the `mask->ne[2] == 1` conjunct unioned
  into our derived-mask predicate in fattn-tile.cuh and both fattn.cu sites.
- ggml-org#31617's typed warp masks: the seven raw __shfl[_xor]_sync(0xFFFFFFFF, ...) calls in the band code become
  ggml_cuda_shfl_xor / ggml_cuda_shfl (HIP now static_asserts a 64-bit mask).
- build_inp_mem_hybrid_iswa_rel and the build_attn_inp_attn_mask refactor, called through the delivery's
  derived-mask signatures (build_attn_inp_kq_mask(mctx, ubatch, cparams, allow_derived)).
- the FA op-test parameters (n_kv_max, q_head_padding, mask_heads) unioned with derived/derived_hole/mask_hole.
nb32 stays int32_t (upstream widened it to int64_t; the delivery's kernels are the ones in the tree, so the
typedef and the kernels are kept consistent rather than half-widened).

Verified: 4B coherence 100 chars sha=1c5d32ac537d (unchanged); test-backend-ops -o FLASH_ATTN_EXT 7428/7428
with 0 failures, 2/2 backends -- the whole FA matrix, which is the oracle the combined-model option would have
needed at every step; and the block's own switch is non-vacuous on the path it exists for (q8_0 KV,
GGML_CUDA_FA_KV_NATIVE=1 88.6 t/s decode vs 83.9 staged, +5.6 %, identical text 71 chars sha=1de99b7e6ee6;
f16 KV is a wash, as expected -- staging only costs anything for a quantized cache).
Nindaleth pushed a commit to Nindaleth/llama.cpp that referenced this pull request Nov 26, 2026
* 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 <son@huggingface.co>
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 <son@huggingface.co>
(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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>
(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 <noreply@anthropic.com>

* 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 <sigbjorn.skjaeret@huggingface.co>

* Update src/llama-model.h

Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@huggingface.co>

---------

Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@huggingface.co>
(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 <noreply@anthropic.com>

* 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 <e.zhou@chocolat.chaud.io>

* 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 <admin@serveurperso.com>
Co-authored-by: Piotr Wilkin (ilintar) <piotr.wilkin@syndatis.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Xuan-Son Nguyen <son@huggingface.co>
Co-authored-by: Aldehir Rojas <hello@alde.dev>
Co-authored-by: Bartowski <3266127+bartowski1182@users.noreply.github.com>
Co-authored-by: Daniel Han <danielhanchen@gmail.com>
Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@huggingface.co>
Co-authored-by: Pedro Cuenca <pedro@huggingface.co>
Co-authored-by: Aman Gupta <aman.gupta@tether.io>
Co-authored-by: Eddie Zhou <e.zhou@chocolat.chaud.io>
@Clarck1

Clarck1 commented Nov 26, 2026

Copy link
Copy Markdown

Small thing I noticed while running Inkling-2-Mini: every model load prints

load: special_eos_id is not in special_eog_ids - the tokenizer config may be incorrect

The GGUF sets both eos_token_id and eot_token_id to <|content_model_end_sampling|> (200006), but this token is not in the text-based EOG list in src/llama-vocab.cpp. The sanity check right after adds it anyway, so generation stops fine. It is only the warning.

One line after the k2-horizon entry removes it:

|| t.first == "<|content_model_end_sampling|>" // inkling

The token is already CONTROL type in the GGUF, and the same token is used by the Inkling and Inkling 2 Small templates in models/templates. Tested on top of b12776 with llama-tokenize: 1 warning before, 0 after.

If you think it is worth it, could this go in a follow-up?

cc @CISC @rinpatch (vocab side)

Assisted-by: Claude Opus 5.5

KyleAnthonyShepherd pushed a commit to KyleAnthonyShepherd/llama.cpp that referenced this pull request Nov 27, 2026
* 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 <son@huggingface.co>
(cherry picked from commit 5c008e0)
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Nov 27, 2026
… derived kq mask

Re-based onto a691b23.  Upstream ggml-org#29510 (flash_attn_ext_rows, the kv_rows unified-KV
form) and the llm_attn_mask refactor meet this block in 9 files / 48 hunks.

Resolutions worth knowing:
- the kernel signatures carry both parameters (upstream's `KV_rows` then our
  `kq_blocks`); the loaders take upstream's kv_rows `indices` with our native-KV
  arguments; the C-tile sizing keeps the delivery's fp32-aware expression under
  upstream's renamed `AMD_WMMA_256B_AVAILABLE` (256B == RDNA3).
- the derived kq mask MOVED ABI: upstream's kv_rows took src[5], which the derived
  form had been using, so cell_pos/tok_lo/tok_hi are now src[6], src[7], src[8]
  (ggml.c, ggml-cpu/ops.cpp, the CUDA launcher, and both fattn.cu predicates).
  Before the move the derived probe resolved to "not supported" and every batch
  silently fell back to the packed mask.
- the rotation constants are no longer filled per ubatch: upstream ggml-org#31073 keeps them
  on the GPU and consumes them at graph-build time (get_k_rot()), so the block's
  set_input_k_rot/v_rot calls and their declarations (removed from the base by
  upstream) are dropped.
- input classes use upstream's llm_attn_mask (raw/rows) instead of the separate
  kq_mask/kq_mask_cnv members; the derived registration hangs off the dense branch of
  build_attn_inp_attn_mask, which is now a graph-context member so it can add inputs.
  The two compact forms are mutually exclusive and the flash-attention build emits one
  op (kv_rows XOR derived XOR plain).

Validated: build green; derived kq mask enabled ("derived kq mask flash attention
enabled"); derived vs LLAMA_KQ_MASK_DERIVED=0 byte-identical at a 4096-ctx prefill
(149 chars, sha 30c7fc8705a6); q8_0 KV runs with flash attention.

r268 amendment (contributor PR ggml-org#303, `overdoingism`): the launchers' GQA choice asks the ONE mask
predicate.  `ggml_cuda_flash_attn_ext_has_mask()` moves from fattn.cu to fattn-common.cuh (ahead of
the fattn-rdna.cuh include), and both the RDNA band predicate and the tile ncols2 dispatch
(launch_fattn_tile_switch_ncols2) call it instead of asking `src[5]` (the kv_rows form) alone.  Since
upstream ggml-org#29510 took src[5] for kv_rows and moved this block's derived form to src[6..8], a derived op
took the ncols2 = 1 variants on every layout where the tile kernel is the chosen one (RDNA2,
RDNA3_0/RDNA3_5 heads above their WMMA cap, GGML_CUDA_FA_WMMA_256=0): a kernel selection that depended
on which mask form the graph used, plus a GGML_ABORT for the DKQ 320/576 tile instances, which have no
non-GQA arm.  The band hunk is inert by construction (a derived batch is always > 8 tokens, the band
requires <= 8) and is carried so the two sites cannot drift apart again.  Measured (gfx1201, tile
launcher forced with GGML_CUDA_FA_WMMA_MAX_HEAD): all-logits byte-identical to the packed arm and to
r267 on head 256/gqa 4 and head 128/gqa 8 (ncols2 4 and 8 vs 1), pp512 +0.6-1.0 % and +1.3 %, 27B
coherence d45e2221805a unchanged.  tests/test-backend-ops.cpp gains the head-512 aligned derived case
that reaches the tile GQA dispatch on a cap-320 layout (and is the MMA arm on gfx1201).

r308 amendment (field report, gfx1151): the kv_rows probe now REQUIRES the node (`require_observed`), because
its probe graph can be built on a shape that never creates one.  The reserve/probe context carries
`n_kv = kv->get_size()` (the whole PADDED cache extent), and a model's decode arm may depend on that extent
rather than on the used depth: qwen4exp (QSA) decodes dense only while `n_kv < qsa_dense_decode_until`, which
is 32768 on gfx1151.  At `-c 32768` (or any larger ctx, including the model dir's `-c 163840`) the probe
therefore took the SPARSE QSA arm, which builds no rows node at all, so nothing was verified and "Flash
Attention over K/V rows enabled" was logged.  No kernel outside NVIDIA turing-MMA reads the rows form (the
kv_rows branch of ggml_cuda_get_best_fattn_kernel returns NONE on every AMD arch), so the scheduler then
placed every joint attention layer on the CPU backend, silently: on an APU (shared host/device pool) it is a
correctness-preserving but ~3x decode loss, not a fault or a copy storm.

Measured (Strix Halo, gfx1151, the model dir's own flags, `--kv-unified`, ONE active slot, 15.5K depth):
- plain decode `-c 32768`: 25 backend splits in the decode graph and **11.0 t/s**, against **32.5 t/s** with
  `LLAMA_KV_ROWS_DISABLE=1` and 32.5 t/s for `--no-kv-unified`; prefill unaffected (1318 vs 1341 t/s), text
  identical in every arm (the CPU rows FA is correct -- this is a performance defect).
- MTP `draft-mtp n3` with the separate Flash-Next MTP GGUF at `-c 32768`: **18.7 -> 62.4-65.0 t/s
  (3.3-3.5x)**, because the verify band (`n_tokens <= max(8, n_rs_batch)`) takes the same dense arm, so every
  verify step built the rows form too -- and the drafter's own unified context was in the same state.
With the flag the target context reads "was not used in the probe graph, set to disabled", the drafter's
context declines by placement (its one layer IS the rows node), and every graph reads `splits = 1`.

Arches that cannot reach it, verified with the flag in place (the same placement path the fix leaves alone):
gfx1100 (RDNA3_0) and gfx1201 (RDNA4) have `qsa_dense_decode_until` unbounded, so their probe always reaches
the dense arm and declines by placement -- exercised on gfx1151 by forcing that policy
(`LLAMA_QSA_DENSE_DECODE_UNTIL=1000000000`), with and without the drafter: placement decline, `splits = 1`,
60.9 t/s with MTP; and a non-QSA model cannot reach the vacuity at all (Qwen3.6-35B-A3B Q8_0 and Qwen3.8-27B
Q8_0, both with embedded MTP: the node is observed, placed on the CPU, declined, `splits = 1`, 90.2 / 21.9
t/s decode, unchanged by the flag).  An explicit `LLAMA_QSA_DENSE_DECODE_UNTIL` below the context reproduces
the vacuity on ANY arch, which the flag also closes.  A probe that cannot verify an op must disable it,
exactly like the derived kq mask probe next to it.

NOTE FOR THE NEXT EDITOR: `llm_fused_op_probe` is initialized POSITIONALLY -- the `/*.field =*/` designators
in this file are comments, not C++20 designated initializers.  Adding `/*.require_observed =*/ true` as the
fourth value initializes `n_seqs`, leaves the flag false, and measures nothing (the first cut of this
amendment did exactly that); the initializer now lists every field through `require_observed` in struct
order and carries that warning next to it.

r314 (contributor PR ggml-org#329, @overdoingism): the band also takes 128-dim heads whose GQA ratio is not a multiple
of 8 -- ratios 5, 6, 7 and 9..12 (the generic dispatch folds the largest power of two dividing the ratio, so an
odd ratio folds NOTHING and a GQA 7 decode reads each K/V head once per query head).  The predicate, the
`ncols2` dispatch (the 32-column block for every query width: no 64-column band row and no fetch-ahead for this
head size) and the band's 2-D path compiled into the existing 128-dim `ncols1 <= 4` instances -- no new config
rows and no new instances.

Two things were changed from the submission, and both are gated:

* It is **on where it pays, not unconditionally**.  The band adds a fixed per-layer cost (the packed-mask
  prepass and the P = nsm fixup combine) and its round-robin split leaves most blocks idle on a short cache, so
  it only wins once folding ceil(ratio/ncols2_tile) tile passes into ceil(ratio/8) band passes is amortized over
  enough KV cells.  `ggml_cuda_fattn_band_wmma_h128_applies()` tests `K->ne[1] * passes_saved >= 20000`, which
  is the measured crossover of the class (band/tile per-op at the decode width: ratio 5 crosses at 4096 cells,
  ratio 7 at 4096, ratio 10 at 8192, ratio 12 at 32768 -- table in the helper), and **the test is the layer's
  CACHE SIZE, never the used length**: K is a permuted view of the KV cache, so `K->ne[1]` is fixed for the run,
  while a verify batch moves the used length by up to W-1 rows and a length-keyed test would select a different
  kernel for a decode step and its own verify batch.  This matters most on a sliding-window/hybrid model, whose
  windowed layers hold `n_swa + n_ubatch` cells for the whole run: unconditional, the band cost ricursive 65B
  (64 of 80 layers windowed at 1024) 4.5-5.8 % of decode at d0..d32K; with the work gate it is 0 % at d0/d4K and
  -0.5..-0.9 % at d16K/d32K, while a non-SWA 128-dim model at a real context keeps the band everywhere.
  `GGML_HIP_FA_BAND_WMMA_H128`: unset = auto (the work gate), 0 = off (kill switch), 1 = forced on for every
  shape the predicate reaches (the measurement arm); `GGML_HIP_FA_BAND_H128_MIN_WORK` is the tuning constant.
* The 2-D launch is guarded on the compiled instance (`Q->ne[0] == 256 || ncols1 <= 4`) in `launch_fattn`, so a
  128-dim op can never be launched with gridDim.y = P against an instance whose band fast path is compiled out.

Tests: 384 cases -- ratios 5/6/7/12 on 8 and 4 K/V heads, query widths 1..16, q8_0/f16 at kv 512/1024/4096
(a 256-cell masked group at 4096) for the dispatch/tile arm, plus q8_0/f16/bf16 at kv 32768 (past the gate for
every ratio) for the band itself, which is also the band's first bf16 oracle for this head size.

r315 (`TODO` ggml-org#345): the 256-dim head class gets the same work gate.  The band has been a published default
for head 256 since r6 and it is measured to lose on this box's weight-bound decode arms: per op (gfx1201,
head 256, 4 K/V heads, band / tile, the best P of 4/8/16/32/64) GQA 6 at the decode width reads 2.64 (q8_0) /
1.96 (f16) at 512 cells, 2.13 / 1.59 at 1024, 1.30 / 1.89 at 2048, 1.26 / 1.48 at 4096, 0.96 / 1.09 at 8192
and 0.66 / 1.10 at 32768, and end to end (3 GPUs, `-sm tensor`, tg64 against `GGML_HIP_FA_BAND_WMMA=0`) the
27B Q8_0 loses 4.6 % at d0, 35B-A3B Q8_0 9.8 % at d0 and 2.7 % at d8192, Flash-Next GSQ-IQ3_XXS 4.0 % / 2.7 %,
plus 4.7 % on the 27B's `draft-mtp n3` arm.

The gate is `ggml_cuda_fattn_band_wmma_h256_applies()`:
`K->ne[1] * max(passes_saved, 1) >= GGML_HIP_FA_BAND_H256_MIN_WORK` (default 20000), i.e. band from 10000
cells for GQA 6 (3 -> 1 passes) and from 20000 for GQA 8 and GQA 12.  The `max(..., 1)` floor is what handles
a ratio that already folds whole outside the band (GQA 8: the tile kernel's ncols2 is 8 there too, so the band
saves no passes at all) -- it is gated by cells alone instead of being disabled for the whole class, which
would throw away the deep verify widths where it measures 0.45 at 8192 cells.  Per-op crossover of the class
at the decode width is 4-10k cells and at verify widths 1-2k, so 20000 (the 128-dim arm's constant) is on the
conservative side.

Measured with the gate: 27B tg64 44.20 / 44.84 / 44.38 / 43.48 / 41.91 -> 46.13 / 45.65 / 45.18 / 43.55 / 41.90
t/s at d0 / 4K / 8K / 16K / 32K (+4.4 / +1.8 / +1.8 / 0.0 / 0.0 %), 35B-A3B 130.12 / 134.63 -> 139.72 / 138.82
(+7.4 / +3.1 %), Flash-Next 72.04 / 72.70 -> 74.25 / 74.35 (+3.1 / +2.3 %); the deep arm that keeps the band
is unchanged (27B, MTP n7 at a 20.5K prompt, 79.0 -> 78.9 t/s, where the band is +6.7 % over the tile kernel),
and the 27B's `draft-mtp n3` arm at a 5.4K prompt is -1.1 % (the band is worth ~1 % there).  Every changed arm
reproduces the PREVIOUS build's all-tile arm byte for byte -- 35B-A3B `265c381dbc11`; the four MTP axes
`7dca501eeb0e` (R), `759c1a4515c6` (R draft), `fcc0bdeb636b` (P), `eb89102cb7d8` (C), `a87c4318b649` (K).

Corrected here: r314's claim that `K->ne[1]` at the FA op is the layer's KV CACHE SIZE is wrong -- it is the
PADDED USED LENGTH (measured on the 27B at `-c 8192`: 256 at d0, 5376 -> 5632 while generating, 8192 only
during a prompt ubatch or in the graph-RESERVATION pass, whose context sets n_kv = kv->get_size()).  That does
not change r314's measurements -- its d0 row reads 0.0 %, which only a used-length key produces -- and it is
the right attribute to price the crossover with, since it is the number of KV iterations the kernel executes.
What it does mean is that a verify batch can straddle a 256-cell padding boundary and take the other kernel
family for that ONE step: `test-logits-width-probe` at P=9980 (W=1..4 on the tile kernel, W=5..8 on the band)
FAILs with maxdiff 0.327, while every arm with a constant family passes with maxdiff 0.  Accepted and recorded
(`GREEDY-PURITY.md` 96/97) -- keying the gate on the cache size instead would band a shallow context on a large
`-c` and reintroduce exactly these losses.

`TODO` ggml-org#345 route (b) (adaptive `P = min(nsm, ceil(cells/nbatch_fa))`) is refuted and not implemented: at depth
there are no idle blocks to remove (32768 cells / 64 = 512 iterations against P = 32 = nsm), and at a short
cache the idle blocks cost nothing (a block that owns no iteration writes a neutral partial and exits) while a
smaller P serialises the KV iterations -- 512 cells with P = 8 measures 52.6 us against 31.1 for P = 16.
P = 16 is the optimum in 30 of the 36 measured rows; the quantized default P = nsm is 10-20 % off it at most
sizes, which is a separate tuning item (it moves every banded model's numerics).

r316 (TODO ggml-org#346 closed) -- the band's fixup period P stops depending on the K/V type: P = max(2, nsm/2) for
EVERY type now (nsm 32 -> 16), so `ggml_cuda_fattn_band_wmma_two_byte()` and the launcher's P fallback are gone
and `GGML_HIP_FA_BAND_WMMA_SPLIT` stays as the tuning override.  A sweep of the 256-dim class
(`GGML_HIP_FA_BAND_WMMA_SPLIT` 8/16/24/32/48/64/96 x kv 512-102400 x n_q 1/8, q8_0, medians of 3,
test-backend-ops perf) puts the DECODE width's optimum at 16 for both type families and the VERIFY widths' at 8,
so one constant cannot serve both and 16 is the compromise the widths force: P 16 beats the old quantized
default 32 by 5-14 % at kv 16384-102400 (92.9 against 99.5 us at kv 16384/n_q 1, 151.2 against 163.9 at 32768,
425.0 against 447.5 at 102400, 279.7 against 318.4 at 32768/n_q 8) and only loses at the short caches every band
gate keeps off (1024 cells/n_q 1: P 16 55.0 against P 32 42.6 -- measured and recorded, unreachable).  The
long-standing comment claim that the verify cost is "flat for P 48..96 at kv 20K..200K" does not reproduce on
this kernel (verify widths are monotone in P; what is flat is the decode width above P 24) and was replaced.

End to end (3 GPU `-sm tensor`, q8_0 K/V, `ROCBLAS_USE_HIPBLASLT=0`): plain 27B tg64 43.66 / 42.45 t/s at
d16384 / d32768 against 43.53 / 42.62 (noise -- a 27B Q8_0 decode is at the DRAM roof), Ripple-65B 26.07 / 25.41
against 25.96 / 25.44 (noise), and the attention-bound arm that pays: 27B `draft-mtp n7` on the 20.5K prose
prompt 88.91 against 75.83 t/s (+17.2 %, of which ~4.5 %/step is the kernel and the rest the acceptance re-roll a
numeric-order change always carries) and 79.00 against 74.91 at ~10.5K (+5.5 %).  P 8 wins the op-level verify
rows but loses every e2e arm (40.86 t/s at d32768, 75.68 on the 20.5K arm), so it was not taken.

Correctness and purity: `test-backend-ops -o FLASH_ATTN_EXT` 7381/7381 in four arms (default, H256+H128 forced,
`WMMA=0`, `WMMA=2`); `test-logits-width-probe` width purity PASS maxdiff 0 on 37 arms (both head classes, q8_0 /
f16 / bf16, one GPU plus `SPLIT=tensor` and `SPLIT=layer`, P 3584 / 4096 / 10240 -- a constant P cannot
straddle); prefill KLD 0.000000 / 100.000 % at the canonical point, and the family-switch point 0.002733 /
99.243 % (27B) and 0.000823 / 98.981 % (Ripple-65B) against same-kernel controls of 0.004182 / 98.822 % and
0.004133 / 97.772 %.  The four MTP axes are byte-identical to r315 on bf16 K/V (R `7dca501eeb0e` /
`759c1a4515c6`, P `fcc0bdeb636b`, C `eb89102cb7d8`, K `a87c4318b649`, acceptance 348/486, 357/460, 368/427,
372/375 reproduced exactly) and the q8_0 arms carry the same acceptance as r315's own (P-independent: the four
axes sit below the band gate and never reach it).  Every text arm that moved -- 27B q8_0 at a 21K prompt
`f7d157b1e07e` -> `774d1c325068` -- reproduces the previous build's `GGML_HIP_FA_BAND_WMMA_SPLIT=16` arm byte for
byte, and `SPLIT=32` still reproduces the old default.  The 128-dim gate's decisions are unchanged in cell terms
and every one of them is still on the right side of the measured crossover with P 16 (ratio 10: 4096 cells 1.06
loss, 8192 0.88 win; ratio 5: 8192 0.62; ratio 7: 4096 0.60; ratio 12: 8192 1.06 tile, 32768 0.91 band).

Records: `INVARIANTS.md` r316, `GREEDY-PURITY.md` 98, `benchmarks/2026-11-18-band-fixup-period.md`,
`MANIFESTS.md` gate 05, `patches/README.md` block 05, `ENVIRONMENT.md` 8, `TODO.md` (ggml-org#346 deleted).

(r328 re-base) 7 conflicted files / 22 regions.  The maintainer's decision (`DECISIONS.md` D16, option 2) is
that the delivery's FA iteration model wins: upstream 054a1ba (ggml-org#32407, "rotate K/V read order") rewrites
`flash_attn_ext_f16_process_tile` as a contiguous run plus a rotated remainder (nkb_pre/nkb_post, kb0_max
wrap-around), while this block rewrites the same loop as a strided band (kb0_step, a kq_blocks bitmap skip, a
neutral partial for a band block that owns no iteration, and the RDNA4 fetch-ahead ring).  Those are different
partitions of the same work, so a merge would be a third model; the rotation is NOT carried (no nkb_pre,
nkb_post, kb0_max or kb0_rot survives; every kb0_next in the tree is the delivery's own fetch-ahead).

What IS taken from upstream, because it is unrelated to the rotation:
- ggml-org#32217 (Inkling 2) per-head masks: the `+ nb32*(zt_Q % ne32)` term at the three mask-pointer sites of the
  MMA kernel, the `mask` tensor declaration in the tile launcher, and the `mask->ne[2] == 1` conjunct unioned
  into our derived-mask predicate in fattn-tile.cuh and both fattn.cu sites.
- ggml-org#31617's typed warp masks: the seven raw __shfl[_xor]_sync(0xFFFFFFFF, ...) calls in the band code become
  ggml_cuda_shfl_xor / ggml_cuda_shfl (HIP now static_asserts a 64-bit mask).
- build_inp_mem_hybrid_iswa_rel and the build_attn_inp_attn_mask refactor, called through the delivery's
  derived-mask signatures (build_attn_inp_kq_mask(mctx, ubatch, cparams, allow_derived)).
- the FA op-test parameters (n_kv_max, q_head_padding, mask_heads) unioned with derived/derived_hole/mask_hole.
nb32 stays int32_t (upstream widened it to int64_t; the delivery's kernels are the ones in the tree, so the
typedef and the kernels are kept consistent rather than half-widened).

Verified: 4B coherence 100 chars sha=1c5d32ac537d (unchanged); test-backend-ops -o FLASH_ATTN_EXT 7428/7428
with 0 failures, 2/2 backends -- the whole FA matrix, which is the oracle the combined-model option would have
needed at every step; and the block's own switch is non-vacuous on the path it exists for (q8_0 KV,
GGML_CUDA_FA_KV_NATIVE=1 88.6 t/s decode vs 83.9 staged, +5.6 %, identical text 71 chars sha=1de99b7e6ee6;
f16 KV is a wash, as expected -- staging only costs anything for a quantized cache).
Co-authored-by: briansp2020 <bsp2020@gmail.com>
Co-authored-by: jstamagal <jstamagal@users.noreply.github.com>
Co-authored-by: RikshaDriver <RikshaDriver@users.noreply.github.com>
Co-authored-by: d32768 <d32768@users.noreply.github.com>
Reported-by: a-n-t-0 <a-n-t-0@users.noreply.github.com>
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Nov 28, 2026
… derived kq mask

Re-based onto a691b23.  Upstream ggml-org#29510 (flash_attn_ext_rows, the kv_rows unified-KV
form) and the llm_attn_mask refactor meet this block in 9 files / 48 hunks.

Resolutions worth knowing:
- the kernel signatures carry both parameters (upstream's `KV_rows` then our
  `kq_blocks`); the loaders take upstream's kv_rows `indices` with our native-KV
  arguments; the C-tile sizing keeps the delivery's fp32-aware expression under
  upstream's renamed `AMD_WMMA_256B_AVAILABLE` (256B == RDNA3).
- the derived kq mask MOVED ABI: upstream's kv_rows took src[5], which the derived
  form had been using, so cell_pos/tok_lo/tok_hi are now src[6], src[7], src[8]
  (ggml.c, ggml-cpu/ops.cpp, the CUDA launcher, and both fattn.cu predicates).
  Before the move the derived probe resolved to "not supported" and every batch
  silently fell back to the packed mask.
- the rotation constants are no longer filled per ubatch: upstream ggml-org#31073 keeps them
  on the GPU and consumes them at graph-build time (get_k_rot()), so the block's
  set_input_k_rot/v_rot calls and their declarations (removed from the base by
  upstream) are dropped.
- input classes use upstream's llm_attn_mask (raw/rows) instead of the separate
  kq_mask/kq_mask_cnv members; the derived registration hangs off the dense branch of
  build_attn_inp_attn_mask, which is now a graph-context member so it can add inputs.
  The two compact forms are mutually exclusive and the flash-attention build emits one
  op (kv_rows XOR derived XOR plain).

Validated: build green; derived kq mask enabled ("derived kq mask flash attention
enabled"); derived vs LLAMA_KQ_MASK_DERIVED=0 byte-identical at a 4096-ctx prefill
(149 chars, sha 30c7fc8705a6); q8_0 KV runs with flash attention.

r268 amendment (contributor PR ggml-org#303, `overdoingism`): the launchers' GQA choice asks the ONE mask
predicate.  `ggml_cuda_flash_attn_ext_has_mask()` moves from fattn.cu to fattn-common.cuh (ahead of
the fattn-rdna.cuh include), and both the RDNA band predicate and the tile ncols2 dispatch
(launch_fattn_tile_switch_ncols2) call it instead of asking `src[5]` (the kv_rows form) alone.  Since
upstream ggml-org#29510 took src[5] for kv_rows and moved this block's derived form to src[6..8], a derived op
took the ncols2 = 1 variants on every layout where the tile kernel is the chosen one (RDNA2,
RDNA3_0/RDNA3_5 heads above their WMMA cap, GGML_CUDA_FA_WMMA_256=0): a kernel selection that depended
on which mask form the graph used, plus a GGML_ABORT for the DKQ 320/576 tile instances, which have no
non-GQA arm.  The band hunk is inert by construction (a derived batch is always > 8 tokens, the band
requires <= 8) and is carried so the two sites cannot drift apart again.  Measured (gfx1201, tile
launcher forced with GGML_CUDA_FA_WMMA_MAX_HEAD): all-logits byte-identical to the packed arm and to
r267 on head 256/gqa 4 and head 128/gqa 8 (ncols2 4 and 8 vs 1), pp512 +0.6-1.0 % and +1.3 %, 27B
coherence d45e2221805a unchanged.  tests/test-backend-ops.cpp gains the head-512 aligned derived case
that reaches the tile GQA dispatch on a cap-320 layout (and is the MMA arm on gfx1201).

r308 amendment (field report, gfx1151): the kv_rows probe now REQUIRES the node (`require_observed`), because
its probe graph can be built on a shape that never creates one.  The reserve/probe context carries
`n_kv = kv->get_size()` (the whole PADDED cache extent), and a model's decode arm may depend on that extent
rather than on the used depth: qwen4exp (QSA) decodes dense only while `n_kv < qsa_dense_decode_until`, which
is 32768 on gfx1151.  At `-c 32768` (or any larger ctx, including the model dir's `-c 163840`) the probe
therefore took the SPARSE QSA arm, which builds no rows node at all, so nothing was verified and "Flash
Attention over K/V rows enabled" was logged.  No kernel outside NVIDIA turing-MMA reads the rows form (the
kv_rows branch of ggml_cuda_get_best_fattn_kernel returns NONE on every AMD arch), so the scheduler then
placed every joint attention layer on the CPU backend, silently: on an APU (shared host/device pool) it is a
correctness-preserving but ~3x decode loss, not a fault or a copy storm.

Measured (Strix Halo, gfx1151, the model dir's own flags, `--kv-unified`, ONE active slot, 15.5K depth):
- plain decode `-c 32768`: 25 backend splits in the decode graph and **11.0 t/s**, against **32.5 t/s** with
  `LLAMA_KV_ROWS_DISABLE=1` and 32.5 t/s for `--no-kv-unified`; prefill unaffected (1318 vs 1341 t/s), text
  identical in every arm (the CPU rows FA is correct -- this is a performance defect).
- MTP `draft-mtp n3` with the separate Flash-Next MTP GGUF at `-c 32768`: **18.7 -> 62.4-65.0 t/s
  (3.3-3.5x)**, because the verify band (`n_tokens <= max(8, n_rs_batch)`) takes the same dense arm, so every
  verify step built the rows form too -- and the drafter's own unified context was in the same state.
With the flag the target context reads "was not used in the probe graph, set to disabled", the drafter's
context declines by placement (its one layer IS the rows node), and every graph reads `splits = 1`.

Arches that cannot reach it, verified with the flag in place (the same placement path the fix leaves alone):
gfx1100 (RDNA3_0) and gfx1201 (RDNA4) have `qsa_dense_decode_until` unbounded, so their probe always reaches
the dense arm and declines by placement -- exercised on gfx1151 by forcing that policy
(`LLAMA_QSA_DENSE_DECODE_UNTIL=1000000000`), with and without the drafter: placement decline, `splits = 1`,
60.9 t/s with MTP; and a non-QSA model cannot reach the vacuity at all (Qwen3.6-35B-A3B Q8_0 and Qwen3.8-27B
Q8_0, both with embedded MTP: the node is observed, placed on the CPU, declined, `splits = 1`, 90.2 / 21.9
t/s decode, unchanged by the flag).  An explicit `LLAMA_QSA_DENSE_DECODE_UNTIL` below the context reproduces
the vacuity on ANY arch, which the flag also closes.  A probe that cannot verify an op must disable it,
exactly like the derived kq mask probe next to it.

NOTE FOR THE NEXT EDITOR: `llm_fused_op_probe` is initialized POSITIONALLY -- the `/*.field =*/` designators
in this file are comments, not C++20 designated initializers.  Adding `/*.require_observed =*/ true` as the
fourth value initializes `n_seqs`, leaves the flag false, and measures nothing (the first cut of this
amendment did exactly that); the initializer now lists every field through `require_observed` in struct
order and carries that warning next to it.

r314 (contributor PR ggml-org#329, @overdoingism): the band also takes 128-dim heads whose GQA ratio is not a multiple
of 8 -- ratios 5, 6, 7 and 9..12 (the generic dispatch folds the largest power of two dividing the ratio, so an
odd ratio folds NOTHING and a GQA 7 decode reads each K/V head once per query head).  The predicate, the
`ncols2` dispatch (the 32-column block for every query width: no 64-column band row and no fetch-ahead for this
head size) and the band's 2-D path compiled into the existing 128-dim `ncols1 <= 4` instances -- no new config
rows and no new instances.

Two things were changed from the submission, and both are gated:

* It is **on where it pays, not unconditionally**.  The band adds a fixed per-layer cost (the packed-mask
  prepass and the P = nsm fixup combine) and its round-robin split leaves most blocks idle on a short cache, so
  it only wins once folding ceil(ratio/ncols2_tile) tile passes into ceil(ratio/8) band passes is amortized over
  enough KV cells.  `ggml_cuda_fattn_band_wmma_h128_applies()` tests `K->ne[1] * passes_saved >= 20000`, which
  is the measured crossover of the class (band/tile per-op at the decode width: ratio 5 crosses at 4096 cells,
  ratio 7 at 4096, ratio 10 at 8192, ratio 12 at 32768 -- table in the helper), and **the test is the layer's
  CACHE SIZE, never the used length**: K is a permuted view of the KV cache, so `K->ne[1]` is fixed for the run,
  while a verify batch moves the used length by up to W-1 rows and a length-keyed test would select a different
  kernel for a decode step and its own verify batch.  This matters most on a sliding-window/hybrid model, whose
  windowed layers hold `n_swa + n_ubatch` cells for the whole run: unconditional, the band cost ricursive 65B
  (64 of 80 layers windowed at 1024) 4.5-5.8 % of decode at d0..d32K; with the work gate it is 0 % at d0/d4K and
  -0.5..-0.9 % at d16K/d32K, while a non-SWA 128-dim model at a real context keeps the band everywhere.
  `GGML_HIP_FA_BAND_WMMA_H128`: unset = auto (the work gate), 0 = off (kill switch), 1 = forced on for every
  shape the predicate reaches (the measurement arm); `GGML_HIP_FA_BAND_H128_MIN_WORK` is the tuning constant.
* The 2-D launch is guarded on the compiled instance (`Q->ne[0] == 256 || ncols1 <= 4`) in `launch_fattn`, so a
  128-dim op can never be launched with gridDim.y = P against an instance whose band fast path is compiled out.

Tests: 384 cases -- ratios 5/6/7/12 on 8 and 4 K/V heads, query widths 1..16, q8_0/f16 at kv 512/1024/4096
(a 256-cell masked group at 4096) for the dispatch/tile arm, plus q8_0/f16/bf16 at kv 32768 (past the gate for
every ratio) for the band itself, which is also the band's first bf16 oracle for this head size.

r315 (`TODO` ggml-org#345): the 256-dim head class gets the same work gate.  The band has been a published default
for head 256 since r6 and it is measured to lose on this box's weight-bound decode arms: per op (gfx1201,
head 256, 4 K/V heads, band / tile, the best P of 4/8/16/32/64) GQA 6 at the decode width reads 2.64 (q8_0) /
1.96 (f16) at 512 cells, 2.13 / 1.59 at 1024, 1.30 / 1.89 at 2048, 1.26 / 1.48 at 4096, 0.96 / 1.09 at 8192
and 0.66 / 1.10 at 32768, and end to end (3 GPUs, `-sm tensor`, tg64 against `GGML_HIP_FA_BAND_WMMA=0`) the
27B Q8_0 loses 4.6 % at d0, 35B-A3B Q8_0 9.8 % at d0 and 2.7 % at d8192, Flash-Next GSQ-IQ3_XXS 4.0 % / 2.7 %,
plus 4.7 % on the 27B's `draft-mtp n3` arm.

The gate is `ggml_cuda_fattn_band_wmma_h256_applies()`:
`K->ne[1] * max(passes_saved, 1) >= GGML_HIP_FA_BAND_H256_MIN_WORK` (default 20000), i.e. band from 10000
cells for GQA 6 (3 -> 1 passes) and from 20000 for GQA 8 and GQA 12.  The `max(..., 1)` floor is what handles
a ratio that already folds whole outside the band (GQA 8: the tile kernel's ncols2 is 8 there too, so the band
saves no passes at all) -- it is gated by cells alone instead of being disabled for the whole class, which
would throw away the deep verify widths where it measures 0.45 at 8192 cells.  Per-op crossover of the class
at the decode width is 4-10k cells and at verify widths 1-2k, so 20000 (the 128-dim arm's constant) is on the
conservative side.

Measured with the gate: 27B tg64 44.20 / 44.84 / 44.38 / 43.48 / 41.91 -> 46.13 / 45.65 / 45.18 / 43.55 / 41.90
t/s at d0 / 4K / 8K / 16K / 32K (+4.4 / +1.8 / +1.8 / 0.0 / 0.0 %), 35B-A3B 130.12 / 134.63 -> 139.72 / 138.82
(+7.4 / +3.1 %), Flash-Next 72.04 / 72.70 -> 74.25 / 74.35 (+3.1 / +2.3 %); the deep arm that keeps the band
is unchanged (27B, MTP n7 at a 20.5K prompt, 79.0 -> 78.9 t/s, where the band is +6.7 % over the tile kernel),
and the 27B's `draft-mtp n3` arm at a 5.4K prompt is -1.1 % (the band is worth ~1 % there).  Every changed arm
reproduces the PREVIOUS build's all-tile arm byte for byte -- 35B-A3B `265c381dbc11`; the four MTP axes
`7dca501eeb0e` (R), `759c1a4515c6` (R draft), `fcc0bdeb636b` (P), `eb89102cb7d8` (C), `a87c4318b649` (K).

Corrected here: r314's claim that `K->ne[1]` at the FA op is the layer's KV CACHE SIZE is wrong -- it is the
PADDED USED LENGTH (measured on the 27B at `-c 8192`: 256 at d0, 5376 -> 5632 while generating, 8192 only
during a prompt ubatch or in the graph-RESERVATION pass, whose context sets n_kv = kv->get_size()).  That does
not change r314's measurements -- its d0 row reads 0.0 %, which only a used-length key produces -- and it is
the right attribute to price the crossover with, since it is the number of KV iterations the kernel executes.
What it does mean is that a verify batch can straddle a 256-cell padding boundary and take the other kernel
family for that ONE step: `test-logits-width-probe` at P=9980 (W=1..4 on the tile kernel, W=5..8 on the band)
FAILs with maxdiff 0.327, while every arm with a constant family passes with maxdiff 0.  Accepted and recorded
(`GREEDY-PURITY.md` 96/97) -- keying the gate on the cache size instead would band a shallow context on a large
`-c` and reintroduce exactly these losses.

`TODO` ggml-org#345 route (b) (adaptive `P = min(nsm, ceil(cells/nbatch_fa))`) is refuted and not implemented: at depth
there are no idle blocks to remove (32768 cells / 64 = 512 iterations against P = 32 = nsm), and at a short
cache the idle blocks cost nothing (a block that owns no iteration writes a neutral partial and exits) while a
smaller P serialises the KV iterations -- 512 cells with P = 8 measures 52.6 us against 31.1 for P = 16.
P = 16 is the optimum in 30 of the 36 measured rows; the quantized default P = nsm is 10-20 % off it at most
sizes, which is a separate tuning item (it moves every banded model's numerics).

r316 (TODO ggml-org#346 closed) -- the band's fixup period P stops depending on the K/V type: P = max(2, nsm/2) for
EVERY type now (nsm 32 -> 16), so `ggml_cuda_fattn_band_wmma_two_byte()` and the launcher's P fallback are gone
and `GGML_HIP_FA_BAND_WMMA_SPLIT` stays as the tuning override.  A sweep of the 256-dim class
(`GGML_HIP_FA_BAND_WMMA_SPLIT` 8/16/24/32/48/64/96 x kv 512-102400 x n_q 1/8, q8_0, medians of 3,
test-backend-ops perf) puts the DECODE width's optimum at 16 for both type families and the VERIFY widths' at 8,
so one constant cannot serve both and 16 is the compromise the widths force: P 16 beats the old quantized
default 32 by 5-14 % at kv 16384-102400 (92.9 against 99.5 us at kv 16384/n_q 1, 151.2 against 163.9 at 32768,
425.0 against 447.5 at 102400, 279.7 against 318.4 at 32768/n_q 8) and only loses at the short caches every band
gate keeps off (1024 cells/n_q 1: P 16 55.0 against P 32 42.6 -- measured and recorded, unreachable).  The
long-standing comment claim that the verify cost is "flat for P 48..96 at kv 20K..200K" does not reproduce on
this kernel (verify widths are monotone in P; what is flat is the decode width above P 24) and was replaced.

End to end (3 GPU `-sm tensor`, q8_0 K/V, `ROCBLAS_USE_HIPBLASLT=0`): plain 27B tg64 43.66 / 42.45 t/s at
d16384 / d32768 against 43.53 / 42.62 (noise -- a 27B Q8_0 decode is at the DRAM roof), Ripple-65B 26.07 / 25.41
against 25.96 / 25.44 (noise), and the attention-bound arm that pays: 27B `draft-mtp n7` on the 20.5K prose
prompt 88.91 against 75.83 t/s (+17.2 %, of which ~4.5 %/step is the kernel and the rest the acceptance re-roll a
numeric-order change always carries) and 79.00 against 74.91 at ~10.5K (+5.5 %).  P 8 wins the op-level verify
rows but loses every e2e arm (40.86 t/s at d32768, 75.68 on the 20.5K arm), so it was not taken.

Correctness and purity: `test-backend-ops -o FLASH_ATTN_EXT` 7381/7381 in four arms (default, H256+H128 forced,
`WMMA=0`, `WMMA=2`); `test-logits-width-probe` width purity PASS maxdiff 0 on 37 arms (both head classes, q8_0 /
f16 / bf16, one GPU plus `SPLIT=tensor` and `SPLIT=layer`, P 3584 / 4096 / 10240 -- a constant P cannot
straddle); prefill KLD 0.000000 / 100.000 % at the canonical point, and the family-switch point 0.002733 /
99.243 % (27B) and 0.000823 / 98.981 % (Ripple-65B) against same-kernel controls of 0.004182 / 98.822 % and
0.004133 / 97.772 %.  The four MTP axes are byte-identical to r315 on bf16 K/V (R `7dca501eeb0e` /
`759c1a4515c6`, P `fcc0bdeb636b`, C `eb89102cb7d8`, K `a87c4318b649`, acceptance 348/486, 357/460, 368/427,
372/375 reproduced exactly) and the q8_0 arms carry the same acceptance as r315's own (P-independent: the four
axes sit below the band gate and never reach it).  Every text arm that moved -- 27B q8_0 at a 21K prompt
`f7d157b1e07e` -> `774d1c325068` -- reproduces the previous build's `GGML_HIP_FA_BAND_WMMA_SPLIT=16` arm byte for
byte, and `SPLIT=32` still reproduces the old default.  The 128-dim gate's decisions are unchanged in cell terms
and every one of them is still on the right side of the measured crossover with P 16 (ratio 10: 4096 cells 1.06
loss, 8192 0.88 win; ratio 5: 8192 0.62; ratio 7: 4096 0.60; ratio 12: 8192 1.06 tile, 32768 0.91 band).

Records: `INVARIANTS.md` r316, `GREEDY-PURITY.md` 98, `benchmarks/2026-11-18-band-fixup-period.md`,
`MANIFESTS.md` gate 05, `patches/README.md` block 05, `ENVIRONMENT.md` 8, `TODO.md` (ggml-org#346 deleted).

(r328 re-base) 7 conflicted files / 22 regions.  The maintainer's decision (`DECISIONS.md` D16, option 2) is
that the delivery's FA iteration model wins: upstream 054a1ba (ggml-org#32407, "rotate K/V read order") rewrites
`flash_attn_ext_f16_process_tile` as a contiguous run plus a rotated remainder (nkb_pre/nkb_post, kb0_max
wrap-around), while this block rewrites the same loop as a strided band (kb0_step, a kq_blocks bitmap skip, a
neutral partial for a band block that owns no iteration, and the RDNA4 fetch-ahead ring).  Those are different
partitions of the same work, so a merge would be a third model; the rotation is NOT carried (no nkb_pre,
nkb_post, kb0_max or kb0_rot survives; every kb0_next in the tree is the delivery's own fetch-ahead).

What IS taken from upstream, because it is unrelated to the rotation:
- ggml-org#32217 (Inkling 2) per-head masks: the `+ nb32*(zt_Q % ne32)` term at the three mask-pointer sites of the
  MMA kernel, the `mask` tensor declaration in the tile launcher, and the `mask->ne[2] == 1` conjunct unioned
  into our derived-mask predicate in fattn-tile.cuh and both fattn.cu sites.
- ggml-org#31617's typed warp masks: the seven raw __shfl[_xor]_sync(0xFFFFFFFF, ...) calls in the band code become
  ggml_cuda_shfl_xor / ggml_cuda_shfl (HIP now static_asserts a 64-bit mask).
- build_inp_mem_hybrid_iswa_rel and the build_attn_inp_attn_mask refactor, called through the delivery's
  derived-mask signatures (build_attn_inp_kq_mask(mctx, ubatch, cparams, allow_derived)).
- the FA op-test parameters (n_kv_max, q_head_padding, mask_heads) unioned with derived/derived_hole/mask_hole.
nb32 stays int32_t (upstream widened it to int64_t; the delivery's kernels are the ones in the tree, so the
typedef and the kernels are kept consistent rather than half-widened).

Verified: 4B coherence 100 chars sha=1c5d32ac537d (unchanged); test-backend-ops -o FLASH_ATTN_EXT 7428/7428
with 0 failures, 2/2 backends -- the whole FA matrix, which is the oracle the combined-model option would have
needed at every step; and the block's own switch is non-vacuous on the path it exists for (q8_0 KV,
GGML_CUDA_FA_KV_NATIVE=1 88.6 t/s decode vs 83.9 staged, +5.6 %, identical text 71 chars sha=1de99b7e6ee6;
f16 KV is a wash, as expected -- staging only costs anything for a quantized cache).
r372 amendment (GitHub issue ggml-org#381, `@mjohanning99`; the RDNA3 half is upstream PR
ggml-org#31746 by `@ravel7524`): head-256 prefill attention under a tensor split, both halves.

1. RDNA4 keeps the stock AMD ncols2 rule WHEN THE GQA GROUP DIVIDES.  The split-aware rule (r285) is
   blind to the GQA ratio: with gqa_ratio 6 it picks ncols2 = 8 and PADS the group of 6 to 8, so a
   quarter of the prefill KQ/VKQ work is padding (at ub 1024, 256 blocks of 64 columns per launch
   instead of 192).  The stock AMD rule divides the group (ncols2 = 2) and pads nothing.
   `GGML_CUDA_FA_RDNA4_GQA_STOCK=0` restores the split-aware rule; RDNA3_5's row is untouched.
   Measured (pp4096, -ub 1024, r2, 2 alternating rounds per arm, this 27B head-256 GQA-6 model):
   2 x R9700 -sm tensor q8_0 2536.9 -> 2509.7 d0 (+1.1 %), 1852.7 vs 1752.3 d32768 (+5.7 %), 1295.5 vs
   1211.1 d81920 (+7.0 %); 3 x R9700 f16 (the split-aware rule's own tuning configuration) +1.7 / +6.2 /
   +6.6 % at the same depths, and +9.0 % at the r285 pp150000 point itself (1086.5 vs 996.7 t/s).
   Neutral where the group already divides: 4B head-256 gqa 4 (+0.2 % at d81920), 35B-A3B head-128
   gqa 4 (+0.0 %), Gemma4-31B head-512 gqa 2 (0.0 %).  Decode is unchanged (tg128 34.40 vs 34.54, the
   band owns it) and a single device is inert by construction: the hint is false, so the switch is
   never consulted (1489.8/1482.7 d0, 1016.8/1025.3 d32768 = noise).

2. RDNA3_0 (gfx1100/gfx1101/gfx1102) head 256 with 2-4 Q heads per KV head takes the upstream ggml-org#31746
   row: Q streamed from LDS, ONE K batch and one V batch per iteration, and its scheduling fence
   (`__builtin_amdgcn_sched_barrier` after each WMMA, or the compiler hoists the next batch's operand
   loads and spills).  RDNA3_5 keeps its own Strix Halo row -- it was tuned separately and is not
   covered by that PR's measurements.  Measured on gfx1100 (RX 7900 XTX, 27B Q4_K_M, q8_0 KV, pp4096,
   ABBA): 1225.1 -> 1225.8 d0 (neutral), 863.6 -> 918.0 d32768 (+6.3 %), 604.1 -> 672.2 d81920 (+11.3 %).

Purity.  The RDNA4 switch moves the Q-row blocking (ncols1 = 64/ncols2, ncols unchanged) and through
ntiles_x -> blocks_per_wave -> pick_parallel_blocks the number of partial KV blocks, so prefill is NOT
bit-identical even at constant ncols: same-seed greedy text is identical on q8_0 and f16 at 3 devices
(399 chars, sha 10a82b5559a9), and the prefill-logit point reads mean KLD 0.000542 / same-top-p 98.81 %
(q8_0) and 0.000529 / 98.92 % (f16) against the split-aware arm, versus a same-kernel -ub 256 control
measured on the spot of 0.000581 / 98.83 % and 0.000580 / 98.86 % -- the change is the model's ordinary
summation-order sensitivity, not a defect (the reporter measured the same class: 0.0185 against a
0.0207-0.0211 ubatch control).  The RDNA3_0 row changes only the online-softmax batching
(nbatch_fa 64 -> 32) and where Q is staged, and reads 0.000051 / 99.71 % on gfx1100 against a same-kernel
-ub 256 control of 0.005210 / 95.9 % -- 100x tighter than a reordering the delivery already accepts.
Its deterministic greedy text DOES move on the gfx1100 f16 arm at a 1818-token prompt (482 chars,
sha 6e2f7d2de955 -> 414 chars, sha 0a644af79489; the q8_0 arm is unchanged at 6e2f7d2de955), which is a
near-tie inside that 5e-5 KLD, not a different arithmetic.  FLASH_ATTN_EXT at hsk=256 on gfx1100:
906/906.

Co-authored-by: Marvin Johanning <3389797+mjohanning99@users.noreply.github.com>
Co-authored-by: ravel7524 <58877666+ravel7524@users.noreply.github.com>
Co-authored-by: briansp2020 <bsp2020@gmail.com>
Co-authored-by: jstamagal <jstamagal@users.noreply.github.com>
Co-authored-by: RikshaDriver <RikshaDriver@users.noreply.github.com>
Co-authored-by: d32768 <d32768@users.noreply.github.com>
Reported-by: a-n-t-0 <a-n-t-0@users.noreply.github.com>
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Nov 28, 2026
… derived kq mask

Re-based onto a691b23.  Upstream ggml-org#29510 (flash_attn_ext_rows, the kv_rows unified-KV
form) and the llm_attn_mask refactor meet this block in 9 files / 48 hunks.

Resolutions worth knowing:
- the kernel signatures carry both parameters (upstream's `KV_rows` then our
  `kq_blocks`); the loaders take upstream's kv_rows `indices` with our native-KV
  arguments; the C-tile sizing keeps the delivery's fp32-aware expression under
  upstream's renamed `AMD_WMMA_256B_AVAILABLE` (256B == RDNA3).
- the derived kq mask MOVED ABI: upstream's kv_rows took src[5], which the derived
  form had been using, so cell_pos/tok_lo/tok_hi are now src[6], src[7], src[8]
  (ggml.c, ggml-cpu/ops.cpp, the CUDA launcher, and both fattn.cu predicates).
  Before the move the derived probe resolved to "not supported" and every batch
  silently fell back to the packed mask.
- the rotation constants are no longer filled per ubatch: upstream ggml-org#31073 keeps them
  on the GPU and consumes them at graph-build time (get_k_rot()), so the block's
  set_input_k_rot/v_rot calls and their declarations (removed from the base by
  upstream) are dropped.
- input classes use upstream's llm_attn_mask (raw/rows) instead of the separate
  kq_mask/kq_mask_cnv members; the derived registration hangs off the dense branch of
  build_attn_inp_attn_mask, which is now a graph-context member so it can add inputs.
  The two compact forms are mutually exclusive and the flash-attention build emits one
  op (kv_rows XOR derived XOR plain).

Validated: build green; derived kq mask enabled ("derived kq mask flash attention
enabled"); derived vs LLAMA_KQ_MASK_DERIVED=0 byte-identical at a 4096-ctx prefill
(149 chars, sha 30c7fc8705a6); q8_0 KV runs with flash attention.

r268 amendment (contributor PR ggml-org#303, `overdoingism`): the launchers' GQA choice asks the ONE mask
predicate.  `ggml_cuda_flash_attn_ext_has_mask()` moves from fattn.cu to fattn-common.cuh (ahead of
the fattn-rdna.cuh include), and both the RDNA band predicate and the tile ncols2 dispatch
(launch_fattn_tile_switch_ncols2) call it instead of asking `src[5]` (the kv_rows form) alone.  Since
upstream ggml-org#29510 took src[5] for kv_rows and moved this block's derived form to src[6..8], a derived op
took the ncols2 = 1 variants on every layout where the tile kernel is the chosen one (RDNA2,
RDNA3_0/RDNA3_5 heads above their WMMA cap, GGML_CUDA_FA_WMMA_256=0): a kernel selection that depended
on which mask form the graph used, plus a GGML_ABORT for the DKQ 320/576 tile instances, which have no
non-GQA arm.  The band hunk is inert by construction (a derived batch is always > 8 tokens, the band
requires <= 8) and is carried so the two sites cannot drift apart again.  Measured (gfx1201, tile
launcher forced with GGML_CUDA_FA_WMMA_MAX_HEAD): all-logits byte-identical to the packed arm and to
r267 on head 256/gqa 4 and head 128/gqa 8 (ncols2 4 and 8 vs 1), pp512 +0.6-1.0 % and +1.3 %, 27B
coherence d45e2221805a unchanged.  tests/test-backend-ops.cpp gains the head-512 aligned derived case
that reaches the tile GQA dispatch on a cap-320 layout (and is the MMA arm on gfx1201).

r308 amendment (field report, gfx1151): the kv_rows probe now REQUIRES the node (`require_observed`), because
its probe graph can be built on a shape that never creates one.  The reserve/probe context carries
`n_kv = kv->get_size()` (the whole PADDED cache extent), and a model's decode arm may depend on that extent
rather than on the used depth: qwen4exp (QSA) decodes dense only while `n_kv < qsa_dense_decode_until`, which
is 32768 on gfx1151.  At `-c 32768` (or any larger ctx, including the model dir's `-c 163840`) the probe
therefore took the SPARSE QSA arm, which builds no rows node at all, so nothing was verified and "Flash
Attention over K/V rows enabled" was logged.  No kernel outside NVIDIA turing-MMA reads the rows form (the
kv_rows branch of ggml_cuda_get_best_fattn_kernel returns NONE on every AMD arch), so the scheduler then
placed every joint attention layer on the CPU backend, silently: on an APU (shared host/device pool) it is a
correctness-preserving but ~3x decode loss, not a fault or a copy storm.

Measured (Strix Halo, gfx1151, the model dir's own flags, `--kv-unified`, ONE active slot, 15.5K depth):
- plain decode `-c 32768`: 25 backend splits in the decode graph and **11.0 t/s**, against **32.5 t/s** with
  `LLAMA_KV_ROWS_DISABLE=1` and 32.5 t/s for `--no-kv-unified`; prefill unaffected (1318 vs 1341 t/s), text
  identical in every arm (the CPU rows FA is correct -- this is a performance defect).
- MTP `draft-mtp n3` with the separate Flash-Next MTP GGUF at `-c 32768`: **18.7 -> 62.4-65.0 t/s
  (3.3-3.5x)**, because the verify band (`n_tokens <= max(8, n_rs_batch)`) takes the same dense arm, so every
  verify step built the rows form too -- and the drafter's own unified context was in the same state.
With the flag the target context reads "was not used in the probe graph, set to disabled", the drafter's
context declines by placement (its one layer IS the rows node), and every graph reads `splits = 1`.

Arches that cannot reach it, verified with the flag in place (the same placement path the fix leaves alone):
gfx1100 (RDNA3_0) and gfx1201 (RDNA4) have `qsa_dense_decode_until` unbounded, so their probe always reaches
the dense arm and declines by placement -- exercised on gfx1151 by forcing that policy
(`LLAMA_QSA_DENSE_DECODE_UNTIL=1000000000`), with and without the drafter: placement decline, `splits = 1`,
60.9 t/s with MTP; and a non-QSA model cannot reach the vacuity at all (Qwen3.6-35B-A3B Q8_0 and Qwen3.8-27B
Q8_0, both with embedded MTP: the node is observed, placed on the CPU, declined, `splits = 1`, 90.2 / 21.9
t/s decode, unchanged by the flag).  An explicit `LLAMA_QSA_DENSE_DECODE_UNTIL` below the context reproduces
the vacuity on ANY arch, which the flag also closes.  A probe that cannot verify an op must disable it,
exactly like the derived kq mask probe next to it.

NOTE FOR THE NEXT EDITOR: `llm_fused_op_probe` is initialized POSITIONALLY -- the `/*.field =*/` designators
in this file are comments, not C++20 designated initializers.  Adding `/*.require_observed =*/ true` as the
fourth value initializes `n_seqs`, leaves the flag false, and measures nothing (the first cut of this
amendment did exactly that); the initializer now lists every field through `require_observed` in struct
order and carries that warning next to it.

r314 (contributor PR ggml-org#329, @overdoingism): the band also takes 128-dim heads whose GQA ratio is not a multiple
of 8 -- ratios 5, 6, 7 and 9..12 (the generic dispatch folds the largest power of two dividing the ratio, so an
odd ratio folds NOTHING and a GQA 7 decode reads each K/V head once per query head).  The predicate, the
`ncols2` dispatch (the 32-column block for every query width: no 64-column band row and no fetch-ahead for this
head size) and the band's 2-D path compiled into the existing 128-dim `ncols1 <= 4` instances -- no new config
rows and no new instances.

Two things were changed from the submission, and both are gated:

* It is **on where it pays, not unconditionally**.  The band adds a fixed per-layer cost (the packed-mask
  prepass and the P = nsm fixup combine) and its round-robin split leaves most blocks idle on a short cache, so
  it only wins once folding ceil(ratio/ncols2_tile) tile passes into ceil(ratio/8) band passes is amortized over
  enough KV cells.  `ggml_cuda_fattn_band_wmma_h128_applies()` tests `K->ne[1] * passes_saved >= 20000`, which
  is the measured crossover of the class (band/tile per-op at the decode width: ratio 5 crosses at 4096 cells,
  ratio 7 at 4096, ratio 10 at 8192, ratio 12 at 32768 -- table in the helper), and **the test is the layer's
  CACHE SIZE, never the used length**: K is a permuted view of the KV cache, so `K->ne[1]` is fixed for the run,
  while a verify batch moves the used length by up to W-1 rows and a length-keyed test would select a different
  kernel for a decode step and its own verify batch.  This matters most on a sliding-window/hybrid model, whose
  windowed layers hold `n_swa + n_ubatch` cells for the whole run: unconditional, the band cost ricursive 65B
  (64 of 80 layers windowed at 1024) 4.5-5.8 % of decode at d0..d32K; with the work gate it is 0 % at d0/d4K and
  -0.5..-0.9 % at d16K/d32K, while a non-SWA 128-dim model at a real context keeps the band everywhere.
  `GGML_HIP_FA_BAND_WMMA_H128`: unset = auto (the work gate), 0 = off (kill switch), 1 = forced on for every
  shape the predicate reaches (the measurement arm); `GGML_HIP_FA_BAND_H128_MIN_WORK` is the tuning constant.
* The 2-D launch is guarded on the compiled instance (`Q->ne[0] == 256 || ncols1 <= 4`) in `launch_fattn`, so a
  128-dim op can never be launched with gridDim.y = P against an instance whose band fast path is compiled out.

Tests: 384 cases -- ratios 5/6/7/12 on 8 and 4 K/V heads, query widths 1..16, q8_0/f16 at kv 512/1024/4096
(a 256-cell masked group at 4096) for the dispatch/tile arm, plus q8_0/f16/bf16 at kv 32768 (past the gate for
every ratio) for the band itself, which is also the band's first bf16 oracle for this head size.

r315 (`TODO` ggml-org#345): the 256-dim head class gets the same work gate.  The band has been a published default
for head 256 since r6 and it is measured to lose on this box's weight-bound decode arms: per op (gfx1201,
head 256, 4 K/V heads, band / tile, the best P of 4/8/16/32/64) GQA 6 at the decode width reads 2.64 (q8_0) /
1.96 (f16) at 512 cells, 2.13 / 1.59 at 1024, 1.30 / 1.89 at 2048, 1.26 / 1.48 at 4096, 0.96 / 1.09 at 8192
and 0.66 / 1.10 at 32768, and end to end (3 GPUs, `-sm tensor`, tg64 against `GGML_HIP_FA_BAND_WMMA=0`) the
27B Q8_0 loses 4.6 % at d0, 35B-A3B Q8_0 9.8 % at d0 and 2.7 % at d8192, Flash-Next GSQ-IQ3_XXS 4.0 % / 2.7 %,
plus 4.7 % on the 27B's `draft-mtp n3` arm.

The gate is `ggml_cuda_fattn_band_wmma_h256_applies()`:
`K->ne[1] * max(passes_saved, 1) >= GGML_HIP_FA_BAND_H256_MIN_WORK` (default 20000), i.e. band from 10000
cells for GQA 6 (3 -> 1 passes) and from 20000 for GQA 8 and GQA 12.  The `max(..., 1)` floor is what handles
a ratio that already folds whole outside the band (GQA 8: the tile kernel's ncols2 is 8 there too, so the band
saves no passes at all) -- it is gated by cells alone instead of being disabled for the whole class, which
would throw away the deep verify widths where it measures 0.45 at 8192 cells.  Per-op crossover of the class
at the decode width is 4-10k cells and at verify widths 1-2k, so 20000 (the 128-dim arm's constant) is on the
conservative side.

Measured with the gate: 27B tg64 44.20 / 44.84 / 44.38 / 43.48 / 41.91 -> 46.13 / 45.65 / 45.18 / 43.55 / 41.90
t/s at d0 / 4K / 8K / 16K / 32K (+4.4 / +1.8 / +1.8 / 0.0 / 0.0 %), 35B-A3B 130.12 / 134.63 -> 139.72 / 138.82
(+7.4 / +3.1 %), Flash-Next 72.04 / 72.70 -> 74.25 / 74.35 (+3.1 / +2.3 %); the deep arm that keeps the band
is unchanged (27B, MTP n7 at a 20.5K prompt, 79.0 -> 78.9 t/s, where the band is +6.7 % over the tile kernel),
and the 27B's `draft-mtp n3` arm at a 5.4K prompt is -1.1 % (the band is worth ~1 % there).  Every changed arm
reproduces the PREVIOUS build's all-tile arm byte for byte -- 35B-A3B `265c381dbc11`; the four MTP axes
`7dca501eeb0e` (R), `759c1a4515c6` (R draft), `fcc0bdeb636b` (P), `eb89102cb7d8` (C), `a87c4318b649` (K).

Corrected here: r314's claim that `K->ne[1]` at the FA op is the layer's KV CACHE SIZE is wrong -- it is the
PADDED USED LENGTH (measured on the 27B at `-c 8192`: 256 at d0, 5376 -> 5632 while generating, 8192 only
during a prompt ubatch or in the graph-RESERVATION pass, whose context sets n_kv = kv->get_size()).  That does
not change r314's measurements -- its d0 row reads 0.0 %, which only a used-length key produces -- and it is
the right attribute to price the crossover with, since it is the number of KV iterations the kernel executes.
What it does mean is that a verify batch can straddle a 256-cell padding boundary and take the other kernel
family for that ONE step: `test-logits-width-probe` at P=9980 (W=1..4 on the tile kernel, W=5..8 on the band)
FAILs with maxdiff 0.327, while every arm with a constant family passes with maxdiff 0.  Accepted and recorded
(`GREEDY-PURITY.md` 96/97) -- keying the gate on the cache size instead would band a shallow context on a large
`-c` and reintroduce exactly these losses.

`TODO` ggml-org#345 route (b) (adaptive `P = min(nsm, ceil(cells/nbatch_fa))`) is refuted and not implemented: at depth
there are no idle blocks to remove (32768 cells / 64 = 512 iterations against P = 32 = nsm), and at a short
cache the idle blocks cost nothing (a block that owns no iteration writes a neutral partial and exits) while a
smaller P serialises the KV iterations -- 512 cells with P = 8 measures 52.6 us against 31.1 for P = 16.
P = 16 is the optimum in 30 of the 36 measured rows; the quantized default P = nsm is 10-20 % off it at most
sizes, which is a separate tuning item (it moves every banded model's numerics).

r316 (TODO ggml-org#346 closed) -- the band's fixup period P stops depending on the K/V type: P = max(2, nsm/2) for
EVERY type now (nsm 32 -> 16), so `ggml_cuda_fattn_band_wmma_two_byte()` and the launcher's P fallback are gone
and `GGML_HIP_FA_BAND_WMMA_SPLIT` stays as the tuning override.  A sweep of the 256-dim class
(`GGML_HIP_FA_BAND_WMMA_SPLIT` 8/16/24/32/48/64/96 x kv 512-102400 x n_q 1/8, q8_0, medians of 3,
test-backend-ops perf) puts the DECODE width's optimum at 16 for both type families and the VERIFY widths' at 8,
so one constant cannot serve both and 16 is the compromise the widths force: P 16 beats the old quantized
default 32 by 5-14 % at kv 16384-102400 (92.9 against 99.5 us at kv 16384/n_q 1, 151.2 against 163.9 at 32768,
425.0 against 447.5 at 102400, 279.7 against 318.4 at 32768/n_q 8) and only loses at the short caches every band
gate keeps off (1024 cells/n_q 1: P 16 55.0 against P 32 42.6 -- measured and recorded, unreachable).  The
long-standing comment claim that the verify cost is "flat for P 48..96 at kv 20K..200K" does not reproduce on
this kernel (verify widths are monotone in P; what is flat is the decode width above P 24) and was replaced.

End to end (3 GPU `-sm tensor`, q8_0 K/V, `ROCBLAS_USE_HIPBLASLT=0`): plain 27B tg64 43.66 / 42.45 t/s at
d16384 / d32768 against 43.53 / 42.62 (noise -- a 27B Q8_0 decode is at the DRAM roof), Ripple-65B 26.07 / 25.41
against 25.96 / 25.44 (noise), and the attention-bound arm that pays: 27B `draft-mtp n7` on the 20.5K prose
prompt 88.91 against 75.83 t/s (+17.2 %, of which ~4.5 %/step is the kernel and the rest the acceptance re-roll a
numeric-order change always carries) and 79.00 against 74.91 at ~10.5K (+5.5 %).  P 8 wins the op-level verify
rows but loses every e2e arm (40.86 t/s at d32768, 75.68 on the 20.5K arm), so it was not taken.

Correctness and purity: `test-backend-ops -o FLASH_ATTN_EXT` 7381/7381 in four arms (default, H256+H128 forced,
`WMMA=0`, `WMMA=2`); `test-logits-width-probe` width purity PASS maxdiff 0 on 37 arms (both head classes, q8_0 /
f16 / bf16, one GPU plus `SPLIT=tensor` and `SPLIT=layer`, P 3584 / 4096 / 10240 -- a constant P cannot
straddle); prefill KLD 0.000000 / 100.000 % at the canonical point, and the family-switch point 0.002733 /
99.243 % (27B) and 0.000823 / 98.981 % (Ripple-65B) against same-kernel controls of 0.004182 / 98.822 % and
0.004133 / 97.772 %.  The four MTP axes are byte-identical to r315 on bf16 K/V (R `7dca501eeb0e` /
`759c1a4515c6`, P `fcc0bdeb636b`, C `eb89102cb7d8`, K `a87c4318b649`, acceptance 348/486, 357/460, 368/427,
372/375 reproduced exactly) and the q8_0 arms carry the same acceptance as r315's own (P-independent: the four
axes sit below the band gate and never reach it).  Every text arm that moved -- 27B q8_0 at a 21K prompt
`f7d157b1e07e` -> `774d1c325068` -- reproduces the previous build's `GGML_HIP_FA_BAND_WMMA_SPLIT=16` arm byte for
byte, and `SPLIT=32` still reproduces the old default.  The 128-dim gate's decisions are unchanged in cell terms
and every one of them is still on the right side of the measured crossover with P 16 (ratio 10: 4096 cells 1.06
loss, 8192 0.88 win; ratio 5: 8192 0.62; ratio 7: 4096 0.60; ratio 12: 8192 1.06 tile, 32768 0.91 band).

Records: `INVARIANTS.md` r316, `GREEDY-PURITY.md` 98, `benchmarks/2026-11-18-band-fixup-period.md`,
`MANIFESTS.md` gate 05, `patches/README.md` block 05, `ENVIRONMENT.md` 8, `TODO.md` (ggml-org#346 deleted).

(r328 re-base) 7 conflicted files / 22 regions.  The maintainer's decision (`DECISIONS.md` D16, option 2) is
that the delivery's FA iteration model wins: upstream 054a1ba (ggml-org#32407, "rotate K/V read order") rewrites
`flash_attn_ext_f16_process_tile` as a contiguous run plus a rotated remainder (nkb_pre/nkb_post, kb0_max
wrap-around), while this block rewrites the same loop as a strided band (kb0_step, a kq_blocks bitmap skip, a
neutral partial for a band block that owns no iteration, and the RDNA4 fetch-ahead ring).  Those are different
partitions of the same work, so a merge would be a third model; the rotation is NOT carried (no nkb_pre,
nkb_post, kb0_max or kb0_rot survives; every kb0_next in the tree is the delivery's own fetch-ahead).

What IS taken from upstream, because it is unrelated to the rotation:
- ggml-org#32217 (Inkling 2) per-head masks: the `+ nb32*(zt_Q % ne32)` term at the three mask-pointer sites of the
  MMA kernel, the `mask` tensor declaration in the tile launcher, and the `mask->ne[2] == 1` conjunct unioned
  into our derived-mask predicate in fattn-tile.cuh and both fattn.cu sites.
- ggml-org#31617's typed warp masks: the seven raw __shfl[_xor]_sync(0xFFFFFFFF, ...) calls in the band code become
  ggml_cuda_shfl_xor / ggml_cuda_shfl (HIP now static_asserts a 64-bit mask).
- build_inp_mem_hybrid_iswa_rel and the build_attn_inp_attn_mask refactor, called through the delivery's
  derived-mask signatures (build_attn_inp_kq_mask(mctx, ubatch, cparams, allow_derived)).
- the FA op-test parameters (n_kv_max, q_head_padding, mask_heads) unioned with derived/derived_hole/mask_hole.
nb32 stays int32_t (upstream widened it to int64_t; the delivery's kernels are the ones in the tree, so the
typedef and the kernels are kept consistent rather than half-widened).

Verified: 4B coherence 100 chars sha=1c5d32ac537d (unchanged); test-backend-ops -o FLASH_ATTN_EXT 7428/7428
with 0 failures, 2/2 backends -- the whole FA matrix, which is the oracle the combined-model option would have
needed at every step; and the block's own switch is non-vacuous on the path it exists for (q8_0 KV,
GGML_CUDA_FA_KV_NATIVE=1 88.6 t/s decode vs 83.9 staged, +5.6 %, identical text 71 chars sha=1de99b7e6ee6;
f16 KV is a wash, as expected -- staging only costs anything for a quantized cache).
r372 amendment (GitHub issue ggml-org#381, `@mjohanning99`; the RDNA3 half is upstream PR
ggml-org#31746 by `@ravel7524`): head-256 prefill attention under a tensor split, both halves.

1. RDNA4 keeps the stock AMD ncols2 rule WHEN THE GQA GROUP DIVIDES.  The split-aware rule (r285) is
   blind to the GQA ratio: with gqa_ratio 6 it picks ncols2 = 8 and PADS the group of 6 to 8, so a
   quarter of the prefill KQ/VKQ work is padding (at ub 1024, 256 blocks of 64 columns per launch
   instead of 192).  The stock AMD rule divides the group (ncols2 = 2) and pads nothing.
   `GGML_CUDA_FA_RDNA4_GQA_STOCK=0` restores the split-aware rule; RDNA3_5's row is untouched.
   Measured (pp4096, -ub 1024, r2, 2 alternating rounds per arm, this 27B head-256 GQA-6 model):
   2 x R9700 -sm tensor q8_0 2536.9 -> 2509.7 d0 (+1.1 %), 1852.7 vs 1752.3 d32768 (+5.7 %), 1295.5 vs
   1211.1 d81920 (+7.0 %); 3 x R9700 f16 (the split-aware rule's own tuning configuration) +1.7 / +6.2 /
   +6.6 % at the same depths, and +9.0 % at the r285 pp150000 point itself (1086.5 vs 996.7 t/s).
   Neutral where the group already divides: 4B head-256 gqa 4 (+0.2 % at d81920), 35B-A3B head-128
   gqa 4 (+0.0 %), Gemma4-31B head-512 gqa 2 (0.0 %).  Decode is unchanged (tg128 34.40 vs 34.54, the
   band owns it) and a single device is inert by construction: the hint is false, so the switch is
   never consulted (1489.8/1482.7 d0, 1016.8/1025.3 d32768 = noise).

2. RDNA3_0 (gfx1100/gfx1101/gfx1102) head 256 with 2-4 Q heads per KV head takes the upstream ggml-org#31746
   row: Q streamed from LDS, ONE K batch and one V batch per iteration, and its scheduling fence
   (`__builtin_amdgcn_sched_barrier` after each WMMA, or the compiler hoists the next batch's operand
   loads and spills).  RDNA3_5 keeps its own Strix Halo row -- it was tuned separately and is not
   covered by that PR's measurements.  Measured on gfx1100 (RX 7900 XTX, 27B Q4_K_M, q8_0 KV, pp4096,
   ABBA): 1225.1 -> 1225.8 d0 (neutral), 863.6 -> 918.0 d32768 (+6.3 %), 604.1 -> 672.2 d81920 (+11.3 %).

Purity.  The RDNA4 switch moves the Q-row blocking (ncols1 = 64/ncols2, ncols unchanged) and through
ntiles_x -> blocks_per_wave -> pick_parallel_blocks the number of partial KV blocks, so prefill is NOT
bit-identical even at constant ncols: same-seed greedy text is identical on q8_0 and f16 at 3 devices
(399 chars, sha 10a82b5559a9), and the prefill-logit point reads mean KLD 0.000542 / same-top-p 98.81 %
(q8_0) and 0.000529 / 98.92 % (f16) against the split-aware arm, versus a same-kernel -ub 256 control
measured on the spot of 0.000581 / 98.83 % and 0.000580 / 98.86 % -- the change is the model's ordinary
summation-order sensitivity, not a defect (the reporter measured the same class: 0.0185 against a
0.0207-0.0211 ubatch control).  The RDNA3_0 row changes only the online-softmax batching
(nbatch_fa 64 -> 32) and where Q is staged, and reads 0.000051 / 99.71 % on gfx1100 against a same-kernel
-ub 256 control of 0.005210 / 95.9 % -- 100x tighter than a reordering the delivery already accepts.
Its deterministic greedy text DOES move on the gfx1100 f16 arm at a 1818-token prompt (482 chars,
sha 6e2f7d2de955 -> 414 chars, sha 0a644af79489; the q8_0 arm is unchanged at 6e2f7d2de955), which is a
near-tie inside that 5e-5 KLD, not a different arithmetic.  FLASH_ATTN_EXT at hsk=256 on gfx1100:
906/906.
[fold] The padded GQA-6 tile fold (contributor PR ggml-org#362, @kapojko), DEFAULT ON, RDNA3_0-gated.

For head-256 / GQA-6 / symmetric native q8_0 K+V at query width 1..8 the ordinary tile launcher
selects ncols2 = 2, i.e. three logical K/V traversals per query row.  The fold pins ncols1 = 1,
ncols2 = 8: all six real query heads in one padded eight-column block, one traversal.  Columns 6/7
receive zero Q and are never stored; a padding-only warp still joins the cooperative K/V loads and
barriers and skips KQ/softmax/VKQ.

It is a SELF-CONTAINED kernel copy (fattn-tile-gqa6-fold.cuh + one generated TU + one
generate_cu_files.py entry) rather than a template parameter on flash_attn_tile: the runtime-branch
form of this patch moved the ordinary instantiations' register allocation, and on gfx1201 that moved
the occupancy the launcher derives the decode/verify KV split from (VGPR 140 -> 94, mean KLD
0.000391 / same-top-p 98.97 %, and 1.4-5.7 % slower at the op with the fold unreachable).  As a copy,
no pre-existing instantiation changes at all; the only shared change is launch_fattn's force_split
template parameter, compiled out unless the fold's launcher sets it, which pins P to the value the
UNFOLDED ncols2=2 kernel reaches for the shape.  The copy must be RE-SYNCED whenever the tile kernel
above it changes -- that is the cost of the isolation, and the header says so.

Gates: `GGML_HIP_FA_TILE_GQA6_FOLD=0` is the kill switch (DIAGNOSTIC.md 8); the fold's one-shot INFO
census at -lv 4 proves the arm launched; scripts/gate-gqa6-fold.sh is the gate (the census, the off
arm's decode-width KLD point against a base recorded from the previous release, FLASH_ATTN_EXT at
hsk=256 nr23=[6,1] in both arms, and the RDNA4 refusal).

Measured (r375+r376 tree, 27B IQ3_S, `-ctk q8_0 -ctv q8_0`).  gfx1100, 1x7900 XTX: fold-off is inert
against the unpatched build (decode-width `--kv q8_0 --ub 1` mean KLD 0.000000 / same-top-p 100.000 %,
the raw u16 log-prob files byte-identical, identical 482-char greedy text, tg within +/-0.2 %), and the
fold reads the same at that point.  Decode tg64 on/off: 52.71 -> 53.00 d2048 (+0.5 %), 51.58 -> 52.05
d8192 (+0.9 %), 47.11 -> 48.33 d32768 (+2.6 %), 42.29 -> 44.11 d65536 (+4.3 %), 38.40 -> 40.59 d98304
(+5.7 %); `FLASH_ATTN_EXT` 7581/7581 at hsk=256 coverage included.  gfx1201, 1xR9700: fold-off and
fold-on are both identical to the unpatched build at the decode-width KLD point and in text (single
device and 3-GPU `-sm tensor`), tg 27.95/26.24 unchanged, and the census does not fire even with the
env set -- the RDNA4 band owns the depth there, so the arch gate keeps the fold off.  The mechanism is
NOT bit-identity: the reduction grouping differs (unfolded np=4 over nbatch_fa 128, fold np=1 over 64),
so a near-tie can move; nothing measured did.
Co-authored-by: Marvin Johanning <3389797+mjohanning99@users.noreply.github.com>
Co-authored-by: ravel7524 <58877666+ravel7524@users.noreply.github.com>
Co-authored-by: briansp2020 <bsp2020@gmail.com>
Co-authored-by: jstamagal <jstamagal@users.noreply.github.com>
Co-authored-by: RikshaDriver <RikshaDriver@users.noreply.github.com>
Co-authored-by: d32768 <d32768@users.noreply.github.com>
Reported-by: a-n-t-0 <a-n-t-0@users.noreply.github.com>
Co-authored-by: Yuriy Kapoyko <yury.kapoyko@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

conversion CUDA Related to the CUDA backend documentation Improvements or additions to documentation ggml changes relating to the ggml tensor library for machine learning model Model specific mtmd Related to multimodal functionality (video/image/audio) testing Everything test related

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants