Skip to content

makefile: Fix CPU feature detection on Haiku - #218

Merged
ggerganov merged 1 commit into
ggml-org:masterfrom
kallisti5:haiku-fixes
Mar 21, 2023
Merged

ggerganov merged 1 commit into
ggml-org:masterfrom
kallisti5:haiku-fixes

Conversation

@kallisti5

Copy link
Copy Markdown
Contributor

No description provided.

@kallisti5

Copy link
Copy Markdown
Contributor Author

I submitted the upstream ggml fix for this too. ggml-org/ggml#39

@gjmulder gjmulder added bug Something isn't working build Compilation issues labels Mar 17, 2023
@ggerganov
ggerganov merged commit f157088 into ggml-org:master Mar 21, 2023
Seunghhon pushed a commit to Seunghhon/llama.cpp that referenced this pull request Apr 26, 2026
phuongncn pushed a commit to phuongncn/llama.cpp-gx10-dgx-sparks-deepseekv4 that referenced this pull request Apr 28, 2026
phuongncn pushed a commit to phuongncn/llama.cpp-gx10-dgx-sparks-deepseekv4 that referenced this pull request Apr 28, 2026
…tokens (ggml-org#218)

* This seems to be a better way

to do the attention matrix multiplications in the TG case.

* Cleanup

---------

Co-authored-by: Iwan Kawrakow <[email protected]>
ljubomirj pushed a commit to ljubomirj/llama.cpp that referenced this pull request May 6, 2026
AlexiAlp pushed a commit to minghaop/llama.cpp that referenced this pull request Jun 2, 2026
ckti pushed a commit to ckti/llama.cpp-consolidated that referenced this pull request Jul 21, 2026
From ggml-org#218 (azvyae): add max-h-dvh to Sidebar.Inset so overflow-hidden
has a definite viewport bound on long chat content.

Intentionally not taking the rest of ggml-org#218 (theme recolor, favicon swap,
bun.lock, reasoning-effort mapping) — those are separate concerns and
should land as focused PRs if desired.
imaami pushed a commit to imaami/llama.cpp that referenced this pull request Oct 10, 2026
… Ada: ggml-org#218 + ggml-org#215 hybrid PTQ1_0 dispatch, in-place q4_0/q8_0 K/V flash attention (integration checkpoint) (ggml-org#221)

* Add: planar-transposed activation layout for the PTQ1_0 mat-vec path

The mmvq path gave every thread one 128-weight PTQ1_0 block and read the
activations as 32 scattered 4-byte loads per column out of 36-byte
block_q8_1 structs, so every extra column cost a full pass: 47 / 104 / 154 /
201 us for 1 / 2 / 3 / 4 columns on a 4096 x 14336 matrix (RTX 3060,
test-backend-ops perf). Quantize PTQ1_0 activations into a planar-transposed
layout instead: per column, 8 planes of 16-byte quant pieces and one plane of
the 4 (d, s) half2 scales, 16 bytes per 128-element block each, with the same
bytes per row and the same column stride as block_q8_1. A thread then reads
its block's activations as 9 aligned 16-byte loads with adjacent lanes on
adjacent pieces: 46 / 55 / 65 / 75 us. The trit decode is unchanged; the
byte-wise minus one is (q + 0x7F7F7F7F) ^ 0x80808080 instead of __vsub4.
nwarps is pinned to 4 for every column count so the K partition, and with it
the fp32 summation order, does not depend on the batch. mmvq now handles
PTQ1_0 up to 8 columns (MMQ took 395 us at 8). HIP keeps the old layout.

* Add: dedicated PTQ1_0 mat-vec kernel with full lane utilization

With 128-element blocks the generic kernel's 128 threads cover 128 K blocks
per iteration, so a K = 5120 projection (40 blocks) keeps 31% of the lanes
busy and K = 17408 (136 blocks) 53%. This kernel handles plain 2D MUL_MAT
(no batch dims, no expert ids, K a multiple of 128, up to 8 columns): it
flattens (row group, K block) pairs into one index space with rows_per_cta
chosen on the host to fill whole 128-thread iterations, gives each thread 4
rows per K block (2 at 5 to 8 columns) for latency hiding and activation
reuse, stores one fp32 partial per (row, column, K block) in dynamic shared
memory and has one warp per (row, column) sum them in a fixed order
(lane-strided sequential, then a butterfly). The per-block partial is
d * sum_k d8_k * sumi_k with exact integer sumi_k, written as __fmaf_rn and
__fmul_rn so every instantiation rounds alike, and the order depends only on
the weight shape: a column's result is bit-identical for every column count
1 to 8. Fusion (bias, gated GLU epilogue) is supported for one column as in
the generic kernel, which remains the path for batched and MoE calls.

Bonsai 2 shapes, RTX 3060 12GB, us per call, 1 column: attn_qkv 5120 x 10240
72.4 to 41.8, ffn_up 5120 x 17408 120.0 to 66.7, attn_gate 5120 x 6144 44.8 to
27.7. Whole model llama-bench tg32 26.1 to 39.8 tok/s, pp2 34.1 to 61.1,
pp3 33.3 to 72.0.

* Test: add Bonsai 2 projection shapes to the mul_mat perf cases

* Add: GGML_CUDA_BATCH_INVARIANT for batch-invariant small-batch kernels

Off by default, nothing changes. When set, kernels are picked so that the
per-column arithmetic of a token does not depend on how many columns (1 to 8)
share the launch: F16 and BF16 matrices with at most 512 rows take the
mul_mat_vec_f kernel for 1 to 8 columns on Ampere and newer (its K partition
depends on K only), flash attention with up to 8 queries takes the vector
kernel on Turing and newer instead of switching to the tensor-core kernel at
2 queries, and the KV split (parallel_blocks) is sized as for one query tile
so the partial-softmax combine order does not depend on the batch. Together
with the batch-invariant PTQ1_0 mat-vec this makes the logits of a token
bit-identical whether it is decoded alone or verified inside a speculative
batch of 2, 3 or 4 tokens (measured on Ternary Bonsai 2 27B: greedy output
with draft-mtp equals greedy output without it on three prompts at n-max 1, 2
and 3). Batches of 5 to 8 agree with each other but not with 1 to 4. Costs
throughput at depth (the vector attention kernel at 3 queries over 42K keys).

* Fix: use the mat-vec kernel for bf16 matrices under 64 rows at 2 to 8 columns

The qwen35 gated-delta-net gate projections are bf16 [5120 x 48]. At 2 to 8
columns on Ampere they took a 10.5 us path where mul_mat_vec_f takes 4.4 to
7.3 us (test-backend-ops perf, RTX 3060); at one column both already used
mul_mat_vec_f (3.3 us). 96 calls per token on the 27B model.

* cuda: fold the recurrent-state gather into the GATED_DELTA_NET kernel (+3.8% TG on Ada)

build_rs gathers each layer's live recurrent state via GET_ROWS(cache, s_copy) into a temp
(3 MB per layer for Bonsai 2 27B) that only the GDN kernel reads. Traced in-graph with CUPTI on
an RTX 4070 the gather kernel costs ~8 us/layer, and its dirty output sits in L2 until the FFN
weight stream evicts it, which made the gate/up GEMVs in GDN layers ~15% slower than the
identical GEMVs in attention layers.

When the GET_ROWS output has no consumer other than (optionally through a RESHAPE) the GDN
node's state input, the graph evaluator skips the GET_ROWS node and records the gather
(cache base, ids, row stride) for that GDN node. The kernel then indexes the cache row
s_ids[seq] directly; no temp, no kernel, no writeback. Single-sequence only: with several
sequences a gathered row may alias a row another sequence writes in the same op.
GGML_CUDA_GDN_GATHER_FUSION=0 disables it.

The registrations live in the evaluating ggml_backend_cuda_context (ggml_cuda_gdn_gather_context,
beside the concurrent-stream state), keyed by node pointer and reset at the start of every
graph evaluation, so two contexts or host threads decoding at once never see each other's
skips. This replaces the process-wide static map in the first revision of ggml-org#215.

Independent of the activation layout change; split out of ggml-org#215 so that layout can be compared
with ggml-org#218 on its own.

RTX 4070 12 GB, Ternary-Bonsai-2-27B-PTQ1_0, llama-bench -fa 1 -ctk/-ctv q4_0, stock clocks,
three alternating rounds of r=3: tg128 56.4 -> 58.5 t/s on top of ggml-org#215 (+3.8%). pp512 unchanged.

test-backend-ops CUDA0 vs CPU: GATED_DELTA_NET 39/39 supported cases, GET_ROWS unchanged.
400 greedy tokens identical with GGML_CUDA_GDN_GATHER_FUSION=0 and 1.

* cuda: PTQ1_0 decode on consumer Ampere/Ada: SoA q8 activations, warp-per-row small-K GEMV (+14% TG)

Merged onto the planar-transposed activation layout and dedicated 2-8 column kernel
(PrismML-Eng#218, sudoingX). One decision, ggml_cuda_q8_1_layout_for(type, ncols_dst, ids),
is evaluated by both the quantizer call and the kernel switch:

  PTQ1_0, 1 column, no ids  -> SOA_ISUM (this change): exact int16 sums, warp-per-row small-K geometry
  PTQ1_0, 2-8 columns / MoE -> PT (ggml-org#218): shared weight decode, full lane utilization
  anything else             -> plain block_q8_1

GGML_CUDA_BATCH_INVARIANT=1 forces the one-column case onto PT as well so a token decoded alone
and a token verified inside a speculative batch still see identical arithmetic.

* cuda: PTQ1_0 hybrid dispatch: template y_soa, MMQ from 5 columns

The SoA/planar choice is a kernel template parameter (only instantiated true for PTQ1_0 at one
column) instead of a runtime branch inside the K loop; the runtime branch cost 5% TG on Ada.
ggml_cuda_should_use_mmvq keeps PTQ1_0 on the mat-vec path up to 4 columns: with the branch-free
MMQ tile loader the tile path overtakes the planar mat-vec kernel at n=5 (RTX 4070, Bonsai 2 27B:
163 vs 137 t/s at n=5, 258 vs 148 at n=8).

* cuda: flash attention MMA reads q4_0/q8_0 K/V in place (no F16 scratch copy)

The tensor-core flash attention path converted the whole quantized K/V cache
to F16 in a scratch buffer on every micro-batch: 1 GB per context at 262k
with q4_0 caches, 2 GB with a draft context, and a full re-conversion per
ubatch during prefill. With Bonsai 2 27B + MTP that pushed the 4070 12 GB
over the edge and WDDM spilled to system RAM (41 tok/s).

flash_attn_ext_f16 now takes type_KV as a template parameter. For q4_0 and
q8_0 the tile loader dequantizes blocks straight from the cache into the
shared-memory half2 tiles (aligned 32-bit word reads, scale from the block
header), the cp.async multi-stage pipeline is disabled for those types
(cp.async cannot dequantize), and K/V strides are byte strides. The
allocator no longer reserves the F16 copy when the native kernel handles the
call. Dispatch is limited to D=128/256 heads with matching K/V types and
word-aligned strides; anything else keeps the old conversion path.

test-backend-ops: 48 new FLASH_ATTN_EXT cases for q4_0/q8_0 at D=128/256,
GQA, batch 1-8, KV lengths incl. non-multiple of the tile, permuted layouts.
All pass against the CPU reference; the full suite is 2984/2984.

Bonsai 2 27B PTQ1_0 + MTP, RTX 4070 12 GB, 262144 context, ub 128:
resident, 222 MiB shared (no spill), 86 tok/s mean over 3 prompts.

* cuda: PTQ1_0 multi-column mat-vec: raw digits with exact activation sums, per-pair epilogue (+13% 3-col, +24% 4-col)

Two changes to mul_mat_vec_ptq1_0_pt, found with Nsight Compute on an RTX 4070 (sm_89).

1. The trit decode returns the raw base-3 digits {0,1,2} and the dot product uses a mixed-sign
   dp4a (u8 x s8) against the activations, subtracting the exact int16 sum of the 32 quantized
   activations once per sub-block: sum((q-1)*a) = sum(q*a) - sum(a). The PT quantizer now stores
   that sum bit-cast in the ds.y half slot (the SoA layout already did). Two ALU ops fewer per
   four weights; the result is the same integer, so output is bit-identical.

2. The epilogue summed each (row, column) pair with one warp: a runtime integer division per
   pair, a lane-strided loop and a 5-step shuffle butterfly. Under the profiler that was 23% of
   issued instructions and ~50% of warp stall samples (FADD on SHFL scoreboard, MUFU.RCP/I2F/F2I
   from the division) while the CTA held its slot and moved no bytes. Now one thread per pair sums
   the K blocks sequentially from shared memory with four interleaved accumulators, over a padded
   (odd) row stride so the reads are bank-conflict-free. The order still depends only on the
   weight shape, so the batch-invariant guarantee holds.

Profile of the 3-column gate|up GEMV (K=5120, N=17408) before -> after, ncu locked clocks:
2135 -> 1493 instructions per warp, 56.3 -> 43.5 us, DRAM 62% -> 83% of peak.
llama-bench, +1500 MHz memory: pp3 150 -> 169 tok/s, pp4 172 -> 212. pp1 unchanged (SoA path).

test-backend-ops -b CUDA0 -o MUL_MAT: 1283/1283.

* qwen35: MTP graph publishes only the output rows of h_nextn when embeddings_nextn_masked

llama_context::decode copies the first n_outputs rows of t_h_nextn when embeddings_nextn_masked is
set, but the QWEN35 MTP builder assigned t_h_nextn before the inp_out_ids gather, so the tensor had
n_tokens rows. Any MTP batch with more tokens than outputs (e.g. catch-up rows decoded together with
a draft row) returned row 0's hidden state for the draft row and the next draft step ran on the
wrong input. Never triggered before because every MTP decode had n_tokens == n_outputs or no outputs.

Gather before publishing in the masked case, exactly as the trunk graph does at its last layer;
the unmasked case is unchanged.

* speculative: draft-mtp decodes the catch-up rows together with the first draft row

process() used to run the draft over every row of the target's verify batch immediately, purely to
fill the draft's memory, and partly on rows the target then rejected. That is one graph launch and
one host round trip per step spent on nothing the next draft needs yet.

Single-head MTP with its own memory now keeps those rows (tokens, positions, shifted h) and decodes
only the accepted prefix at the start of draft(), in the same llama_decode as the first draft row.
Positions are contiguous and the draft row attends to the catch-up rows in-batch, so the draft is
unchanged; accept() trims the stash to the accepted prefix, and rows are decoded on their own when a
batch does not lead straight into a draft (prompt fed in tiny ubatches, drafting stopped, rollback
replay overwrites them). Shared-memory and chained-head drafters keep the eager path, as does
LLAMA_MTP_EAGER_CATCHUP=1 for A/B.

RTX 4070, Bonsai-2-27B PTQ1_0 + MTP head, 262k context, q4_0 K/V, greedy, --backend-sampling:
23.0 -> 22.4 ms/step, three-prompt mean 101.0 -> 103.3 tok/s with identical draft acceptance
(0.86 / 0.46 / 0.65) and byte-identical output vs the draft head off. Draft-side launches per step
4 -> 3.

* cuda: Hadamard transform quantizes its own output when every consumer is a PTQ1_0 mat-vec

A Hadamard-rotated activation ([MUL signs, RESHAPE,] MUL_MAT with GGML_HINT_SRC0_IS_HADAMARD)
whose every use is src1 of a PTQ1_0 mat-vec on the mmvq path never needs to exist in F32: each
consumer immediately quantizes it to q8_1. The transform kernel now quantizes as it goes and
writes the q8_1 rows, in the layout the consumers expect (AoS / PT / SoA with exact integer sums
and the same padding rule as ggml_cuda_mul_mat_vec_q), into its own output buffer; the mat-vecs
find the rows through a per-context registry keyed by tensor identity and skip their quantize
launch. On Bonsai 2 this removes ~390 launches per decode step.

Safety rules the pass enforces:
- every later node that reads the transform output (directly or via a whole-tensor reshape view)
  must be a PTQ1_0 MUL_MAT that ggml_cuda_mul_mat routes to mmvq, and the graph use count must
  match, so nothing ever reads the buffer as F32
- the registry is keyed by ggml_tensor pointer, never by data pointer: ggml-alloc recycles a dead
  output's block for later tensors in the same graph
- when the output buffer aliases the input (ggml-alloc does this for the output-projection input
  on every Bonsai layer: x is a reshape view of a cont, there is no in-place reuse through a view
  parent, so the cont is released at the MUL and mm takes its block two nodes later) the rows go
  to a pool block held until the next graph evaluation. Writing into the aliased buffer raced the
  kernel's own input reads and produced sporadic garbage that, on a hybrid model, entered the
  recurrent state and poisoned the rest of the sequence (surfaced as INT_MAX from the backend
  argmax over an all-NaN logits row, about once per ~170 requests)
- GGML_CUDA_FWHT_FUSION=0 disables the pass

fwht.cuh: the block butterfly is a shared inline so fwht.cu and the fused quantizer stay one
implementation.

Validated: 340 consecutive requests (probe.py x 20 at 262144 ctx, q4_0 KV, draft-mtp n_max=2,
backend sampling) with zero errors; output byte-identical to the unfused path.

* sampling: reject out-of-vocab token ids from the backend sampler and the draft

A backend-sampled id outside [0, n_vocab) (the CUDA argmax/top-k pad sentinel INT_MAX when a
logits row is all NaN) used to travel as-is into the server, where the tokenizer's vector::at()
threw "invalid vector subscript" and killed the request. Log the origin (idx, n_vocab, first
candidate) and fall back to the CPU chain instead; the draft-mtp loop drops a draft whose top
candidate id is out of vocab rather than feeding it to the verify decode.

* speculative: draft-mtp drops stale deferred rows when a new task starts on the slot

begin() used to decode whatever catch-up rows the previous task left pending. That is right only
when the new prompt reuses them (same tokens at the same positions, continuing what ctx_dft
holds). After a cancelled task or a different conversation landing on the slot, the server has
already trimmed ctx_dft past those rows and decoding them writes stale positions into the
recurrent draft state. Check first, flush when they belong, discard otherwise.

* cuda: release the FWHT-q8 held pool blocks LIFO and before the pools are destroyed

The registry keeps pool blocks alive across a graph when the fused Hadamard quantize would
otherwise write over its own input. Its implicit destructor released them oldest first, and it is
declared before the pools, so at context teardown the frees hit a destroyed VMM pool:
GGML_ASSERT(ptr == pool_addr + pool_used) at the end of llama-bench. Release newest first in a
destructor, and reset() from the context destructor ahead of the pools.

* server: --spec-draft-depth-max stops drafting once the sequence is deep

Deep in the context a decode step is bound by reading the KV cache. The draft passes and the
multi-column verify add to that read without shortening it, so past some depth speculation costs
more than the accepted tokens save: with Bonsai 2 27B on an RTX 4070 the MTP draft is +85% at
zero depth, even near 24-32k tokens and -27% at 64k. Past the cutoff the slot decodes one token
per step and the process() hook is skipped for batches that sit entirely beyond it (by position,
so the early ubatches of a long prompt still reach the draft context and remain reusable as a
prefix). Default 0 keeps the old behaviour. 0 / 32k / 64k tokens: 101 / 48 / 37 tok/s with a 24k
cutoff against 101 / 45 / 27 without.

* cuda: restrict off PTQ1_0 kernel params; Ampere uses the PT 1-col path.

C2912 / stub mismatch on sm_90 and sm_120 when GGML_CUDA_RESTRICT is on the formal parameters of mul_mat_vec_ptq1_0_pt (same hunk as 2578fdf on ggml-org#218). Ampere (cc 800-889) takes the planar 1-col kernel; Ada and newer keep SoA. 3060: ggml-org#218 was +5.9% tg128 vs ggml-org#215 at one column.

* cuda: address Copilot review on native q4/q8 FA, MTP catch-up, and BOM.

Disable drafting when deferred catch-up decode fails. Gate in-place quantized K/V FA to NVIDIA and require ggml_cuda_is_aligned on K and V. Strip UTF-8 BOMs. The FWHT fusion comment no longer opens with the GDN gather notes.

* cuda: share the PTQ1_0 mat-vec smem budget between guard and launch

The combo kernel pads each partials row by one float. Use the same
byte count in the entry guard as the launch, including that pad, so
oversized gated shapes fall back instead of requesting more than smpb.

* spec: flush MTP catch-up when it plus anchors would overflow n_batch

process() can stash n_batch rows; draft() then added one more anchor.
Flush first when the combined count would exceed llama_n_batch.

* cuda: restore the scalar PTQ1_0 vec-dot on MUSA

Same hole as ggml-org#215: the generic entry returned zero once MUSA was kept off the SoA path.
MUSA now takes the HIP scalar implementation.

* spec: keep MTP catch-up across a failed draft decode

catchup_failed was set on a flush failure and never cleared, so one bad decode disabled that slot for every later task. begin() now resets it with the rest of the per-task state.

draft() also cleared pending while building the batch, so a failed llama_decode dropped those rows from both the stash and ctx_dft. pending stays set until that first decode succeeds, and a failure marks the slot so it is not drafted again until the next begin(). flush_deferred waits for success the same way.

The layout_for comment now says it is the column-count helper. ggml_cuda_q8_1_layout_host is the decision both sides call.

* cuda: define the PTQ1_0 layout helper after ggml_cuda_info

The host layout decision reads the current device's compute capability. It was declared above ggml_cuda_info and ggml_cuda_get_device, so a clean sm_89 build failed in every CUDA translation unit. The helper now sits below those declarations.

* cuda: land remaining ggml-org#221 review notes: pass q8 layout down, skip HIP/MUSA q4/q8 FA instances, exercise ALiBi/softcap.

* cuda: wait on the PDL dependency in the PTQ1_0 planar mat-vec (Hopper/Blackwell).

* cuda: restore warp-reduce epilogue under BATCH_INVARIANT so MTP-on matches MTP-off.

The four-accumulator path (5300cd1) is faster but a 5080 run flipped a late near-tie.
GDN now waits on PDL before reading s_ids.

---------

Co-authored-by: sudoingX <[email protected]>
Co-authored-by: Cary Palmer <[email protected]>
(cherry picked from commit 5244cea)
Assisted-by: GitHub Copilot
imaami pushed a commit to imaami/llama.cpp that referenced this pull request Oct 10, 2026
…s Ampere

One-column PTQ1_0 decode kept the Ada SOA_ISUM layout on sm_75. The planar PT kernel from ggml-org#218 is faster there, as it is on Ampere: RTX 2060 SUPER, Bonsai 2 27B, q8_0 K/V, 4k context, greedy, 2 prompts x 400 tokens x 2 reps, stock clocks: SOA_ISUM 38.07 tok/s, PT 43.34 / 43.22 (+13.7%). GGML_CUDA_BATCH_INVARIANT=1 output is byte-identical before and after the change.

(cherry picked from commit 34a932b)
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 25, 2026
Also adds mmf32, the F32 counterpart of MMB: the
shapes MMB cannot take -- non-quantized (F32) weights with more than 16 token columns -- currently fall
through ggml_cuda_mul_mat_cublas() to rocBLAS, which dispatches to hipBLASLt.

Two reasons to own that path:
  * correctness: hipBLASLt picks its solution per process start from a heap-ordered container, so the prefill
    arithmetic (and therefore the logits) changes between fresh runs -- GREEDY-PURITY.md §44, TODO ggml-org#75: 3
    logit classes in 8 starts on 35B-A3B, 3 in 18 on gemma4;
  * speed: the solution the heuristic lands on is the slowest in the pool for these shapes (0.13-0.19 ms vs
    0.046 ms for a well-chosen one).

mmf32 is a plain SIMT tiled GEMM (RDNA has no F32 MMA form: amd_mfma_available is CDNA-only,
amd_wmma_available is f16/bf16).  32 output rows per block, a 4x8 thread sub-tile, BN=256 for m <= 64 (the
GDN ssm_alpha/ssm_beta projections) and 64 above it (the MoE routers), and the k range split into contiguous
chunks summed in increasing z -- a fixed reduction tree, no atomics, so a run is bit-stable by construction.
No approximation: an F32 FMA accumulation in a pinned order.

Scope: F32 weights only, m <= 256, 17 <= n <= 65536, 256 <= k <= 8192, ldc == m; every other mul_mat keeps the
rocBLAS call unchanged (BF16/f16 prefill -- Flash-Next -- is untouched, as is its hipBLASLt advantage; a
full-F32 model's FFN GEMMs, m >> 256, stay on rocBLAS: a recorded limitation).

Measured on gfx1201 (35B-A3B Q4_K_M, one GPU): deterministic -- one logits class in 12/12 fresh starts (6/6 at
2 GPU -sm tensor), --chunks 8 dumps byte-identical; +4.2 % pp512 / +4.1 % pp2048, decode flat (3 interleaved
llama-bench visits); kernel 0.032 ms vs 0.046 ms for the best hipBLASLt class on 32x512x2048.  Correctness:
16-shape oracle NMSE ~1e-13, and 11x closer to the CPU reference than the rocBLAS path on the
test-backend-ops cases it intercepts.  Purity: judged with the family-switch gate at a confident point
(in-domain corpus, base PPL 1.43) at 0.014646 / 98.045 % against a same-kernel control of 0.018100 / 97.808 %.

Default-on for RDNA4 (GGML_CUDA_MMF32=0 disables; opt-in on RDNA3/RDNA3_5 until those boxes run the same
determinism + bench pair).  GGML_CUDA_MMF32_LOG prints the resolved plans (diagnostic only).

Amended (r132): the per-arch dispatch is keyed to the device the kernel runs on, not the primary.  mmb_enabled,
mmb_cfg, mmb_cfg_dump_once, mmb_dense_flag, mmb_wtype_mask and mmb_dense_tmask read
ggml_cuda_info().devices[ggml_cuda_get_device()].cc, and mmb_cfg() takes one magic static per architecture class
(mmb_arch_defaults() only discriminates RDNA4 and RDNA3_0, so every cc that reaches the fallback shares the same
pre-S11 table).  ggml_backend_cuda_graph_optimize() now selects its own context's device before it consults those
predicates, so the MMB marking half agrees with the launch path under the Meta backend, where the pass is
forwarded per child from meta graph_compute and the current device is still the previously computed one.

Reported in PR ggml-org#218 (@slavap): on a mixed-arch box (gfx1100 primary + gfx1030 secondary) the policy froze at the
primary's, so the RDNA2 card ran RDNA3-tuned MMB kernels -- byte-exact zero output-projection logits (PPL ==
vocab) or garbled tail layers, depending on where the output projection sat.  On a single-arch box this is
bit-for-bit the previous behaviour (validated here on 3x gfx1201: 12/12 same-seed configs byte-identical,
prefill-logit KLD 0.000000 on both recorded points, no GPU faults).

Co-authored-by: Slava P. <[email protected]>
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 25, 2026
…rastructure)

The infrastructure half of the old block 10.  qwen4exp, QSA and the
hyper-connection ops now live in their own block (11); this block is what they
are built on, and it no longer references them.

Contents:

- The movable-boundary slab and its arena (ggml-cuda-slab.cu,
  ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM
  reserve per device split by a movable boundary -- compute below, MoE arena
  above, no HIP call at runtime.  Plus the narrow-band learning, the wide-phase
  auxiliary region, pool-wide routing, and the slab transient absorption.
- The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of
  ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it.
- The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the
  r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU
  split's output, which the next ubatch rewrites), default-on, and the per-origin
  (per host thread) ordering state of issue ggml-org#201.
- Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT)
  matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes
  folded into the rope + FWHT kernel, and the paired GDN q/k norms.
- GDN / attention-gate decode fusions: the BF16 alpha/beta pair with
  softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108
  multi-sequence fix and its model-free regression test), the q/k norm pair in
  the direct conv kernel, the attention gate's row-strided view read in place by
  the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and
  GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots).
- MMB and the HC16 BF16 streams: the per-context MMB state (two contexts
  interleaving must not share the activation cache or the marks), the BF16
  activation copies, DOWN16, and the graph-optimize marking passes.
- The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel),
  the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output
  matmul, the MoE down fold, and the weighted-down reduction.
- The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize
  predicate and in the direct GDN conv.
- Meta/scheduler/allocator: the split-state refusals for a straddling split,
  the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory
  generations so a graph is recaptured when the pool / FA staging / H2D ring
  memory it captured is freed -- including the slab work-boundary shrink of
  issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy
  instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED).
- bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16
  instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu.

Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED /
GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values
rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the
next getenv() call overwrites, so a cached pointer is unsafe on Windows.

Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve
lives in src/ (not linked against the CUDA common.cuh), so it uses a local
static instead of the CUDA helper.

Split note (r109): this commit plus block 11 carries exactly the tree the old
block 10 carried -- the net set is unchanged.  What moved to block 11 is the
qwen4exp model graph, the QSA/indexer ops and their kernels, the
hyper-connection ops, the managed lazy reader and the keys-only indexer cache,
i.e. everything that exists only because of that architecture.  The pieces of
the old block 10 that exist for qwen4exp but are implemented inside a general
kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp
weighted-down reduction, the PLE conv fusion) stay here with the TU that owns
them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved
to block 11 with the matchers they call.

Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers
block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`.  With HIP on Windows (clang + the
MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an
inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's
version win overload resolution is not part of the mangled name), so a translation unit that
instantiates both fails to codegen with "definition with same mangled name".  Behaviour is unchanged.

Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces.  The fused GLU -> Q8_1 site's
key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the
root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel
and the GLU write -- validate their sources with q8_1_src_range_ok() before launching.  From PR ggml-org#218 (@slavap);
the rule and the validation are recorded with block 08.

Co-authored-by: Slava P. <[email protected]>
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 25, 2026
Also adds mmf32, the F32 counterpart of MMB: the
shapes MMB cannot take -- non-quantized (F32) weights with more than 16 token columns -- currently fall
through ggml_cuda_mul_mat_cublas() to rocBLAS, which dispatches to hipBLASLt.

Two reasons to own that path:
  * correctness: hipBLASLt picks its solution per process start from a heap-ordered container, so the prefill
    arithmetic (and therefore the logits) changes between fresh runs -- GREEDY-PURITY.md §44, TODO ggml-org#75: 3
    logit classes in 8 starts on 35B-A3B, 3 in 18 on gemma4;
  * speed: the solution the heuristic lands on is the slowest in the pool for these shapes (0.13-0.19 ms vs
    0.046 ms for a well-chosen one).

mmf32 is a plain SIMT tiled GEMM (RDNA has no F32 MMA form: amd_mfma_available is CDNA-only,
amd_wmma_available is f16/bf16).  32 output rows per block, a 4x8 thread sub-tile, BN=256 for m <= 64 (the
GDN ssm_alpha/ssm_beta projections) and 64 above it (the MoE routers), and the k range split into contiguous
chunks summed in increasing z -- a fixed reduction tree, no atomics, so a run is bit-stable by construction.
No approximation: an F32 FMA accumulation in a pinned order.

Scope: F32 weights only, m <= 256, 17 <= n <= 65536, 256 <= k <= 8192, ldc == m; every other mul_mat keeps the
rocBLAS call unchanged (BF16/f16 prefill -- Flash-Next -- is untouched, as is its hipBLASLt advantage; a
full-F32 model's FFN GEMMs, m >> 256, stay on rocBLAS: a recorded limitation).

Measured on gfx1201 (35B-A3B Q4_K_M, one GPU): deterministic -- one logits class in 12/12 fresh starts (6/6 at
2 GPU -sm tensor), --chunks 8 dumps byte-identical; +4.2 % pp512 / +4.1 % pp2048, decode flat (3 interleaved
llama-bench visits); kernel 0.032 ms vs 0.046 ms for the best hipBLASLt class on 32x512x2048.  Correctness:
16-shape oracle NMSE ~1e-13, and 11x closer to the CPU reference than the rocBLAS path on the
test-backend-ops cases it intercepts.  Purity: judged with the family-switch gate at a confident point
(in-domain corpus, base PPL 1.43) at 0.014646 / 98.045 % against a same-kernel control of 0.018100 / 97.808 %.

Default-on for RDNA4 (GGML_CUDA_MMF32=0 disables; opt-in on RDNA3/RDNA3_5 until those boxes run the same
determinism + bench pair).  GGML_CUDA_MMF32_LOG prints the resolved plans (diagnostic only).

Amended (r132): the per-arch dispatch is keyed to the device the kernel runs on, not the primary.  mmb_enabled,
mmb_cfg, mmb_cfg_dump_once, mmb_dense_flag, mmb_wtype_mask and mmb_dense_tmask read
ggml_cuda_info().devices[ggml_cuda_get_device()].cc, and mmb_cfg() takes one magic static per architecture class
(mmb_arch_defaults() only discriminates RDNA4 and RDNA3_0, so every cc that reaches the fallback shares the same
pre-S11 table).  ggml_backend_cuda_graph_optimize() now selects its own context's device before it consults those
predicates, so the MMB marking half agrees with the launch path under the Meta backend, where the pass is
forwarded per child from meta graph_compute and the current device is still the previously computed one.

Reported in PR ggml-org#218 (@slavap): on a mixed-arch box (gfx1100 primary + gfx1030 secondary) the policy froze at the
primary's, so the RDNA2 card ran RDNA3-tuned MMB kernels -- byte-exact zero output-projection logits (PPL ==
vocab) or garbled tail layers, depending on where the output projection sat.  On a single-arch box this is
bit-for-bit the previous behaviour (validated here on 3x gfx1201: 12/12 same-seed configs byte-identical,
prefill-logit KLD 0.000000 on both recorded points, no GPU faults).

Co-authored-by: Slava P. <[email protected]>

Fold (r134, issue ggml-org#224): the width probe's n_ctx is now the prefill length plus the decode
width instead of a fixed 4096, and a purity run must pass P >= 4096.  The RDNA4 band's
64-column block (query widths 5..8) is only reachable above the launcher's KV-length gate
(K->ne[1] >= 4096), and K->ne[1] is the context's used length, so the P=256 default never
reached that block: the probe reported PASS on every arm while widths 5..8 ran a geometry
that was not bit-identical to widths 1..4.  At P=4096 the r126 geometry fails it
(width_purity=FAIL, worst maxdiff 0.199764 on q8_0 K/V, row-0 hash split between W=4 and
W=5), and the shipped band geometry passes with maxdiff 0.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 25, 2026
…oE + old-15 PR57/63)

Merged from the planned 08 fused-prefill and 09 fused-moe: the two are not
hunk-separable (the fusions and the mmvq dispatch share ggml_cuda.cu try_fuse,
mmvq.cu, norm.cu, common.cuh and the ggml_cuda_mm_fusion_args plumbing), and the
old-08-only fusion set was not correct (fusion-on greedy text differed from
fusion-off).

Contents:
- old-08 fusions: gdn-conv, ple-conv, norm-gated, topk-moe, the norm/unary/
  getrows/argsort kernels, the CPU references and the try_fuse arms.
- old-13: fused MoE gate+up+GLU MMQ, the mmvq short-K item-split/ksplit, the
  routed-compact MMQ (mmq.cuh/mmq-config), MWR, the mmq gate instances.
- old-15 PR ggml-org#57/ggml-org#63: the mmvq multi-row/row-loop decode (GGML_MMVQ_RDNA4_
  DECODE_GRID, nrows_loop, the lf_nval halving reduction), ssm_gate_beta/
  ssm_conv_l2_gatebeta, the norm rms_norm_q8_1 refactor and quantize_mmq_q8_1_glu.

The MoE-cache-aware arms (moe_cache_get_cold/redirect, the B1 stand-down) and
the qwen4exp/HC arms are deliberately NOT here -- they belong to the slab-moe and
qwen4exp blocks, and their absence leaves the resident-only path (bit-identical).

Gates: build all OK; fusion on == off (4B greedy text); test-logits-width-probe
width_purity PASS; MUL_MAT 2444/2444.

Amended (r132): the Q8_1 quantize cache is keyed by the ROOT tensor's identity but filled from the (possibly
offset) view's pointer, so an offset view stored its rows under the root identity and a later op with the same
root and canonical row layout could hit them.  Every key walk that reaches the cache now stops at the first
pointer change (this block: the four mmvq sites and the unary mul_q8_1 site; block 10 adds its own GLU site), so
offset-free views keep the shared root entry and an offset view gets its own arena entry.  A new
q8_1_src_range_ok() validates the source read range against the root buffer's allocation before every
quantize_row_q8_1_cuda / fused gated-q8_1 launch, so a stale source pointer (a compute buffer reallocated under a
still-matching cache entry) aborts loudly with the layout logged instead of faulting with
HSA_STATUS_ERROR_MEMORY_APERTURE_VIOLATION or silently reading reused memory.

Reported in PR ggml-org#218 (@slavap), whose V620 hit the fault on decode.  Not reachable on the maintainer's model set
(0 offset-view keys in 14336-60416 key walks per config across 7 configs, probed on gfx1201), so this is a
correctness fix for configurations we do not run: 12/12 same-seed configs byte-identical, MTP acceptance
identical (1859/3416, 1420/1710, 2171/2483, 372/375 on the four axes), prefill-logit KLD 0.000000.

Co-authored-by: Slava P. <[email protected]>
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 25, 2026
…rastructure)

The infrastructure half of the old block 10.  qwen4exp, QSA and the
hyper-connection ops now live in their own block (11); this block is what they
are built on, and it no longer references them.

Contents:

- The movable-boundary slab and its arena (ggml-cuda-slab.cu,
  ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM
  reserve per device split by a movable boundary -- compute below, MoE arena
  above, no HIP call at runtime.  Plus the narrow-band learning, the wide-phase
  auxiliary region, pool-wide routing, and the slab transient absorption.
- The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of
  ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it.
- The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the
  r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU
  split's output, which the next ubatch rewrites), default-on, and the per-origin
  (per host thread) ordering state of issue ggml-org#201.
- Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT)
  matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes
  folded into the rope + FWHT kernel, and the paired GDN q/k norms.
- GDN / attention-gate decode fusions: the BF16 alpha/beta pair with
  softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108
  multi-sequence fix and its model-free regression test), the q/k norm pair in
  the direct conv kernel, the attention gate's row-strided view read in place by
  the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and
  GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots).
- MMB and the HC16 BF16 streams: the per-context MMB state (two contexts
  interleaving must not share the activation cache or the marks), the BF16
  activation copies, DOWN16, and the graph-optimize marking passes.
- The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel),
  the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output
  matmul, the MoE down fold, and the weighted-down reduction.
- The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize
  predicate and in the direct GDN conv.
- Meta/scheduler/allocator: the split-state refusals for a straddling split,
  the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory
  generations so a graph is recaptured when the pool / FA staging / H2D ring
  memory it captured is freed -- including the slab work-boundary shrink of
  issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy
  instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED).
- bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16
  instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu.

Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED /
GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values
rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the
next getenv() call overwrites, so a cached pointer is unsafe on Windows.

Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve
lives in src/ (not linked against the CUDA common.cuh), so it uses a local
static instead of the CUDA helper.

Split note (r109): this commit plus block 11 carries exactly the tree the old
block 10 carried -- the net set is unchanged.  What moved to block 11 is the
qwen4exp model graph, the QSA/indexer ops and their kernels, the
hyper-connection ops, the managed lazy reader and the keys-only indexer cache,
i.e. everything that exists only because of that architecture.  The pieces of
the old block 10 that exist for qwen4exp but are implemented inside a general
kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp
weighted-down reduction, the PLE conv fusion) stay here with the TU that owns
them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved
to block 11 with the matchers they call.

Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers
block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`.  With HIP on Windows (clang + the
MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an
inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's
version win overload resolution is not part of the mangled name), so a translation unit that
instantiates both fails to codegen with "definition with same mangled name".  Behaviour is unchanged.

Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces.  The fused GLU -> Q8_1 site's
key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the
root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel
and the GLU write -- validate their sources with q8_1_src_range_ok() before launching.  From PR ggml-org#218 (@slavap);
the rule and the validation are recorded with block 08.

Co-authored-by: Slava P. <[email protected]>
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 25, 2026
Also adds mmf32, the F32 counterpart of MMB: the
shapes MMB cannot take -- non-quantized (F32) weights with more than 16 token columns -- currently fall
through ggml_cuda_mul_mat_cublas() to rocBLAS, which dispatches to hipBLASLt.

Two reasons to own that path:
  * correctness: hipBLASLt picks its solution per process start from a heap-ordered container, so the prefill
    arithmetic (and therefore the logits) changes between fresh runs -- GREEDY-PURITY.md §44, TODO ggml-org#75: 3
    logit classes in 8 starts on 35B-A3B, 3 in 18 on gemma4;
  * speed: the solution the heuristic lands on is the slowest in the pool for these shapes (0.13-0.19 ms vs
    0.046 ms for a well-chosen one).

mmf32 is a plain SIMT tiled GEMM (RDNA has no F32 MMA form: amd_mfma_available is CDNA-only,
amd_wmma_available is f16/bf16).  32 output rows per block, a 4x8 thread sub-tile, BN=256 for m <= 64 (the
GDN ssm_alpha/ssm_beta projections) and 64 above it (the MoE routers), and the k range split into contiguous
chunks summed in increasing z -- a fixed reduction tree, no atomics, so a run is bit-stable by construction.
No approximation: an F32 FMA accumulation in a pinned order.

Scope: F32 weights only, m <= 256, 17 <= n <= 65536, 256 <= k <= 8192, ldc == m; every other mul_mat keeps the
rocBLAS call unchanged (BF16/f16 prefill -- Flash-Next -- is untouched, as is its hipBLASLt advantage; a
full-F32 model's FFN GEMMs, m >> 256, stay on rocBLAS: a recorded limitation).

Measured on gfx1201 (35B-A3B Q4_K_M, one GPU): deterministic -- one logits class in 12/12 fresh starts (6/6 at
2 GPU -sm tensor), --chunks 8 dumps byte-identical; +4.2 % pp512 / +4.1 % pp2048, decode flat (3 interleaved
llama-bench visits); kernel 0.032 ms vs 0.046 ms for the best hipBLASLt class on 32x512x2048.  Correctness:
16-shape oracle NMSE ~1e-13, and 11x closer to the CPU reference than the rocBLAS path on the
test-backend-ops cases it intercepts.  Purity: judged with the family-switch gate at a confident point
(in-domain corpus, base PPL 1.43) at 0.014646 / 98.045 % against a same-kernel control of 0.018100 / 97.808 %.

Default-on for RDNA4 (GGML_CUDA_MMF32=0 disables; opt-in on RDNA3/RDNA3_5 until those boxes run the same
determinism + bench pair).  GGML_CUDA_MMF32_LOG prints the resolved plans (diagnostic only).

Amended (r132): the per-arch dispatch is keyed to the device the kernel runs on, not the primary.  mmb_enabled,
mmb_cfg, mmb_cfg_dump_once, mmb_dense_flag, mmb_wtype_mask and mmb_dense_tmask read
ggml_cuda_info().devices[ggml_cuda_get_device()].cc, and mmb_cfg() takes one magic static per architecture class
(mmb_arch_defaults() only discriminates RDNA4 and RDNA3_0, so every cc that reaches the fallback shares the same
pre-S11 table).  ggml_backend_cuda_graph_optimize() now selects its own context's device before it consults those
predicates, so the MMB marking half agrees with the launch path under the Meta backend, where the pass is
forwarded per child from meta graph_compute and the current device is still the previously computed one.

Reported in PR ggml-org#218 (@slavap): on a mixed-arch box (gfx1100 primary + gfx1030 secondary) the policy froze at the
primary's, so the RDNA2 card ran RDNA3-tuned MMB kernels -- byte-exact zero output-projection logits (PPL ==
vocab) or garbled tail layers, depending on where the output projection sat.  On a single-arch box this is
bit-for-bit the previous behaviour (validated here on 3x gfx1201: 12/12 same-seed configs byte-identical,
prefill-logit KLD 0.000000 on both recorded points, no GPU faults).

Co-authored-by: Slava P. <[email protected]>

Fold (r134, issue ggml-org#224): the width probe's n_ctx is now the prefill length plus the decode
width instead of a fixed 4096, and a purity run must pass P >= 4096.  The RDNA4 band's
64-column block (query widths 5..8) is only reachable above the launcher's KV-length gate
(K->ne[1] >= 4096), and K->ne[1] is the context's used length, so the P=256 default never
reached that block: the probe reported PASS on every arm while widths 5..8 ran a geometry
that was not bit-identical to widths 1..4.  At P=4096 the r126 geometry fails it
(width_purity=FAIL, worst maxdiff 0.199764 on q8_0 K/V, row-0 hash split between W=4 and
W=5), and the shipped band geometry passes with maxdiff 0.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 25, 2026
…oE + old-15 PR57/63)

Merged from the planned 08 fused-prefill and 09 fused-moe: the two are not
hunk-separable (the fusions and the mmvq dispatch share ggml_cuda.cu try_fuse,
mmvq.cu, norm.cu, common.cuh and the ggml_cuda_mm_fusion_args plumbing), and the
old-08-only fusion set was not correct (fusion-on greedy text differed from
fusion-off).

Contents:
- old-08 fusions: gdn-conv, ple-conv, norm-gated, topk-moe, the norm/unary/
  getrows/argsort kernels, the CPU references and the try_fuse arms.
- old-13: fused MoE gate+up+GLU MMQ, the mmvq short-K item-split/ksplit, the
  routed-compact MMQ (mmq.cuh/mmq-config), MWR, the mmq gate instances.
- old-15 PR ggml-org#57/ggml-org#63: the mmvq multi-row/row-loop decode (GGML_MMVQ_RDNA4_
  DECODE_GRID, nrows_loop, the lf_nval halving reduction), ssm_gate_beta/
  ssm_conv_l2_gatebeta, the norm rms_norm_q8_1 refactor and quantize_mmq_q8_1_glu.

The MoE-cache-aware arms (moe_cache_get_cold/redirect, the B1 stand-down) and
the qwen4exp/HC arms are deliberately NOT here -- they belong to the slab-moe and
qwen4exp blocks, and their absence leaves the resident-only path (bit-identical).

Gates: build all OK; fusion on == off (4B greedy text); test-logits-width-probe
width_purity PASS; MUL_MAT 2444/2444.

Amended (r132): the Q8_1 quantize cache is keyed by the ROOT tensor's identity but filled from the (possibly
offset) view's pointer, so an offset view stored its rows under the root identity and a later op with the same
root and canonical row layout could hit them.  Every key walk that reaches the cache now stops at the first
pointer change (this block: the four mmvq sites and the unary mul_q8_1 site; block 10 adds its own GLU site), so
offset-free views keep the shared root entry and an offset view gets its own arena entry.  A new
q8_1_src_range_ok() validates the source read range against the root buffer's allocation before every
quantize_row_q8_1_cuda / fused gated-q8_1 launch, so a stale source pointer (a compute buffer reallocated under a
still-matching cache entry) aborts loudly with the layout logged instead of faulting with
HSA_STATUS_ERROR_MEMORY_APERTURE_VIOLATION or silently reading reused memory.

Reported in PR ggml-org#218 (@slavap), whose V620 hit the fault on decode.  Not reachable on the maintainer's model set
(0 offset-view keys in 14336-60416 key walks per config across 7 configs, probed on gfx1201), so this is a
correctness fix for configurations we do not run: 12/12 same-seed configs byte-identical, MTP acceptance
identical (1859/3416, 1420/1710, 2171/2483, 372/375 on the four axes), prefill-logit KLD 0.000000.

Co-authored-by: Slava P. <[email protected]>
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 25, 2026
…rastructure)

The infrastructure half of the old block 10.  qwen4exp, QSA and the
hyper-connection ops now live in their own block (11); this block is what they
are built on, and it no longer references them.

Contents:

- The movable-boundary slab and its arena (ggml-cuda-slab.cu,
  ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM
  reserve per device split by a movable boundary -- compute below, MoE arena
  above, no HIP call at runtime.  Plus the narrow-band learning, the wide-phase
  auxiliary region, pool-wide routing, and the slab transient absorption.
- The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of
  ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it.
- The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the
  r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU
  split's output, which the next ubatch rewrites), default-on, and the per-origin
  (per host thread) ordering state of issue ggml-org#201.
- Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT)
  matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes
  folded into the rope + FWHT kernel, and the paired GDN q/k norms.
- GDN / attention-gate decode fusions: the BF16 alpha/beta pair with
  softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108
  multi-sequence fix and its model-free regression test), the q/k norm pair in
  the direct conv kernel, the attention gate's row-strided view read in place by
  the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and
  GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots).
- MMB and the HC16 BF16 streams: the per-context MMB state (two contexts
  interleaving must not share the activation cache or the marks), the BF16
  activation copies, DOWN16, and the graph-optimize marking passes.
- The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel),
  the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output
  matmul, the MoE down fold, and the weighted-down reduction.
- The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize
  predicate and in the direct GDN conv.
- Meta/scheduler/allocator: the split-state refusals for a straddling split,
  the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory
  generations so a graph is recaptured when the pool / FA staging / H2D ring
  memory it captured is freed -- including the slab work-boundary shrink of
  issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy
  instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED).
- bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16
  instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu.

Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED /
GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values
rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the
next getenv() call overwrites, so a cached pointer is unsafe on Windows.

Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve
lives in src/ (not linked against the CUDA common.cuh), so it uses a local
static instead of the CUDA helper.

Split note (r109): this commit plus block 11 carries exactly the tree the old
block 10 carried -- the net set is unchanged.  What moved to block 11 is the
qwen4exp model graph, the QSA/indexer ops and their kernels, the
hyper-connection ops, the managed lazy reader and the keys-only indexer cache,
i.e. everything that exists only because of that architecture.  The pieces of
the old block 10 that exist for qwen4exp but are implemented inside a general
kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp
weighted-down reduction, the PLE conv fusion) stay here with the TU that owns
them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved
to block 11 with the matchers they call.

Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers
block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`.  With HIP on Windows (clang + the
MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an
inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's
version win overload resolution is not part of the mangled name), so a translation unit that
instantiates both fails to codegen with "definition with same mangled name".  Behaviour is unchanged.

Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces.  The fused GLU -> Q8_1 site's
key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the
root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel
and the GLU write -- validate their sources with q8_1_src_range_ok() before launching.  From PR ggml-org#218 (@slavap);
the rule and the validation are recorded with block 08.

Co-authored-by: Slava P. <[email protected]>
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 26, 2026
Also adds mmf32, the F32 counterpart of MMB: the
shapes MMB cannot take -- non-quantized (F32) weights with more than 16 token columns -- currently fall
through ggml_cuda_mul_mat_cublas() to rocBLAS, which dispatches to hipBLASLt.

Two reasons to own that path:
  * correctness: hipBLASLt picks its solution per process start from a heap-ordered container, so the prefill
    arithmetic (and therefore the logits) changes between fresh runs -- GREEDY-PURITY.md §44, TODO ggml-org#75: 3
    logit classes in 8 starts on 35B-A3B, 3 in 18 on gemma4;
  * speed: the solution the heuristic lands on is the slowest in the pool for these shapes (0.13-0.19 ms vs
    0.046 ms for a well-chosen one).

mmf32 is a plain SIMT tiled GEMM (RDNA has no F32 MMA form: amd_mfma_available is CDNA-only,
amd_wmma_available is f16/bf16).  32 output rows per block, a 4x8 thread sub-tile, BN=256 for m <= 64 (the
GDN ssm_alpha/ssm_beta projections) and 64 above it (the MoE routers), and the k range split into contiguous
chunks summed in increasing z -- a fixed reduction tree, no atomics, so a run is bit-stable by construction.
No approximation: an F32 FMA accumulation in a pinned order.

Scope: F32 weights only, m <= 256, 17 <= n <= 65536, 256 <= k <= 8192, ldc == m; every other mul_mat keeps the
rocBLAS call unchanged (BF16/f16 prefill -- Flash-Next -- is untouched, as is its hipBLASLt advantage; a
full-F32 model's FFN GEMMs, m >> 256, stay on rocBLAS: a recorded limitation).

Measured on gfx1201 (35B-A3B Q4_K_M, one GPU): deterministic -- one logits class in 12/12 fresh starts (6/6 at
2 GPU -sm tensor), --chunks 8 dumps byte-identical; +4.2 % pp512 / +4.1 % pp2048, decode flat (3 interleaved
llama-bench visits); kernel 0.032 ms vs 0.046 ms for the best hipBLASLt class on 32x512x2048.  Correctness:
16-shape oracle NMSE ~1e-13, and 11x closer to the CPU reference than the rocBLAS path on the
test-backend-ops cases it intercepts.  Purity: judged with the family-switch gate at a confident point
(in-domain corpus, base PPL 1.43) at 0.014646 / 98.045 % against a same-kernel control of 0.018100 / 97.808 %.

Default-on for RDNA4 (GGML_CUDA_MMF32=0 disables; opt-in on RDNA3/RDNA3_5 until those boxes run the same
determinism + bench pair).  GGML_CUDA_MMF32_LOG prints the resolved plans (diagnostic only).

Amended (r132): the per-arch dispatch is keyed to the device the kernel runs on, not the primary.  mmb_enabled,
mmb_cfg, mmb_cfg_dump_once, mmb_dense_flag, mmb_wtype_mask and mmb_dense_tmask read
ggml_cuda_info().devices[ggml_cuda_get_device()].cc, and mmb_cfg() takes one magic static per architecture class
(mmb_arch_defaults() only discriminates RDNA4 and RDNA3_0, so every cc that reaches the fallback shares the same
pre-S11 table).  ggml_backend_cuda_graph_optimize() now selects its own context's device before it consults those
predicates, so the MMB marking half agrees with the launch path under the Meta backend, where the pass is
forwarded per child from meta graph_compute and the current device is still the previously computed one.

Reported in PR ggml-org#218 (@slavap): on a mixed-arch box (gfx1100 primary + gfx1030 secondary) the policy froze at the
primary's, so the RDNA2 card ran RDNA3-tuned MMB kernels -- byte-exact zero output-projection logits (PPL ==
vocab) or garbled tail layers, depending on where the output projection sat.  On a single-arch box this is
bit-for-bit the previous behaviour (validated here on 3x gfx1201: 12/12 same-seed configs byte-identical,
prefill-logit KLD 0.000000 on both recorded points, no GPU faults).

Co-authored-by: Slava P. <[email protected]>

Fold (r134, issue ggml-org#224): the width probe's n_ctx is now the prefill length plus the decode
width instead of a fixed 4096, and a purity run must pass P >= 4096.  The RDNA4 band's
64-column block (query widths 5..8) is only reachable above the launcher's KV-length gate
(K->ne[1] >= 4096), and K->ne[1] is the context's used length, so the P=256 default never
reached that block: the probe reported PASS on every arm while widths 5..8 ran a geometry
that was not bit-identical to widths 1..4.  At P=4096 the r126 geometry fails it
(width_purity=FAIL, worst maxdiff 0.199764 on q8_0 K/V, row-0 hash split between W=4 and
W=5), and the shipped band geometry passes with maxdiff 0.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 26, 2026
…oE + old-15 PR57/63)

Merged from the planned 08 fused-prefill and 09 fused-moe: the two are not
hunk-separable (the fusions and the mmvq dispatch share ggml_cuda.cu try_fuse,
mmvq.cu, norm.cu, common.cuh and the ggml_cuda_mm_fusion_args plumbing), and the
old-08-only fusion set was not correct (fusion-on greedy text differed from
fusion-off).

Contents:
- old-08 fusions: gdn-conv, ple-conv, norm-gated, topk-moe, the norm/unary/
  getrows/argsort kernels, the CPU references and the try_fuse arms.
- old-13: fused MoE gate+up+GLU MMQ, the mmvq short-K item-split/ksplit, the
  routed-compact MMQ (mmq.cuh/mmq-config), MWR, the mmq gate instances.
- old-15 PR ggml-org#57/ggml-org#63: the mmvq multi-row/row-loop decode (GGML_MMVQ_RDNA4_
  DECODE_GRID, nrows_loop, the lf_nval halving reduction), ssm_gate_beta/
  ssm_conv_l2_gatebeta, the norm rms_norm_q8_1 refactor and quantize_mmq_q8_1_glu.

The MoE-cache-aware arms (moe_cache_get_cold/redirect, the B1 stand-down) and
the qwen4exp/HC arms are deliberately NOT here -- they belong to the slab-moe and
qwen4exp blocks, and their absence leaves the resident-only path (bit-identical).

Gates: build all OK; fusion on == off (4B greedy text); test-logits-width-probe
width_purity PASS; MUL_MAT 2444/2444.

Amended (r132): the Q8_1 quantize cache is keyed by the ROOT tensor's identity but filled from the (possibly
offset) view's pointer, so an offset view stored its rows under the root identity and a later op with the same
root and canonical row layout could hit them.  Every key walk that reaches the cache now stops at the first
pointer change (this block: the four mmvq sites and the unary mul_q8_1 site; block 10 adds its own GLU site), so
offset-free views keep the shared root entry and an offset view gets its own arena entry.  A new
q8_1_src_range_ok() validates the source read range against the root buffer's allocation before every
quantize_row_q8_1_cuda / fused gated-q8_1 launch, so a stale source pointer (a compute buffer reallocated under a
still-matching cache entry) aborts loudly with the layout logged instead of faulting with
HSA_STATUS_ERROR_MEMORY_APERTURE_VIOLATION or silently reading reused memory.

Reported in PR ggml-org#218 (@slavap), whose V620 hit the fault on decode.  Not reachable on the maintainer's model set
(0 offset-view keys in 14336-60416 key walks per config across 7 configs, probed on gfx1201), so this is a
correctness fix for configurations we do not run: 12/12 same-seed configs byte-identical, MTP acceptance
identical (1859/3416, 1420/1710, 2171/2483, 372/375 on the four axes), prefill-logit KLD 0.000000.

Co-authored-by: Slava P. <[email protected]>
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 26, 2026
…rastructure)

The infrastructure half of the old block 10.  qwen4exp, QSA and the
hyper-connection ops now live in their own block (11); this block is what they
are built on, and it no longer references them.

Contents:

- The movable-boundary slab and its arena (ggml-cuda-slab.cu,
  ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM
  reserve per device split by a movable boundary -- compute below, MoE arena
  above, no HIP call at runtime.  Plus the narrow-band learning, the wide-phase
  auxiliary region, pool-wide routing, and the slab transient absorption.
- The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of
  ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it.
- The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the
  r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU
  split's output, which the next ubatch rewrites), default-on, and the per-origin
  (per host thread) ordering state of issue ggml-org#201.
- Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT)
  matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes
  folded into the rope + FWHT kernel, and the paired GDN q/k norms.
- GDN / attention-gate decode fusions: the BF16 alpha/beta pair with
  softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108
  multi-sequence fix and its model-free regression test), the q/k norm pair in
  the direct conv kernel, the attention gate's row-strided view read in place by
  the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and
  GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots).
- MMB and the HC16 BF16 streams: the per-context MMB state (two contexts
  interleaving must not share the activation cache or the marks), the BF16
  activation copies, DOWN16, and the graph-optimize marking passes.
- The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel),
  the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output
  matmul, the MoE down fold, and the weighted-down reduction.
- The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize
  predicate and in the direct GDN conv.
- Meta/scheduler/allocator: the split-state refusals for a straddling split,
  the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory
  generations so a graph is recaptured when the pool / FA staging / H2D ring
  memory it captured is freed -- including the slab work-boundary shrink of
  issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy
  instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED).
- bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16
  instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu.

Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED /
GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values
rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the
next getenv() call overwrites, so a cached pointer is unsafe on Windows.

Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve
lives in src/ (not linked against the CUDA common.cuh), so it uses a local
static instead of the CUDA helper.

Split note (r109): this commit plus block 11 carries exactly the tree the old
block 10 carried -- the net set is unchanged.  What moved to block 11 is the
qwen4exp model graph, the QSA/indexer ops and their kernels, the
hyper-connection ops, the managed lazy reader and the keys-only indexer cache,
i.e. everything that exists only because of that architecture.  The pieces of
the old block 10 that exist for qwen4exp but are implemented inside a general
kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp
weighted-down reduction, the PLE conv fusion) stay here with the TU that owns
them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved
to block 11 with the matchers they call.

Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers
block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`.  With HIP on Windows (clang + the
MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an
inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's
version win overload resolution is not part of the mangled name), so a translation unit that
instantiates both fails to codegen with "definition with same mangled name".  Behaviour is unchanged.

Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces.  The fused GLU -> Q8_1 site's
key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the
root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel
and the GLU write -- validate their sources with q8_1_src_range_ok() before launching.  From PR ggml-org#218 (@slavap);
the rule and the validation are recorded with block 08.

Co-authored-by: Slava P. <[email protected]>
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 26, 2026
…rastructure)

The infrastructure half of the old block 10.  qwen4exp, QSA and the
hyper-connection ops now live in their own block (11); this block is what they
are built on, and it no longer references them.

Contents:

- The movable-boundary slab and its arena (ggml-cuda-slab.cu,
  ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM
  reserve per device split by a movable boundary -- compute below, MoE arena
  above, no HIP call at runtime.  Plus the narrow-band learning, the wide-phase
  auxiliary region, pool-wide routing, and the slab transient absorption.
- The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of
  ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it.
- The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the
  r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU
  split's output, which the next ubatch rewrites), default-on, and the per-origin
  (per host thread) ordering state of issue ggml-org#201.
- Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT)
  matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes
  folded into the rope + FWHT kernel, and the paired GDN q/k norms.
- GDN / attention-gate decode fusions: the BF16 alpha/beta pair with
  softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108
  multi-sequence fix and its model-free regression test), the q/k norm pair in
  the direct conv kernel, the attention gate's row-strided view read in place by
  the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and
  GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots).
- MMB and the HC16 BF16 streams: the per-context MMB state (two contexts
  interleaving must not share the activation cache or the marks), the BF16
  activation copies, DOWN16, and the graph-optimize marking passes.
- The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel),
  the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output
  matmul, the MoE down fold, and the weighted-down reduction.
- The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize
  predicate and in the direct GDN conv.
- Meta/scheduler/allocator: the split-state refusals for a straddling split,
  the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory
  generations so a graph is recaptured when the pool / FA staging / H2D ring
  memory it captured is freed -- including the slab work-boundary shrink of
  issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy
  instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED).
- bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16
  instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu.

Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED /
GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values
rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the
next getenv() call overwrites, so a cached pointer is unsafe on Windows.

Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve
lives in src/ (not linked against the CUDA common.cuh), so it uses a local
static instead of the CUDA helper.

Split note (r109): this commit plus block 11 carries exactly the tree the old
block 10 carried -- the net set is unchanged.  What moved to block 11 is the
qwen4exp model graph, the QSA/indexer ops and their kernels, the
hyper-connection ops, the managed lazy reader and the keys-only indexer cache,
i.e. everything that exists only because of that architecture.  The pieces of
the old block 10 that exist for qwen4exp but are implemented inside a general
kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp
weighted-down reduction, the PLE conv fusion) stay here with the TU that owns
them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved
to block 11 with the matchers they call.

Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers
block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`.  With HIP on Windows (clang + the
MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an
inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's
version win overload resolution is not part of the mangled name), so a translation unit that
instantiates both fails to codegen with "definition with same mangled name".  Behaviour is unchanged.

Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces.  The fused GLU -> Q8_1 site's
key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the
root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel
and the GLU write -- validate their sources with q8_1_src_range_ok() before launching.  From PR ggml-org#218 (@slavap);
the rule and the validation are recorded with block 08.

Co-authored-by: Slava P. <[email protected]>
kiljoy001 pushed a commit to kiljoy001/llama.cpp that referenced this pull request Oct 26, 2026
… -30%, MTP depth 5 x1.24 on H200; not token-identical at verify width >= 5) (ggml-org#382)

On Hopper, PTQ1_0 batches of 5-8 columns stay on the PT mat-vec instead of falling back to MMQ (pp N=5 -30%, N=8 -16% on H200; MTP depth 5 x1.24).

Not token-identical to the previous MMQ path at verify widths >= 5. The KLD gate against an F16 reference is at the noise floor (27B ub8: mean KLD 3.04e-4 vs 3.06e-4, top-1 +0.04 pp).

Builds on the PT kernel from ggml-org#218; related to ggml-org#322.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 26, 2026
Also adds mmf32, the F32 counterpart of MMB: the
shapes MMB cannot take -- non-quantized (F32) weights with more than 16 token columns -- currently fall
through ggml_cuda_mul_mat_cublas() to rocBLAS, which dispatches to hipBLASLt.

Two reasons to own that path:
  * correctness: hipBLASLt picks its solution per process start from a heap-ordered container, so the prefill
    arithmetic (and therefore the logits) changes between fresh runs -- GREEDY-PURITY.md §44, TODO ggml-org#75: 3
    logit classes in 8 starts on 35B-A3B, 3 in 18 on gemma4;
  * speed: the solution the heuristic lands on is the slowest in the pool for these shapes (0.13-0.19 ms vs
    0.046 ms for a well-chosen one).

mmf32 is a plain SIMT tiled GEMM (RDNA has no F32 MMA form: amd_mfma_available is CDNA-only,
amd_wmma_available is f16/bf16).  32 output rows per block, a 4x8 thread sub-tile, BN=256 for m <= 64 (the
GDN ssm_alpha/ssm_beta projections) and 64 above it (the MoE routers), and the k range split into contiguous
chunks summed in increasing z -- a fixed reduction tree, no atomics, so a run is bit-stable by construction.
No approximation: an F32 FMA accumulation in a pinned order.

Scope: F32 weights only, m <= 256, 17 <= n <= 65536, 256 <= k <= 8192, ldc == m; every other mul_mat keeps the
rocBLAS call unchanged (BF16/f16 prefill -- Flash-Next -- is untouched, as is its hipBLASLt advantage; a
full-F32 model's FFN GEMMs, m >> 256, stay on rocBLAS: a recorded limitation).

Measured on gfx1201 (35B-A3B Q4_K_M, one GPU): deterministic -- one logits class in 12/12 fresh starts (6/6 at
2 GPU -sm tensor), --chunks 8 dumps byte-identical; +4.2 % pp512 / +4.1 % pp2048, decode flat (3 interleaved
llama-bench visits); kernel 0.032 ms vs 0.046 ms for the best hipBLASLt class on 32x512x2048.  Correctness:
16-shape oracle NMSE ~1e-13, and 11x closer to the CPU reference than the rocBLAS path on the
test-backend-ops cases it intercepts.  Purity: judged with the family-switch gate at a confident point
(in-domain corpus, base PPL 1.43) at 0.014646 / 98.045 % against a same-kernel control of 0.018100 / 97.808 %.

Default-on for RDNA4 (GGML_CUDA_MMF32=0 disables; opt-in on RDNA3/RDNA3_5 until those boxes run the same
determinism + bench pair).  GGML_CUDA_MMF32_LOG prints the resolved plans (diagnostic only).

Amended (r132): the per-arch dispatch is keyed to the device the kernel runs on, not the primary.  mmb_enabled,
mmb_cfg, mmb_cfg_dump_once, mmb_dense_flag, mmb_wtype_mask and mmb_dense_tmask read
ggml_cuda_info().devices[ggml_cuda_get_device()].cc, and mmb_cfg() takes one magic static per architecture class
(mmb_arch_defaults() only discriminates RDNA4 and RDNA3_0, so every cc that reaches the fallback shares the same
pre-S11 table).  ggml_backend_cuda_graph_optimize() now selects its own context's device before it consults those
predicates, so the MMB marking half agrees with the launch path under the Meta backend, where the pass is
forwarded per child from meta graph_compute and the current device is still the previously computed one.

Reported in PR ggml-org#218 (@slavap): on a mixed-arch box (gfx1100 primary + gfx1030 secondary) the policy froze at the
primary's, so the RDNA2 card ran RDNA3-tuned MMB kernels -- byte-exact zero output-projection logits (PPL ==
vocab) or garbled tail layers, depending on where the output projection sat.  On a single-arch box this is
bit-for-bit the previous behaviour (validated here on 3x gfx1201: 12/12 same-seed configs byte-identical,
prefill-logit KLD 0.000000 on both recorded points, no GPU faults).

Co-authored-by: Slava P. <[email protected]>

Fold (r134, issue ggml-org#224): the width probe's n_ctx is now the prefill length plus the decode
width instead of a fixed 4096, and a purity run must pass P >= 4096.  The RDNA4 band's
64-column block (query widths 5..8) is only reachable above the launcher's KV-length gate
(K->ne[1] >= 4096), and K->ne[1] is the context's used length, so the P=256 default never
reached that block: the probe reported PASS on every arm while widths 5..8 ran a geometry
that was not bit-identical to widths 1..4.  At P=4096 the r126 geometry fails it
(width_purity=FAIL, worst maxdiff 0.199764 on q8_0 K/V, row-0 hash split between W=4 and
W=5), and the shipped band geometry passes with maxdiff 0.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 26, 2026
…oE + old-15 PR57/63)

Merged from the planned 08 fused-prefill and 09 fused-moe: the two are not
hunk-separable (the fusions and the mmvq dispatch share ggml_cuda.cu try_fuse,
mmvq.cu, norm.cu, common.cuh and the ggml_cuda_mm_fusion_args plumbing), and the
old-08-only fusion set was not correct (fusion-on greedy text differed from
fusion-off).

Contents:
- old-08 fusions: gdn-conv, ple-conv, norm-gated, topk-moe, the norm/unary/
  getrows/argsort kernels, the CPU references and the try_fuse arms.
- old-13: fused MoE gate+up+GLU MMQ, the mmvq short-K item-split/ksplit, the
  routed-compact MMQ (mmq.cuh/mmq-config), MWR, the mmq gate instances.
- old-15 PR ggml-org#57/ggml-org#63: the mmvq multi-row/row-loop decode (GGML_MMVQ_RDNA4_
  DECODE_GRID, nrows_loop, the lf_nval halving reduction), ssm_gate_beta/
  ssm_conv_l2_gatebeta, the norm rms_norm_q8_1 refactor and quantize_mmq_q8_1_glu.

The MoE-cache-aware arms (moe_cache_get_cold/redirect, the B1 stand-down) and
the qwen4exp/HC arms are deliberately NOT here -- they belong to the slab-moe and
qwen4exp blocks, and their absence leaves the resident-only path (bit-identical).

Gates: build all OK; fusion on == off (4B greedy text); test-logits-width-probe
width_purity PASS; MUL_MAT 2444/2444.

Amended (r132): the Q8_1 quantize cache is keyed by the ROOT tensor's identity but filled from the (possibly
offset) view's pointer, so an offset view stored its rows under the root identity and a later op with the same
root and canonical row layout could hit them.  Every key walk that reaches the cache now stops at the first
pointer change (this block: the four mmvq sites and the unary mul_q8_1 site; block 10 adds its own GLU site), so
offset-free views keep the shared root entry and an offset view gets its own arena entry.  A new
q8_1_src_range_ok() validates the source read range against the root buffer's allocation before every
quantize_row_q8_1_cuda / fused gated-q8_1 launch, so a stale source pointer (a compute buffer reallocated under a
still-matching cache entry) aborts loudly with the layout logged instead of faulting with
HSA_STATUS_ERROR_MEMORY_APERTURE_VIOLATION or silently reading reused memory.

Reported in PR ggml-org#218 (@slavap), whose V620 hit the fault on decode.  Not reachable on the maintainer's model set
(0 offset-view keys in 14336-60416 key walks per config across 7 configs, probed on gfx1201), so this is a
correctness fix for configurations we do not run: 12/12 same-seed configs byte-identical, MTP acceptance
identical (1859/3416, 1420/1710, 2171/2483, 372/375 on the four axes), prefill-logit KLD 0.000000.

Co-authored-by: Slava P. <[email protected]>
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 26, 2026
…rastructure)

The infrastructure half of the old block 10.  qwen4exp, QSA and the
hyper-connection ops now live in their own block (11); this block is what they
are built on, and it no longer references them.

Contents:

- The movable-boundary slab and its arena (ggml-cuda-slab.cu,
  ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM
  reserve per device split by a movable boundary -- compute below, MoE arena
  above, no HIP call at runtime.  Plus the narrow-band learning, the wide-phase
  auxiliary region, pool-wide routing, and the slab transient absorption.
- The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of
  ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it.
- The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the
  r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU
  split's output, which the next ubatch rewrites), default-on, and the per-origin
  (per host thread) ordering state of issue ggml-org#201.
- Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT)
  matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes
  folded into the rope + FWHT kernel, and the paired GDN q/k norms.
- GDN / attention-gate decode fusions: the BF16 alpha/beta pair with
  softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108
  multi-sequence fix and its model-free regression test), the q/k norm pair in
  the direct conv kernel, the attention gate's row-strided view read in place by
  the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and
  GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots).
- MMB and the HC16 BF16 streams: the per-context MMB state (two contexts
  interleaving must not share the activation cache or the marks), the BF16
  activation copies, DOWN16, and the graph-optimize marking passes.
- The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel),
  the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output
  matmul, the MoE down fold, and the weighted-down reduction.
- The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize
  predicate and in the direct GDN conv.
- Meta/scheduler/allocator: the split-state refusals for a straddling split,
  the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory
  generations so a graph is recaptured when the pool / FA staging / H2D ring
  memory it captured is freed -- including the slab work-boundary shrink of
  issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy
  instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED).
- bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16
  instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu.

Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED /
GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values
rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the
next getenv() call overwrites, so a cached pointer is unsafe on Windows.

Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve
lives in src/ (not linked against the CUDA common.cuh), so it uses a local
static instead of the CUDA helper.

Split note (r109): this commit plus block 11 carries exactly the tree the old
block 10 carried -- the net set is unchanged.  What moved to block 11 is the
qwen4exp model graph, the QSA/indexer ops and their kernels, the
hyper-connection ops, the managed lazy reader and the keys-only indexer cache,
i.e. everything that exists only because of that architecture.  The pieces of
the old block 10 that exist for qwen4exp but are implemented inside a general
kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp
weighted-down reduction, the PLE conv fusion) stay here with the TU that owns
them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved
to block 11 with the matchers they call.

Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers
block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`.  With HIP on Windows (clang + the
MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an
inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's
version win overload resolution is not part of the mangled name), so a translation unit that
instantiates both fails to codegen with "definition with same mangled name".  Behaviour is unchanged.

Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces.  The fused GLU -> Q8_1 site's
key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the
root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel
and the GLU write -- validate their sources with q8_1_src_range_ok() before launching.  From PR ggml-org#218 (@slavap);
the rule and the validation are recorded with block 08.

Co-authored-by: Slava P. <[email protected]>
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 26, 2026
Also adds mmf32, the F32 counterpart of MMB: the
shapes MMB cannot take -- non-quantized (F32) weights with more than 16 token columns -- currently fall
through ggml_cuda_mul_mat_cublas() to rocBLAS, which dispatches to hipBLASLt.

Two reasons to own that path:
  * correctness: hipBLASLt picks its solution per process start from a heap-ordered container, so the prefill
    arithmetic (and therefore the logits) changes between fresh runs -- GREEDY-PURITY.md §44, TODO ggml-org#75: 3
    logit classes in 8 starts on 35B-A3B, 3 in 18 on gemma4;
  * speed: the solution the heuristic lands on is the slowest in the pool for these shapes (0.13-0.19 ms vs
    0.046 ms for a well-chosen one).

mmf32 is a plain SIMT tiled GEMM (RDNA has no F32 MMA form: amd_mfma_available is CDNA-only,
amd_wmma_available is f16/bf16).  32 output rows per block, a 4x8 thread sub-tile, BN=256 for m <= 64 (the
GDN ssm_alpha/ssm_beta projections) and 64 above it (the MoE routers), and the k range split into contiguous
chunks summed in increasing z -- a fixed reduction tree, no atomics, so a run is bit-stable by construction.
No approximation: an F32 FMA accumulation in a pinned order.

Scope: F32 weights only, m <= 256, 17 <= n <= 65536, 256 <= k <= 8192, ldc == m; every other mul_mat keeps the
rocBLAS call unchanged (BF16/f16 prefill -- Flash-Next -- is untouched, as is its hipBLASLt advantage; a
full-F32 model's FFN GEMMs, m >> 256, stay on rocBLAS: a recorded limitation).

Measured on gfx1201 (35B-A3B Q4_K_M, one GPU): deterministic -- one logits class in 12/12 fresh starts (6/6 at
2 GPU -sm tensor), --chunks 8 dumps byte-identical; +4.2 % pp512 / +4.1 % pp2048, decode flat (3 interleaved
llama-bench visits); kernel 0.032 ms vs 0.046 ms for the best hipBLASLt class on 32x512x2048.  Correctness:
16-shape oracle NMSE ~1e-13, and 11x closer to the CPU reference than the rocBLAS path on the
test-backend-ops cases it intercepts.  Purity: judged with the family-switch gate at a confident point
(in-domain corpus, base PPL 1.43) at 0.014646 / 98.045 % against a same-kernel control of 0.018100 / 97.808 %.

Default-on for RDNA4 (GGML_CUDA_MMF32=0 disables; opt-in on RDNA3/RDNA3_5 until those boxes run the same
determinism + bench pair).  GGML_CUDA_MMF32_LOG prints the resolved plans (diagnostic only).

Amended (r132): the per-arch dispatch is keyed to the device the kernel runs on, not the primary.  mmb_enabled,
mmb_cfg, mmb_cfg_dump_once, mmb_dense_flag, mmb_wtype_mask and mmb_dense_tmask read
ggml_cuda_info().devices[ggml_cuda_get_device()].cc, and mmb_cfg() takes one magic static per architecture class
(mmb_arch_defaults() only discriminates RDNA4 and RDNA3_0, so every cc that reaches the fallback shares the same
pre-S11 table).  ggml_backend_cuda_graph_optimize() now selects its own context's device before it consults those
predicates, so the MMB marking half agrees with the launch path under the Meta backend, where the pass is
forwarded per child from meta graph_compute and the current device is still the previously computed one.

Reported in PR ggml-org#218 (@slavap): on a mixed-arch box (gfx1100 primary + gfx1030 secondary) the policy froze at the
primary's, so the RDNA2 card ran RDNA3-tuned MMB kernels -- byte-exact zero output-projection logits (PPL ==
vocab) or garbled tail layers, depending on where the output projection sat.  On a single-arch box this is
bit-for-bit the previous behaviour (validated here on 3x gfx1201: 12/12 same-seed configs byte-identical,
prefill-logit KLD 0.000000 on both recorded points, no GPU faults).

Co-authored-by: Slava P. <[email protected]>

Fold (r134, issue ggml-org#224): the width probe's n_ctx is now the prefill length plus the decode
width instead of a fixed 4096, and a purity run must pass P >= 4096.  The RDNA4 band's
64-column block (query widths 5..8) is only reachable above the launcher's KV-length gate
(K->ne[1] >= 4096), and K->ne[1] is the context's used length, so the P=256 default never
reached that block: the probe reported PASS on every arm while widths 5..8 ran a geometry
that was not bit-identical to widths 1..4.  At P=4096 the r126 geometry fails it
(width_purity=FAIL, worst maxdiff 0.199764 on q8_0 K/V, row-0 hash split between W=4 and
W=5), and the shipped band geometry passes with maxdiff 0.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 26, 2026
…oE + old-15 PR57/63)

Merged from the planned 08 fused-prefill and 09 fused-moe: the two are not
hunk-separable (the fusions and the mmvq dispatch share ggml_cuda.cu try_fuse,
mmvq.cu, norm.cu, common.cuh and the ggml_cuda_mm_fusion_args plumbing), and the
old-08-only fusion set was not correct (fusion-on greedy text differed from
fusion-off).

Contents:
- old-08 fusions: gdn-conv, ple-conv, norm-gated, topk-moe, the norm/unary/
  getrows/argsort kernels, the CPU references and the try_fuse arms.
- old-13: fused MoE gate+up+GLU MMQ, the mmvq short-K item-split/ksplit, the
  routed-compact MMQ (mmq.cuh/mmq-config), MWR, the mmq gate instances.
- old-15 PR ggml-org#57/ggml-org#63: the mmvq multi-row/row-loop decode (GGML_MMVQ_RDNA4_
  DECODE_GRID, nrows_loop, the lf_nval halving reduction), ssm_gate_beta/
  ssm_conv_l2_gatebeta, the norm rms_norm_q8_1 refactor and quantize_mmq_q8_1_glu.

The MoE-cache-aware arms (moe_cache_get_cold/redirect, the B1 stand-down) and
the qwen4exp/HC arms are deliberately NOT here -- they belong to the slab-moe and
qwen4exp blocks, and their absence leaves the resident-only path (bit-identical).

Gates: build all OK; fusion on == off (4B greedy text); test-logits-width-probe
width_purity PASS; MUL_MAT 2444/2444.

Amended (r132): the Q8_1 quantize cache is keyed by the ROOT tensor's identity but filled from the (possibly
offset) view's pointer, so an offset view stored its rows under the root identity and a later op with the same
root and canonical row layout could hit them.  Every key walk that reaches the cache now stops at the first
pointer change (this block: the four mmvq sites and the unary mul_q8_1 site; block 10 adds its own GLU site), so
offset-free views keep the shared root entry and an offset view gets its own arena entry.  A new
q8_1_src_range_ok() validates the source read range against the root buffer's allocation before every
quantize_row_q8_1_cuda / fused gated-q8_1 launch, so a stale source pointer (a compute buffer reallocated under a
still-matching cache entry) aborts loudly with the layout logged instead of faulting with
HSA_STATUS_ERROR_MEMORY_APERTURE_VIOLATION or silently reading reused memory.

Reported in PR ggml-org#218 (@slavap), whose V620 hit the fault on decode.  Not reachable on the maintainer's model set
(0 offset-view keys in 14336-60416 key walks per config across 7 configs, probed on gfx1201), so this is a
correctness fix for configurations we do not run: 12/12 same-seed configs byte-identical, MTP acceptance
identical (1859/3416, 1420/1710, 2171/2483, 372/375 on the four axes), prefill-logit KLD 0.000000.

Co-authored-by: Slava P. <[email protected]>
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 26, 2026
…rastructure)

The infrastructure half of the old block 10.  qwen4exp, QSA and the
hyper-connection ops now live in their own block (11); this block is what they
are built on, and it no longer references them.

Contents:

- The movable-boundary slab and its arena (ggml-cuda-slab.cu,
  ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM
  reserve per device split by a movable boundary -- compute below, MoE arena
  above, no HIP call at runtime.  Plus the narrow-band learning, the wide-phase
  auxiliary region, pool-wide routing, and the slab transient absorption.
- The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of
  ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it.
- The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the
  r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU
  split's output, which the next ubatch rewrites), default-on, and the per-origin
  (per host thread) ordering state of issue ggml-org#201.
- Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT)
  matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes
  folded into the rope + FWHT kernel, and the paired GDN q/k norms.
- GDN / attention-gate decode fusions: the BF16 alpha/beta pair with
  softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108
  multi-sequence fix and its model-free regression test), the q/k norm pair in
  the direct conv kernel, the attention gate's row-strided view read in place by
  the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and
  GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots).
- MMB and the HC16 BF16 streams: the per-context MMB state (two contexts
  interleaving must not share the activation cache or the marks), the BF16
  activation copies, DOWN16, and the graph-optimize marking passes.
- The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel),
  the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output
  matmul, the MoE down fold, and the weighted-down reduction.
- The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize
  predicate and in the direct GDN conv.
- Meta/scheduler/allocator: the split-state refusals for a straddling split,
  the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory
  generations so a graph is recaptured when the pool / FA staging / H2D ring
  memory it captured is freed -- including the slab work-boundary shrink of
  issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy
  instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED).
- bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16
  instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu.

Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED /
GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values
rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the
next getenv() call overwrites, so a cached pointer is unsafe on Windows.

Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve
lives in src/ (not linked against the CUDA common.cuh), so it uses a local
static instead of the CUDA helper.

Split note (r109): this commit plus block 11 carries exactly the tree the old
block 10 carried -- the net set is unchanged.  What moved to block 11 is the
qwen4exp model graph, the QSA/indexer ops and their kernels, the
hyper-connection ops, the managed lazy reader and the keys-only indexer cache,
i.e. everything that exists only because of that architecture.  The pieces of
the old block 10 that exist for qwen4exp but are implemented inside a general
kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp
weighted-down reduction, the PLE conv fusion) stay here with the TU that owns
them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved
to block 11 with the matchers they call.

Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers
block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`.  With HIP on Windows (clang + the
MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an
inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's
version win overload resolution is not part of the mangled name), so a translation unit that
instantiates both fails to codegen with "definition with same mangled name".  Behaviour is unchanged.

Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces.  The fused GLU -> Q8_1 site's
key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the
root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel
and the GLU write -- validate their sources with q8_1_src_range_ok() before launching.  From PR ggml-org#218 (@slavap);
the rule and the validation are recorded with block 08.

Co-authored-by: Slava P. <[email protected]>
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 27, 2026
Also adds mmf32, the F32 counterpart of MMB: the
shapes MMB cannot take -- non-quantized (F32) weights with more than 16 token columns -- currently fall
through ggml_cuda_mul_mat_cublas() to rocBLAS, which dispatches to hipBLASLt.

Two reasons to own that path:
  * correctness: hipBLASLt picks its solution per process start from a heap-ordered container, so the prefill
    arithmetic (and therefore the logits) changes between fresh runs -- GREEDY-PURITY.md §44, TODO ggml-org#75: 3
    logit classes in 8 starts on 35B-A3B, 3 in 18 on gemma4;
  * speed: the solution the heuristic lands on is the slowest in the pool for these shapes (0.13-0.19 ms vs
    0.046 ms for a well-chosen one).

mmf32 is a plain SIMT tiled GEMM (RDNA has no F32 MMA form: amd_mfma_available is CDNA-only,
amd_wmma_available is f16/bf16).  32 output rows per block, a 4x8 thread sub-tile, BN=256 for m <= 64 (the
GDN ssm_alpha/ssm_beta projections) and 64 above it (the MoE routers), and the k range split into contiguous
chunks summed in increasing z -- a fixed reduction tree, no atomics, so a run is bit-stable by construction.
No approximation: an F32 FMA accumulation in a pinned order.

Scope: F32 weights only, m <= 256, 17 <= n <= 65536, 256 <= k <= 8192, ldc == m; every other mul_mat keeps the
rocBLAS call unchanged (BF16/f16 prefill -- Flash-Next -- is untouched, as is its hipBLASLt advantage; a
full-F32 model's FFN GEMMs, m >> 256, stay on rocBLAS: a recorded limitation).

Measured on gfx1201 (35B-A3B Q4_K_M, one GPU): deterministic -- one logits class in 12/12 fresh starts (6/6 at
2 GPU -sm tensor), --chunks 8 dumps byte-identical; +4.2 % pp512 / +4.1 % pp2048, decode flat (3 interleaved
llama-bench visits); kernel 0.032 ms vs 0.046 ms for the best hipBLASLt class on 32x512x2048.  Correctness:
16-shape oracle NMSE ~1e-13, and 11x closer to the CPU reference than the rocBLAS path on the
test-backend-ops cases it intercepts.  Purity: judged with the family-switch gate at a confident point
(in-domain corpus, base PPL 1.43) at 0.014646 / 98.045 % against a same-kernel control of 0.018100 / 97.808 %.

Default-on for RDNA4 (GGML_CUDA_MMF32=0 disables; opt-in on RDNA3/RDNA3_5 until those boxes run the same
determinism + bench pair).  GGML_CUDA_MMF32_LOG prints the resolved plans (diagnostic only).

Amended (r132): the per-arch dispatch is keyed to the device the kernel runs on, not the primary.  mmb_enabled,
mmb_cfg, mmb_cfg_dump_once, mmb_dense_flag, mmb_wtype_mask and mmb_dense_tmask read
ggml_cuda_info().devices[ggml_cuda_get_device()].cc, and mmb_cfg() takes one magic static per architecture class
(mmb_arch_defaults() only discriminates RDNA4 and RDNA3_0, so every cc that reaches the fallback shares the same
pre-S11 table).  ggml_backend_cuda_graph_optimize() now selects its own context's device before it consults those
predicates, so the MMB marking half agrees with the launch path under the Meta backend, where the pass is
forwarded per child from meta graph_compute and the current device is still the previously computed one.

Reported in PR ggml-org#218 (@slavap): on a mixed-arch box (gfx1100 primary + gfx1030 secondary) the policy froze at the
primary's, so the RDNA2 card ran RDNA3-tuned MMB kernels -- byte-exact zero output-projection logits (PPL ==
vocab) or garbled tail layers, depending on where the output projection sat.  On a single-arch box this is
bit-for-bit the previous behaviour (validated here on 3x gfx1201: 12/12 same-seed configs byte-identical,
prefill-logit KLD 0.000000 on both recorded points, no GPU faults).

Co-authored-by: Slava P. <[email protected]>

Fold (r134, issue ggml-org#224): the width probe's n_ctx is now the prefill length plus the decode
width instead of a fixed 4096, and a purity run must pass P >= 4096.  The RDNA4 band's
64-column block (query widths 5..8) is only reachable above the launcher's KV-length gate
(K->ne[1] >= 4096), and K->ne[1] is the context's used length, so the P=256 default never
reached that block: the probe reported PASS on every arm while widths 5..8 ran a geometry
that was not bit-identical to widths 1..4.  At P=4096 the r126 geometry fails it
(width_purity=FAIL, worst maxdiff 0.199764 on q8_0 K/V, row-0 hash split between W=4 and
W=5), and the shipped band geometry passes with maxdiff 0.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 27, 2026
…oE + old-15 PR57/63)

Merged from the planned 08 fused-prefill and 09 fused-moe: the two are not
hunk-separable (the fusions and the mmvq dispatch share ggml_cuda.cu try_fuse,
mmvq.cu, norm.cu, common.cuh and the ggml_cuda_mm_fusion_args plumbing), and the
old-08-only fusion set was not correct (fusion-on greedy text differed from
fusion-off).

Contents:
- old-08 fusions: gdn-conv, ple-conv, norm-gated, topk-moe, the norm/unary/
  getrows/argsort kernels, the CPU references and the try_fuse arms.
- old-13: fused MoE gate+up+GLU MMQ, the mmvq short-K item-split/ksplit, the
  routed-compact MMQ (mmq.cuh/mmq-config), MWR, the mmq gate instances.
- old-15 PR ggml-org#57/ggml-org#63: the mmvq multi-row/row-loop decode (GGML_MMVQ_RDNA4_
  DECODE_GRID, nrows_loop, the lf_nval halving reduction), ssm_gate_beta/
  ssm_conv_l2_gatebeta, the norm rms_norm_q8_1 refactor and quantize_mmq_q8_1_glu.

The MoE-cache-aware arms (moe_cache_get_cold/redirect, the B1 stand-down) and
the qwen4exp/HC arms are deliberately NOT here -- they belong to the slab-moe and
qwen4exp blocks, and their absence leaves the resident-only path (bit-identical).

Gates: build all OK; fusion on == off (4B greedy text); test-logits-width-probe
width_purity PASS; MUL_MAT 2444/2444.

Amended (r132): the Q8_1 quantize cache is keyed by the ROOT tensor's identity but filled from the (possibly
offset) view's pointer, so an offset view stored its rows under the root identity and a later op with the same
root and canonical row layout could hit them.  Every key walk that reaches the cache now stops at the first
pointer change (this block: the four mmvq sites and the unary mul_q8_1 site; block 10 adds its own GLU site), so
offset-free views keep the shared root entry and an offset view gets its own arena entry.  A new
q8_1_src_range_ok() validates the source read range against the root buffer's allocation before every
quantize_row_q8_1_cuda / fused gated-q8_1 launch, so a stale source pointer (a compute buffer reallocated under a
still-matching cache entry) aborts loudly with the layout logged instead of faulting with
HSA_STATUS_ERROR_MEMORY_APERTURE_VIOLATION or silently reading reused memory.

Reported in PR ggml-org#218 (@slavap), whose V620 hit the fault on decode.  Not reachable on the maintainer's model set
(0 offset-view keys in 14336-60416 key walks per config across 7 configs, probed on gfx1201), so this is a
correctness fix for configurations we do not run: 12/12 same-seed configs byte-identical, MTP acceptance
identical (1859/3416, 1420/1710, 2171/2483, 372/375 on the four axes), prefill-logit KLD 0.000000.

Co-authored-by: Slava P. <[email protected]>
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 27, 2026
…rastructure)

The infrastructure half of the old block 10.  qwen4exp, QSA and the
hyper-connection ops now live in their own block (11); this block is what they
are built on, and it no longer references them.

Contents:

- The movable-boundary slab and its arena (ggml-cuda-slab.cu,
  ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM
  reserve per device split by a movable boundary -- compute below, MoE arena
  above, no HIP call at runtime.  Plus the narrow-band learning, the wide-phase
  auxiliary region, pool-wide routing, and the slab transient absorption.
- The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of
  ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it.
- The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the
  r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU
  split's output, which the next ubatch rewrites), default-on, and the per-origin
  (per host thread) ordering state of issue ggml-org#201.
- Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT)
  matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes
  folded into the rope + FWHT kernel, and the paired GDN q/k norms.
- GDN / attention-gate decode fusions: the BF16 alpha/beta pair with
  softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108
  multi-sequence fix and its model-free regression test), the q/k norm pair in
  the direct conv kernel, the attention gate's row-strided view read in place by
  the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and
  GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots).
- MMB and the HC16 BF16 streams: the per-context MMB state (two contexts
  interleaving must not share the activation cache or the marks), the BF16
  activation copies, DOWN16, and the graph-optimize marking passes.
- The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel),
  the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output
  matmul, the MoE down fold, and the weighted-down reduction.
- The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize
  predicate and in the direct GDN conv.
- Meta/scheduler/allocator: the split-state refusals for a straddling split,
  the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory
  generations so a graph is recaptured when the pool / FA staging / H2D ring
  memory it captured is freed -- including the slab work-boundary shrink of
  issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy
  instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED).
- bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16
  instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu.

Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED /
GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values
rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the
next getenv() call overwrites, so a cached pointer is unsafe on Windows.

Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve
lives in src/ (not linked against the CUDA common.cuh), so it uses a local
static instead of the CUDA helper.

Split note (r109): this commit plus block 11 carries exactly the tree the old
block 10 carried -- the net set is unchanged.  What moved to block 11 is the
qwen4exp model graph, the QSA/indexer ops and their kernels, the
hyper-connection ops, the managed lazy reader and the keys-only indexer cache,
i.e. everything that exists only because of that architecture.  The pieces of
the old block 10 that exist for qwen4exp but are implemented inside a general
kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp
weighted-down reduction, the PLE conv fusion) stay here with the TU that owns
them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved
to block 11 with the matchers they call.

Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers
block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`.  With HIP on Windows (clang + the
MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an
inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's
version win overload resolution is not part of the mangled name), so a translation unit that
instantiates both fails to codegen with "definition with same mangled name".  Behaviour is unchanged.

Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces.  The fused GLU -> Q8_1 site's
key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the
root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel
and the GLU write -- validate their sources with q8_1_src_range_ok() before launching.  From PR ggml-org#218 (@slavap);
the rule and the validation are recorded with block 08.

Co-authored-by: Slava P. <[email protected]>
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 27, 2026
Also adds mmf32, the F32 counterpart of MMB: the
shapes MMB cannot take -- non-quantized (F32) weights with more than 16 token columns -- currently fall
through ggml_cuda_mul_mat_cublas() to rocBLAS, which dispatches to hipBLASLt.

Two reasons to own that path:
  * correctness: hipBLASLt picks its solution per process start from a heap-ordered container, so the prefill
    arithmetic (and therefore the logits) changes between fresh runs -- GREEDY-PURITY.md §44, TODO ggml-org#75: 3
    logit classes in 8 starts on 35B-A3B, 3 in 18 on gemma4;
  * speed: the solution the heuristic lands on is the slowest in the pool for these shapes (0.13-0.19 ms vs
    0.046 ms for a well-chosen one).

mmf32 is a plain SIMT tiled GEMM (RDNA has no F32 MMA form: amd_mfma_available is CDNA-only,
amd_wmma_available is f16/bf16).  32 output rows per block, a 4x8 thread sub-tile, BN=256 for m <= 64 (the
GDN ssm_alpha/ssm_beta projections) and 64 above it (the MoE routers), and the k range split into contiguous
chunks summed in increasing z -- a fixed reduction tree, no atomics, so a run is bit-stable by construction.
No approximation: an F32 FMA accumulation in a pinned order.

Scope: F32 weights only, m <= 256, 17 <= n <= 65536, 256 <= k <= 8192, ldc == m; every other mul_mat keeps the
rocBLAS call unchanged (BF16/f16 prefill -- Flash-Next -- is untouched, as is its hipBLASLt advantage; a
full-F32 model's FFN GEMMs, m >> 256, stay on rocBLAS: a recorded limitation).

Measured on gfx1201 (35B-A3B Q4_K_M, one GPU): deterministic -- one logits class in 12/12 fresh starts (6/6 at
2 GPU -sm tensor), --chunks 8 dumps byte-identical; +4.2 % pp512 / +4.1 % pp2048, decode flat (3 interleaved
llama-bench visits); kernel 0.032 ms vs 0.046 ms for the best hipBLASLt class on 32x512x2048.  Correctness:
16-shape oracle NMSE ~1e-13, and 11x closer to the CPU reference than the rocBLAS path on the
test-backend-ops cases it intercepts.  Purity: judged with the family-switch gate at a confident point
(in-domain corpus, base PPL 1.43) at 0.014646 / 98.045 % against a same-kernel control of 0.018100 / 97.808 %.

Default-on for RDNA4 (GGML_CUDA_MMF32=0 disables; opt-in on RDNA3/RDNA3_5 until those boxes run the same
determinism + bench pair).  GGML_CUDA_MMF32_LOG prints the resolved plans (diagnostic only).

Amended (r132): the per-arch dispatch is keyed to the device the kernel runs on, not the primary.  mmb_enabled,
mmb_cfg, mmb_cfg_dump_once, mmb_dense_flag, mmb_wtype_mask and mmb_dense_tmask read
ggml_cuda_info().devices[ggml_cuda_get_device()].cc, and mmb_cfg() takes one magic static per architecture class
(mmb_arch_defaults() only discriminates RDNA4 and RDNA3_0, so every cc that reaches the fallback shares the same
pre-S11 table).  ggml_backend_cuda_graph_optimize() now selects its own context's device before it consults those
predicates, so the MMB marking half agrees with the launch path under the Meta backend, where the pass is
forwarded per child from meta graph_compute and the current device is still the previously computed one.

Reported in PR ggml-org#218 (@slavap): on a mixed-arch box (gfx1100 primary + gfx1030 secondary) the policy froze at the
primary's, so the RDNA2 card ran RDNA3-tuned MMB kernels -- byte-exact zero output-projection logits (PPL ==
vocab) or garbled tail layers, depending on where the output projection sat.  On a single-arch box this is
bit-for-bit the previous behaviour (validated here on 3x gfx1201: 12/12 same-seed configs byte-identical,
prefill-logit KLD 0.000000 on both recorded points, no GPU faults).

Co-authored-by: Slava P. <[email protected]>

Fold (r134, issue ggml-org#224): the width probe's n_ctx is now the prefill length plus the decode
width instead of a fixed 4096, and a purity run must pass P >= 4096.  The RDNA4 band's
64-column block (query widths 5..8) is only reachable above the launcher's KV-length gate
(K->ne[1] >= 4096), and K->ne[1] is the context's used length, so the P=256 default never
reached that block: the probe reported PASS on every arm while widths 5..8 ran a geometry
that was not bit-identical to widths 1..4.  At P=4096 the r126 geometry fails it
(width_purity=FAIL, worst maxdiff 0.199764 on q8_0 K/V, row-0 hash split between W=4 and
W=5), and the shipped band geometry passes with maxdiff 0.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 27, 2026
…oE + old-15 PR57/63)

Merged from the planned 08 fused-prefill and 09 fused-moe: the two are not
hunk-separable (the fusions and the mmvq dispatch share ggml_cuda.cu try_fuse,
mmvq.cu, norm.cu, common.cuh and the ggml_cuda_mm_fusion_args plumbing), and the
old-08-only fusion set was not correct (fusion-on greedy text differed from
fusion-off).

Contents:
- old-08 fusions: gdn-conv, ple-conv, norm-gated, topk-moe, the norm/unary/
  getrows/argsort kernels, the CPU references and the try_fuse arms.
- old-13: fused MoE gate+up+GLU MMQ, the mmvq short-K item-split/ksplit, the
  routed-compact MMQ (mmq.cuh/mmq-config), MWR, the mmq gate instances.
- old-15 PR ggml-org#57/ggml-org#63: the mmvq multi-row/row-loop decode (GGML_MMVQ_RDNA4_
  DECODE_GRID, nrows_loop, the lf_nval halving reduction), ssm_gate_beta/
  ssm_conv_l2_gatebeta, the norm rms_norm_q8_1 refactor and quantize_mmq_q8_1_glu.

The MoE-cache-aware arms (moe_cache_get_cold/redirect, the B1 stand-down) and
the qwen4exp/HC arms are deliberately NOT here -- they belong to the slab-moe and
qwen4exp blocks, and their absence leaves the resident-only path (bit-identical).

Gates: build all OK; fusion on == off (4B greedy text); test-logits-width-probe
width_purity PASS; MUL_MAT 2444/2444.

Amended (r132): the Q8_1 quantize cache is keyed by the ROOT tensor's identity but filled from the (possibly
offset) view's pointer, so an offset view stored its rows under the root identity and a later op with the same
root and canonical row layout could hit them.  Every key walk that reaches the cache now stops at the first
pointer change (this block: the four mmvq sites and the unary mul_q8_1 site; block 10 adds its own GLU site), so
offset-free views keep the shared root entry and an offset view gets its own arena entry.  A new
q8_1_src_range_ok() validates the source read range against the root buffer's allocation before every
quantize_row_q8_1_cuda / fused gated-q8_1 launch, so a stale source pointer (a compute buffer reallocated under a
still-matching cache entry) aborts loudly with the layout logged instead of faulting with
HSA_STATUS_ERROR_MEMORY_APERTURE_VIOLATION or silently reading reused memory.

Reported in PR ggml-org#218 (@slavap), whose V620 hit the fault on decode.  Not reachable on the maintainer's model set
(0 offset-view keys in 14336-60416 key walks per config across 7 configs, probed on gfx1201), so this is a
correctness fix for configurations we do not run: 12/12 same-seed configs byte-identical, MTP acceptance
identical (1859/3416, 1420/1710, 2171/2483, 372/375 on the four axes), prefill-logit KLD 0.000000.

Co-authored-by: Slava P. <[email protected]>
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 27, 2026
…rastructure)

The infrastructure half of the old block 10.  qwen4exp, QSA and the
hyper-connection ops now live in their own block (11); this block is what they
are built on, and it no longer references them.

Contents:

- The movable-boundary slab and its arena (ggml-cuda-slab.cu,
  ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM
  reserve per device split by a movable boundary -- compute below, MoE arena
  above, no HIP call at runtime.  Plus the narrow-band learning, the wide-phase
  auxiliary region, pool-wide routing, and the slab transient absorption.
- The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of
  ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it.
- The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the
  r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU
  split's output, which the next ubatch rewrites), default-on, and the per-origin
  (per host thread) ordering state of issue ggml-org#201.
- Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT)
  matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes
  folded into the rope + FWHT kernel, and the paired GDN q/k norms.
- GDN / attention-gate decode fusions: the BF16 alpha/beta pair with
  softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108
  multi-sequence fix and its model-free regression test), the q/k norm pair in
  the direct conv kernel, the attention gate's row-strided view read in place by
  the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and
  GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots).
- MMB and the HC16 BF16 streams: the per-context MMB state (two contexts
  interleaving must not share the activation cache or the marks), the BF16
  activation copies, DOWN16, and the graph-optimize marking passes.
- The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel),
  the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output
  matmul, the MoE down fold, and the weighted-down reduction.
- The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize
  predicate and in the direct GDN conv.
- Meta/scheduler/allocator: the split-state refusals for a straddling split,
  the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory
  generations so a graph is recaptured when the pool / FA staging / H2D ring
  memory it captured is freed -- including the slab work-boundary shrink of
  issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy
  instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED).
- bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16
  instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu.

Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED /
GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values
rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the
next getenv() call overwrites, so a cached pointer is unsafe on Windows.

Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve
lives in src/ (not linked against the CUDA common.cuh), so it uses a local
static instead of the CUDA helper.

Split note (r109): this commit plus block 11 carries exactly the tree the old
block 10 carried -- the net set is unchanged.  What moved to block 11 is the
qwen4exp model graph, the QSA/indexer ops and their kernels, the
hyper-connection ops, the managed lazy reader and the keys-only indexer cache,
i.e. everything that exists only because of that architecture.  The pieces of
the old block 10 that exist for qwen4exp but are implemented inside a general
kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp
weighted-down reduction, the PLE conv fusion) stay here with the TU that owns
them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved
to block 11 with the matchers they call.

Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers
block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`.  With HIP on Windows (clang + the
MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an
inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's
version win overload resolution is not part of the mangled name), so a translation unit that
instantiates both fails to codegen with "definition with same mangled name".  Behaviour is unchanged.

Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces.  The fused GLU -> Q8_1 site's
key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the
root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel
and the GLU write -- validate their sources with q8_1_src_range_ok() before launching.  From PR ggml-org#218 (@slavap);
the rule and the validation are recorded with block 08.

Co-authored-by: Slava P. <[email protected]>
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 27, 2026
Also adds mmf32, the F32 counterpart of MMB: the
shapes MMB cannot take -- non-quantized (F32) weights with more than 16 token columns -- currently fall
through ggml_cuda_mul_mat_cublas() to rocBLAS, which dispatches to hipBLASLt.

Two reasons to own that path:
  * correctness: hipBLASLt picks its solution per process start from a heap-ordered container, so the prefill
    arithmetic (and therefore the logits) changes between fresh runs -- GREEDY-PURITY.md §44, TODO ggml-org#75: 3
    logit classes in 8 starts on 35B-A3B, 3 in 18 on gemma4;
  * speed: the solution the heuristic lands on is the slowest in the pool for these shapes (0.13-0.19 ms vs
    0.046 ms for a well-chosen one).

mmf32 is a plain SIMT tiled GEMM (RDNA has no F32 MMA form: amd_mfma_available is CDNA-only,
amd_wmma_available is f16/bf16).  32 output rows per block, a 4x8 thread sub-tile, BN=256 for m <= 64 (the
GDN ssm_alpha/ssm_beta projections) and 64 above it (the MoE routers), and the k range split into contiguous
chunks summed in increasing z -- a fixed reduction tree, no atomics, so a run is bit-stable by construction.
No approximation: an F32 FMA accumulation in a pinned order.

Scope: F32 weights only, m <= 256, 17 <= n <= 65536, 256 <= k <= 8192, ldc == m; every other mul_mat keeps the
rocBLAS call unchanged (BF16/f16 prefill -- Flash-Next -- is untouched, as is its hipBLASLt advantage; a
full-F32 model's FFN GEMMs, m >> 256, stay on rocBLAS: a recorded limitation).

Measured on gfx1201 (35B-A3B Q4_K_M, one GPU): deterministic -- one logits class in 12/12 fresh starts (6/6 at
2 GPU -sm tensor), --chunks 8 dumps byte-identical; +4.2 % pp512 / +4.1 % pp2048, decode flat (3 interleaved
llama-bench visits); kernel 0.032 ms vs 0.046 ms for the best hipBLASLt class on 32x512x2048.  Correctness:
16-shape oracle NMSE ~1e-13, and 11x closer to the CPU reference than the rocBLAS path on the
test-backend-ops cases it intercepts.  Purity: judged with the family-switch gate at a confident point
(in-domain corpus, base PPL 1.43) at 0.014646 / 98.045 % against a same-kernel control of 0.018100 / 97.808 %.

Default-on for RDNA4 (GGML_CUDA_MMF32=0 disables; opt-in on RDNA3/RDNA3_5 until those boxes run the same
determinism + bench pair).  GGML_CUDA_MMF32_LOG prints the resolved plans (diagnostic only).

Amended (r132): the per-arch dispatch is keyed to the device the kernel runs on, not the primary.  mmb_enabled,
mmb_cfg, mmb_cfg_dump_once, mmb_dense_flag, mmb_wtype_mask and mmb_dense_tmask read
ggml_cuda_info().devices[ggml_cuda_get_device()].cc, and mmb_cfg() takes one magic static per architecture class
(mmb_arch_defaults() only discriminates RDNA4 and RDNA3_0, so every cc that reaches the fallback shares the same
pre-S11 table).  ggml_backend_cuda_graph_optimize() now selects its own context's device before it consults those
predicates, so the MMB marking half agrees with the launch path under the Meta backend, where the pass is
forwarded per child from meta graph_compute and the current device is still the previously computed one.

Reported in PR ggml-org#218 (@slavap): on a mixed-arch box (gfx1100 primary + gfx1030 secondary) the policy froze at the
primary's, so the RDNA2 card ran RDNA3-tuned MMB kernels -- byte-exact zero output-projection logits (PPL ==
vocab) or garbled tail layers, depending on where the output projection sat.  On a single-arch box this is
bit-for-bit the previous behaviour (validated here on 3x gfx1201: 12/12 same-seed configs byte-identical,
prefill-logit KLD 0.000000 on both recorded points, no GPU faults).

Co-authored-by: Slava P. <[email protected]>

Fold (r134, issue ggml-org#224): the width probe's n_ctx is now the prefill length plus the decode
width instead of a fixed 4096, and a purity run must pass P >= 4096.  The RDNA4 band's
64-column block (query widths 5..8) is only reachable above the launcher's KV-length gate
(K->ne[1] >= 4096), and K->ne[1] is the context's used length, so the P=256 default never
reached that block: the probe reported PASS on every arm while widths 5..8 ran a geometry
that was not bit-identical to widths 1..4.  At P=4096 the r126 geometry fails it
(width_purity=FAIL, worst maxdiff 0.199764 on q8_0 K/V, row-0 hash split between W=4 and
W=5), and the shipped band geometry passes with maxdiff 0.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 27, 2026
…oE + old-15 PR57/63)

Merged from the planned 08 fused-prefill and 09 fused-moe: the two are not
hunk-separable (the fusions and the mmvq dispatch share ggml_cuda.cu try_fuse,
mmvq.cu, norm.cu, common.cuh and the ggml_cuda_mm_fusion_args plumbing), and the
old-08-only fusion set was not correct (fusion-on greedy text differed from
fusion-off).

Contents:
- old-08 fusions: gdn-conv, ple-conv, norm-gated, topk-moe, the norm/unary/
  getrows/argsort kernels, the CPU references and the try_fuse arms.
- old-13: fused MoE gate+up+GLU MMQ, the mmvq short-K item-split/ksplit, the
  routed-compact MMQ (mmq.cuh/mmq-config), MWR, the mmq gate instances.
- old-15 PR ggml-org#57/ggml-org#63: the mmvq multi-row/row-loop decode (GGML_MMVQ_RDNA4_
  DECODE_GRID, nrows_loop, the lf_nval halving reduction), ssm_gate_beta/
  ssm_conv_l2_gatebeta, the norm rms_norm_q8_1 refactor and quantize_mmq_q8_1_glu.

The MoE-cache-aware arms (moe_cache_get_cold/redirect, the B1 stand-down) and
the qwen4exp/HC arms are deliberately NOT here -- they belong to the slab-moe and
qwen4exp blocks, and their absence leaves the resident-only path (bit-identical).

Gates: build all OK; fusion on == off (4B greedy text); test-logits-width-probe
width_purity PASS; MUL_MAT 2444/2444.

Amended (r132): the Q8_1 quantize cache is keyed by the ROOT tensor's identity but filled from the (possibly
offset) view's pointer, so an offset view stored its rows under the root identity and a later op with the same
root and canonical row layout could hit them.  Every key walk that reaches the cache now stops at the first
pointer change (this block: the four mmvq sites and the unary mul_q8_1 site; block 10 adds its own GLU site), so
offset-free views keep the shared root entry and an offset view gets its own arena entry.  A new
q8_1_src_range_ok() validates the source read range against the root buffer's allocation before every
quantize_row_q8_1_cuda / fused gated-q8_1 launch, so a stale source pointer (a compute buffer reallocated under a
still-matching cache entry) aborts loudly with the layout logged instead of faulting with
HSA_STATUS_ERROR_MEMORY_APERTURE_VIOLATION or silently reading reused memory.

Reported in PR ggml-org#218 (@slavap), whose V620 hit the fault on decode.  Not reachable on the maintainer's model set
(0 offset-view keys in 14336-60416 key walks per config across 7 configs, probed on gfx1201), so this is a
correctness fix for configurations we do not run: 12/12 same-seed configs byte-identical, MTP acceptance
identical (1859/3416, 1420/1710, 2171/2483, 372/375 on the four axes), prefill-logit KLD 0.000000.

Co-authored-by: Slava P. <[email protected]>
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 27, 2026
…rastructure)

The infrastructure half of the old block 10.  qwen4exp, QSA and the
hyper-connection ops now live in their own block (11); this block is what they
are built on, and it no longer references them.

Contents:

- The movable-boundary slab and its arena (ggml-cuda-slab.cu,
  ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM
  reserve per device split by a movable boundary -- compute below, MoE arena
  above, no HIP call at runtime.  Plus the narrow-band learning, the wide-phase
  auxiliary region, pool-wide routing, and the slab transient absorption.
- The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of
  ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it.
- The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the
  r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU
  split's output, which the next ubatch rewrites), default-on, and the per-origin
  (per host thread) ordering state of issue ggml-org#201.
- Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT)
  matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes
  folded into the rope + FWHT kernel, and the paired GDN q/k norms.
- GDN / attention-gate decode fusions: the BF16 alpha/beta pair with
  softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108
  multi-sequence fix and its model-free regression test), the q/k norm pair in
  the direct conv kernel, the attention gate's row-strided view read in place by
  the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and
  GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots).
- MMB and the HC16 BF16 streams: the per-context MMB state (two contexts
  interleaving must not share the activation cache or the marks), the BF16
  activation copies, DOWN16, and the graph-optimize marking passes.
- The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel),
  the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output
  matmul, the MoE down fold, and the weighted-down reduction.
- The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize
  predicate and in the direct GDN conv.
- Meta/scheduler/allocator: the split-state refusals for a straddling split,
  the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory
  generations so a graph is recaptured when the pool / FA staging / H2D ring
  memory it captured is freed -- including the slab work-boundary shrink of
  issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy
  instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED).
- bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16
  instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu.

Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED /
GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values
rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the
next getenv() call overwrites, so a cached pointer is unsafe on Windows.

Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve
lives in src/ (not linked against the CUDA common.cuh), so it uses a local
static instead of the CUDA helper.

Split note (r109): this commit plus block 11 carries exactly the tree the old
block 10 carried -- the net set is unchanged.  What moved to block 11 is the
qwen4exp model graph, the QSA/indexer ops and their kernels, the
hyper-connection ops, the managed lazy reader and the keys-only indexer cache,
i.e. everything that exists only because of that architecture.  The pieces of
the old block 10 that exist for qwen4exp but are implemented inside a general
kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp
weighted-down reduction, the PLE conv fusion) stay here with the TU that owns
them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved
to block 11 with the matchers they call.

Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers
block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`.  With HIP on Windows (clang + the
MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an
inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's
version win overload resolution is not part of the mangled name), so a translation unit that
instantiates both fails to codegen with "definition with same mangled name".  Behaviour is unchanged.

Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces.  The fused GLU -> Q8_1 site's
key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the
root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel
and the GLU write -- validate their sources with q8_1_src_range_ok() before launching.  From PR ggml-org#218 (@slavap);
the rule and the validation are recorded with block 08.

Co-authored-by: Slava P. <[email protected]>
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 27, 2026
Also adds mmf32, the F32 counterpart of MMB: the
shapes MMB cannot take -- non-quantized (F32) weights with more than 16 token columns -- currently fall
through ggml_cuda_mul_mat_cublas() to rocBLAS, which dispatches to hipBLASLt.

Two reasons to own that path:
  * correctness: hipBLASLt picks its solution per process start from a heap-ordered container, so the prefill
    arithmetic (and therefore the logits) changes between fresh runs -- GREEDY-PURITY.md §44, TODO ggml-org#75: 3
    logit classes in 8 starts on 35B-A3B, 3 in 18 on gemma4;
  * speed: the solution the heuristic lands on is the slowest in the pool for these shapes (0.13-0.19 ms vs
    0.046 ms for a well-chosen one).

mmf32 is a plain SIMT tiled GEMM (RDNA has no F32 MMA form: amd_mfma_available is CDNA-only,
amd_wmma_available is f16/bf16).  32 output rows per block, a 4x8 thread sub-tile, BN=256 for m <= 64 (the
GDN ssm_alpha/ssm_beta projections) and 64 above it (the MoE routers), and the k range split into contiguous
chunks summed in increasing z -- a fixed reduction tree, no atomics, so a run is bit-stable by construction.
No approximation: an F32 FMA accumulation in a pinned order.

Scope: F32 weights only, m <= 256, 17 <= n <= 65536, 256 <= k <= 8192, ldc == m; every other mul_mat keeps the
rocBLAS call unchanged (BF16/f16 prefill -- Flash-Next -- is untouched, as is its hipBLASLt advantage; a
full-F32 model's FFN GEMMs, m >> 256, stay on rocBLAS: a recorded limitation).

Measured on gfx1201 (35B-A3B Q4_K_M, one GPU): deterministic -- one logits class in 12/12 fresh starts (6/6 at
2 GPU -sm tensor), --chunks 8 dumps byte-identical; +4.2 % pp512 / +4.1 % pp2048, decode flat (3 interleaved
llama-bench visits); kernel 0.032 ms vs 0.046 ms for the best hipBLASLt class on 32x512x2048.  Correctness:
16-shape oracle NMSE ~1e-13, and 11x closer to the CPU reference than the rocBLAS path on the
test-backend-ops cases it intercepts.  Purity: judged with the family-switch gate at a confident point
(in-domain corpus, base PPL 1.43) at 0.014646 / 98.045 % against a same-kernel control of 0.018100 / 97.808 %.

Default-on for RDNA4 (GGML_CUDA_MMF32=0 disables; opt-in on RDNA3/RDNA3_5 until those boxes run the same
determinism + bench pair).  GGML_CUDA_MMF32_LOG prints the resolved plans (diagnostic only).

Amended (r132): the per-arch dispatch is keyed to the device the kernel runs on, not the primary.  mmb_enabled,
mmb_cfg, mmb_cfg_dump_once, mmb_dense_flag, mmb_wtype_mask and mmb_dense_tmask read
ggml_cuda_info().devices[ggml_cuda_get_device()].cc, and mmb_cfg() takes one magic static per architecture class
(mmb_arch_defaults() only discriminates RDNA4 and RDNA3_0, so every cc that reaches the fallback shares the same
pre-S11 table).  ggml_backend_cuda_graph_optimize() now selects its own context's device before it consults those
predicates, so the MMB marking half agrees with the launch path under the Meta backend, where the pass is
forwarded per child from meta graph_compute and the current device is still the previously computed one.

Reported in PR ggml-org#218 (@slavap): on a mixed-arch box (gfx1100 primary + gfx1030 secondary) the policy froze at the
primary's, so the RDNA2 card ran RDNA3-tuned MMB kernels -- byte-exact zero output-projection logits (PPL ==
vocab) or garbled tail layers, depending on where the output projection sat.  On a single-arch box this is
bit-for-bit the previous behaviour (validated here on 3x gfx1201: 12/12 same-seed configs byte-identical,
prefill-logit KLD 0.000000 on both recorded points, no GPU faults).

Co-authored-by: Slava P. <[email protected]>

Fold (r134, issue ggml-org#224): the width probe's n_ctx is now the prefill length plus the decode
width instead of a fixed 4096, and a purity run must pass P >= 4096.  The RDNA4 band's
64-column block (query widths 5..8) is only reachable above the launcher's KV-length gate
(K->ne[1] >= 4096), and K->ne[1] is the context's used length, so the P=256 default never
reached that block: the probe reported PASS on every arm while widths 5..8 ran a geometry
that was not bit-identical to widths 1..4.  At P=4096 the r126 geometry fails it
(width_purity=FAIL, worst maxdiff 0.199764 on q8_0 K/V, row-0 hash split between W=4 and
W=5), and the shipped band geometry passes with maxdiff 0.
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 27, 2026
…oE + old-15 PR57/63)

Merged from the planned 08 fused-prefill and 09 fused-moe: the two are not
hunk-separable (the fusions and the mmvq dispatch share ggml_cuda.cu try_fuse,
mmvq.cu, norm.cu, common.cuh and the ggml_cuda_mm_fusion_args plumbing), and the
old-08-only fusion set was not correct (fusion-on greedy text differed from
fusion-off).

Contents:
- old-08 fusions: gdn-conv, ple-conv, norm-gated, topk-moe, the norm/unary/
  getrows/argsort kernels, the CPU references and the try_fuse arms.
- old-13: fused MoE gate+up+GLU MMQ, the mmvq short-K item-split/ksplit, the
  routed-compact MMQ (mmq.cuh/mmq-config), MWR, the mmq gate instances.
- old-15 PR ggml-org#57/ggml-org#63: the mmvq multi-row/row-loop decode (GGML_MMVQ_RDNA4_
  DECODE_GRID, nrows_loop, the lf_nval halving reduction), ssm_gate_beta/
  ssm_conv_l2_gatebeta, the norm rms_norm_q8_1 refactor and quantize_mmq_q8_1_glu.

The MoE-cache-aware arms (moe_cache_get_cold/redirect, the B1 stand-down) and
the qwen4exp/HC arms are deliberately NOT here -- they belong to the slab-moe and
qwen4exp blocks, and their absence leaves the resident-only path (bit-identical).

Gates: build all OK; fusion on == off (4B greedy text); test-logits-width-probe
width_purity PASS; MUL_MAT 2444/2444.

Amended (r132): the Q8_1 quantize cache is keyed by the ROOT tensor's identity but filled from the (possibly
offset) view's pointer, so an offset view stored its rows under the root identity and a later op with the same
root and canonical row layout could hit them.  Every key walk that reaches the cache now stops at the first
pointer change (this block: the four mmvq sites and the unary mul_q8_1 site; block 10 adds its own GLU site), so
offset-free views keep the shared root entry and an offset view gets its own arena entry.  A new
q8_1_src_range_ok() validates the source read range against the root buffer's allocation before every
quantize_row_q8_1_cuda / fused gated-q8_1 launch, so a stale source pointer (a compute buffer reallocated under a
still-matching cache entry) aborts loudly with the layout logged instead of faulting with
HSA_STATUS_ERROR_MEMORY_APERTURE_VIOLATION or silently reading reused memory.

Reported in PR ggml-org#218 (@slavap), whose V620 hit the fault on decode.  Not reachable on the maintainer's model set
(0 offset-view keys in 14336-60416 key walks per config across 7 configs, probed on gfx1201), so this is a
correctness fix for configurations we do not run: 12/12 same-seed configs byte-identical, MTP acceptance
identical (1859/3416, 1420/1710, 2171/2483, 372/375 on the four axes), prefill-logit KLD 0.000000.

Co-authored-by: Slava P. <[email protected]>
stew675 pushed a commit to stew675/llama.cpp that referenced this pull request Oct 27, 2026
…rastructure)

The infrastructure half of the old block 10.  qwen4exp, QSA and the
hyper-connection ops now live in their own block (11); this block is what they
are built on, and it no longer references them.

Contents:

- The movable-boundary slab and its arena (ggml-cuda-slab.cu,
  ggml-cuda-arena.cu, ggml-cuda-vmm.h, ggml-cuda-moe-cache-hooks.cu): one VMM
  reserve per device split by a movable boundary -- compute below, MoE arena
  above, no HIP call at runtime.  Plus the narrow-band learning, the wide-phase
  auxiliary region, pool-wide routing, and the slab transient absorption.
- The fusion dispatcher (ggml-cuda-try-fuse.cu): the matcher arms moved out of
  ggml-cuda.cu, with every arm implemented inside the kernel TU that owns it.
- The async graph-input ring: batched uploads + lazy done event (PR ggml-org#182), the
  r90 snapshot fix (the scheduler's set_tensor_async path is used for a CPU
  split's output, which the next ubatch rewrites), default-on, and the per-origin
  (per host thread) ordering state of issue ggml-org#201.
- Rope/FWHT fusions: M-ROPE and IMROPE in the RMS_NORM + MUL + ROPE (+ FWHT)
  matcher, BF16 SET_ROWS kept off the 5-op fusion, the q8_0 K/V cache writes
  folded into the rope + FWHT kernel, and the paired GDN q/k norms.
- GDN / attention-gate decode fusions: the BF16 alpha/beta pair with
  softplus(alpha + dt) * a in one mul_mat_vec_f launch (with the r108
  multi-sequence fix and its model-free regression test), the q/k norm pair in
  the direct conv kernel, the attention gate's row-strided view read in place by
  the gate -> Q8_1 kernel, the GDN output norm inside the gate kernel, and
  GGML_CUDA_GDN_TAIL (the sequential tail that writes the rollback snapshots).
- MMB and the HC16 BF16 streams: the per-context MMB state (two contexts
  interleaving must not share the activation cache or the marks), the BF16
  activation copies, DOWN16, and the graph-optimize marking passes.
- The MoE/MMQ decode fusions: mmvq-moe (the dedicated MoE multi-token kernel),
  the gate+up pair fold, silu(gate)*up into the mmq quantize, the dual-output
  matmul, the MoE down fold, and the weighted-down reduction.
- The verify-band arch extension: RDNA3_0 joins RDNA4 in the Q8_1 pre-quantize
  predicate and in the direct GDN conv.
- Meta/scheduler/allocator: the split-state refusals for a straddling split,
  the two-pass graph-optimize protocol (allocs_only / marks_only), graph-memory
  generations so a graph is recaptured when the pool / FA staging / H2D ring
  memory it captured is freed -- including the slab work-boundary shrink of
  issue ggml-org#187 -- the KV prefill pad (LLAMA_KV_N_PAD_PREFILL), and the FA accuracy
  instrument (LLAMA_TEST_OP_NMSE / LLAMA_TEST_SEED).
- bf16 RoPE destinations (TODO ggml-org#83): the missing NORMAL/NEOX bf16
  instantiations, so -ctk bf16 -ctv bf16 prefill does not abort in rope.cu.

Env-read hygiene (no behaviour change): resolve GGML_CUDA_GDN_CHUNKED /
GGML_CUDA_GDN_CHUNKED_BF16 and the GDN_DBG_SKIP_* diagnostics once into values
rather than caching the getenv() pointer: the MSVC CRT returns a buffer that the
next getenv() call overwrites, so a cached pointer is unsafe on Windows.

Build fix: the GGML_CUDA_WORK_ALLOC_DEBUG read in llama_context::graph_reserve
lives in src/ (not linked against the CUDA common.cuh), so it uses a local
static instead of the CUDA helper.

Split note (r109): this commit plus block 11 carries exactly the tree the old
block 10 carried -- the net set is unchanged.  What moved to block 11 is the
qwen4exp model graph, the QSA/indexer ops and their kernels, the
hyper-connection ops, the managed lazy reader and the keys-only indexer cache,
i.e. everything that exists only because of that architecture.  The pieces of
the old block 10 that exist for qwen4exp but are implemented inside a general
kernel TU (the GDN gate/beta fusion, the HC16 MMB BF16 streams, the qwen4exp
weighted-down reduction, the PLE conv fusion) stay here with the TU that owns
them; the HC_BLK16/RES16 marking pass and the indexer relu-sum alloc-dep moved
to block 11 with the matchers they call.

Windows HIP build (issue ggml-org#217): the tables-registration slack guard uses the int64_t min/max helpers
block 09 defines instead of `std::min<int64_t>`/`std::max<int64_t>`.  With HIP on Windows (clang + the
MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an
inline `std::min<long long>` (`int64_t` is `__int64` there, and the `enable_if` that makes clang's
version win overload resolution is not part of the mangled name), so a translation unit that
instantiates both fails to codegen with "definition with same mangled name".  Behaviour is unchanged.

Amended (r132): the block-10 arms of the Q8_1 cache fix that block 08 introduces.  The fused GLU -> Q8_1 site's
key walk stops at the first pointer change (the fused write is keyed by the matmul's src1, and must not take the
root's entry for an offset view), and both of this block's gated-q8_1 launch arms -- the fused norm+gate kernel
and the GLU write -- validate their sources with q8_1_src_range_ok() before launching.  From PR ggml-org#218 (@slavap);
the rule and the validation are recorded with block 08.

Co-authored-by: Slava P. <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working build Compilation issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants