Skip to content

kv: verify the zero padding of the KV cache, and repair it (engine #528) - #155

Merged
bong-water-water-bong merged 1 commit into
1bit/hrx-vulkan-patchedfrom
1bit/528-pad-nan
Oct 30, 2026
Merged

bong-water-water-bong merged 1 commit into
1bit/hrx-vulkan-patchedfrom
1bit/528-pad-nan

Conversation

@bong-water-water-bong

@bong-water-water-bong bong-water-water-bong commented Oct 30, 2026 •

Copy link
Copy Markdown

Rewritten per the orchestrator's decision on ggml-org#528 (allocator side, no inference-path cost), and revised after the two reviews: the wrong CPU claim, the "load-time only" cost statement, the dropped return value, the dead accessor and the untested sampler are all addressed below.

The invariant

Every attention kernel masks the columns past the sequence end with -INFINITY and relies on those columns holding zeros: -infinity + NaN is NaN and 0 * NaN is NaN, so one padded column with garbage in it turns a whole output row into NaN. llama.cpp clears the KV buffer when it allocates it ("allocate tensors and initialize the buffers to avoid NaNs in the padding"), but on HRX that clear is best-effort — ggml-hrx.cpp buffer_clear logs a failed fill and carries on — and a clear that did not take leaves whatever the device memory held before.

Fix

src/llama-kv-zero.cpp (our file, full header) verifies the padding instead of trusting the clear, at allocation and on every reset (src/llama-kv-cache.cpp, marked [1bit]):

  • Fast path: three 4 KiB windows in each of three tensors spread over the buffer — the clear is one fill submit per buffer, so a spread sample says as much as scanning it, and it keeps the cost at a handful of readbacks because a server resets the cache in request handling, not only at load.
  • When the sample is not zero: the buffer is filled through ggml_backend_tensor_set (fails loudly) and verified in full, then logged as a repair.
  • A repair that still leaves non-zero padding no longer continues silently: allocation throws (the precedent three lines above it), a reset aborts — serving NaN is worse than stopping, and the existing NaN-logits guard (common/sampling.cpp) aborts for the same reason.
  • ONEBIT_KV_ZERO=0 skips the verification, for measuring it. Default on.

Cost, measured (the review was right that my first number was measuring the wrong thing)

llama-bench never resets mid-run, so it cannot see this. Measured directly instead, one call on the shipped path, HRX0, 1152 MiB KV cache (56 tensors):

llama_kv_zero_fill: cost verified zero (HRX0, 1152.01 MiB, 3 of 56 tensors sampled)
verify: 0.202 ms per call (20 calls)

0.2 ms per reset. In a served run the cache is reset ~3-4 times per 25 requests (it is reset when a slot's cache is invalidated, not on every request), which is why request time does not separate the arms; at one reset per request the overhead would be 0.2 ms against a ~60 ms request. The first body's "no change beyond the box's noise" came from llama-bench and is withdrawn.

End-to-end reproduction of the incident, and the fix against it

The incident's condition is a KV clear that does not take, reproduced with a local uncommitted switch that makes buffer_clear leave 0x7E (f16 NaN) in buffers over 64 MiB, Qwen3-4B --parallel 4 -kvu on HRX0:

arm result
clear only, no verification (ONEBIT_KV_ZERO=0) 32-64 × E common_sampler_sample: HRX returned NaN logits: count=151936 of 151936, index range [0..151935], contiguous=yes — the abort in ggml-org#528, line for line
verification on (default) W llama_kv_zero_fill: KV cache was not zero after the clear (HRX0, 12288 bytes non-zero in 3 samples): zero-filling 1152.00 MiB and verifying again → 0 NaN logits, 60/60 requests clean, 4/4 slots

Tests

  • tests/test-kv-zero.cpp (new, 147 lines, CPU only so it runs anywhere): a clean buffer is verified; a poisoned one is repaired; each of the three sampled windows is checked individually (poison the start, middle and end window of the first and last tensor in turn); a 6 MiB buffer exercises the 1 MiB chunking and the second, full verification. ctest -R test-kv-zero, or ./bin/test-kv-zero.
  • tests/test-backend-ops.cpp: alias nodes are now skipped by the support gate — it asked ggml_backend_supports_op about every tensor before allocation, including the k/v views, and ggml-hrx claims only what its dispatcher emits, so every FLASH_ATTN_EXT case was not supported [HRX0, HRX0] and no upstream flash-attention case had ever run on HRX. pad_nan=0 (finite padding, the property this commit guarantees) runs always: OK on HRX0 vs CPU, prefill q=175 over n_kv=256 and decode n_kv=1024 in the model's cache layout — 2/2, and it is the first FA case to run on HRX at all.

The CPU claim in the previous body was wrong — corrected

pad_nan=1..3 are not "a property the CPU reference has for free". Measured at 40c4ccb7 on this box, -b CPU: the batched prefill shape returns NaN for all three poisonings (CPU=nan at index 0), only the decode shape survives; HRX returns NaN in both shapes. So no backend tolerates non-finite padding in the prefill shape — the reference skips a masked key in ggml_compute_forward_flash_attn_ext_f16_one_chunk, but the batched paths multiply and a -INFINITY mask cannot undo a NaN. That is the argument for zeroing the padding rather than for any kernel change, and the cases stay opt-in (GGML_TEST_FA_NAN_PAD=1) with the comment reworded to say exactly this.

Also measured

FLASH_ATTN_EXT matrix on the default path: 419 OK / 0 FAIL. MUL_MAT,MUL_MAT_ID,SOFT_MAX,GET_ROWS,RMS_NORM: 0 FAIL. test-kv-zero: all pass. Qwen3-4B --parallel 4 -kvu + a bench neighbour in one claim, 60 unique requests: 0 NaN, 4/4 slots, 60/60 LRU. KLD Qwen3-0.6B unchanged (this change adds no arithmetic to the model path).

Reproducing on HRX needs two things (from the review, worth knowing)

  1. IREE_HAL_AMDGPU_LIBHSA_PATH must point at TheRock's libhsa-runtime64.so.1; without it hrx_gpu_initialize(0) fails, the backend registers an empty device list and test-backend-ops tests the CPU only while exiting 0.
  2. -b is an exact device name: -b HRX skips every device and still exits 0. Use -b HRX0.

Not in this PR

The mask-select in small_rows_f32.loom / flash_attention_f32_f16_wmma.loom and the matching add-on change (1bit-MONSTER/gpu-kernels#44, closed) were measured at -2..-4 % pp512 and dropped by decision; with the padding guaranteed zero they buy nothing on the serving path.

@bong-water-water-bong bong-water-water-bong changed the title tests + hrx: a masked KV column is selected, not added (engine #528) kv: verify the zero padding of the KV cache, and repair it (engine #528) Oct 30, 2026

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

VERDICT: CHANGES (posted as a comment: GitHub refuses --request-changes on a PR owned by the same account). The fix itself is sound and the default test path is clean; three claims it rests on do not survive re-running them here.

Built and run on this box (cmake -DCMAKE_BUILD_TYPE=Release CPU-only at dd7ecd5, ~/lb/thermal-run.sh, 4 jobs): 331/331, test-backend-ops, llama-cli, llama-server all link.

1. pad_nan=1..3 fail on the CPU backend too, not only on HRX. The body and the comment in tests/test-backend-ops.cpp say those cases test "the stricter property the CPU reference has for free (it never reads a masked key)" and that "with the flag they fail on HRX as documented". On this box they fail on CPU, in the prefill shape, for all three poisonings:

$ GGML_TEST_FA_NAN_PAD=1 ./test-backend-ops test -b CPU -o FLASH_ATTN_EXT -p pad_nan
  ...kv=256,nb=175,mask=1,...,permute=[0,1,2,3],pad_nan=0): OK
  ...kv=1024,nb=1,mask=1,...,permute=[0,2,1,3],pad_nan=0): OK
[FLASH_ATTN_EXT] NaN at index 0 (CPU=nan CPU=-0.003321)   ...kv=256,nb=175,...,permute=[0,1,2,3],pad_nan=1): FAIL
  ...kv=1024,nb=1,...,permute=[0,2,1,3],pad_nan=1): OK
[FLASH_ATTN_EXT] NaN at index 0 (CPU=nan CPU=0.007933)    ...kv=256,nb=175,...,pad_nan=2): FAIL
  ...kv=1024,nb=1,...,pad_nan=2): OK
[FLASH_ATTN_EXT] NaN at index 0 (CPU=nan CPU=-0.027581)   ...kv=256,nb=175,...,pad_nan=3): FAIL
  ...kv=1024,nb=1,...,pad_nan=3): OK
  5/8 tests passed        Failing tests: pad_nan=1, pad_nan=2, pad_nan=3 (kv=256,nb=175)

The decode shape does have the property (nb=1 over kv=1024 passes all three); the batched prefill shape does not — the CPU kernel multiplies by the poisoned column and the -INFINITY on the score cannot undo a NaN. So the comment's premise is wrong for exactly the shape this case was added in, and pad_nan=0 passing tells you nothing about whether a backend reads masked keys. Either fix the sentence (say plainly that neither CPU nor HRX guarantees it, which is why the allocator zeroes the padding) or drop the three cases; as written, anyone who sets GGML_TEST_FA_NAN_PAD=1 in CI gets a red CPU backend.

2. The verification is not load-time only. llama_kv_cache::clear(data=true) calls llama_kv_zero_fill on every reset, and llama-server resets the cache per request. Measured here, llama-server -c 2048 -np 1 -lv 4, three /v1/completions requests:

I llama_kv_zero_fill: KV cache verified zero (CPU, 224.00 MiB) (engine #528)          <- allocation
I llama_kv_zero_fill: KV cache reset verified zero (CPU, 224.00 MiB) (engine #528)    <- request 1
I llama_kv_zero_fill: KV cache reset verified zero (CPU, 224.00 MiB) (engine #528)    <- request 2
I llama_kv_zero_fill: KV cache reset verified zero (CPU, 224.00 MiB) (engine #528)    <- request 3

One request, one pass of three sampled reads over every KV tensor (56 of them for 0.6B, ~112 for the 30B, each ggml_backend_tensor_get a device readback on HRX). The benchmark in the body does not see it because llama-bench never resets mid-run, so "no change beyond the box's own noise" is measuring a different thing from the shipped path. Keep the behaviour if you want it, but say "once per reset (once per request in a server)" instead of "load-time only / runs once per KV buffer", and if you want the cost statement to hold on HRX, measure it there once.

3. Two loose ends in src/llama-kv-zero.cpp: llama_kv_zero_chunk_bytes() is declared in the header and defined, and has no caller anywhere in the tree (dead accessor, or the test that was meant to use it is missing), and the return value of llama_kv_zero_fill is dropped at both call sites (llama-kv-cache.cpp:314,410), so a repair that also fails leaves an ERROR line and a run that continues into the NaN this PR exists to prevent — the throw std::runtime_error("failed to allocate buffer for kv cache") three lines above is the local precedent for a hard stop. The sampling/repair logic itself has no test: a 1 MiB CPU buffer poisoned with 0x7E, one call, is a ten-line test and would cover the offsets, the 1 MiB chunking and the second verification.

What does hold here: the pad_nan=0 cases pass on CPU (the default suite, both shapes), the full FLASH_ATTN_EXT matrix on CPU is at 3,274 cases with 0 failures while I write this (still running, no regression from the harness change), and the harness fix itself is right — skipping view nodes in the support gate is what lets any FA case run on a backend whose dispatcher does not own the alias node, and it cannot change the verdict for backends that support every view. I could not verify the HRX half of the claim (419 OK / 0 FAIL on HRX0) without a GPU run; that is the one number in the body I am taking on trust.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Ran the HRX half on the real device, so here is the number I said I was taking on trust — plus what it cost to reproduce, because the documented command does not work from a plain llama.cpp build without two extra things.

HRX0, default path — your claim holds. Built this branch with the engine's HRX knobs (amdclang from /opt/rocm-therock, -DGGML_HRX=ON -DHRX_SOURCE_DIR=<hrx-system> -DGGML_NATIVE=ON), ran under gpu-hold -l "pi prs" -t 20:

$ ./test-backend-ops test -b HRX0 -o FLASH_ATTN_EXT -p pad_nan
Backend 1/2: HRX0
  Device description: AMD Radeon 8060S Graphics (Node 1) (gfx1151)
  FLASH_ATTN_EXT(...kv=256,nb=175,mask=1,...,permute=[0,1,2,3],pad_nan=0): OK
  FLASH_ATTN_EXT(...kv=1024,nb=1,mask=1,...,permute=[0,2,1,3],pad_nan=0): OK
  2/2 tests passed
  Backend HRX0: OK

Both shapes, HRX0 vs CPU, as the body says. This is also the first FA case that has ever run on HRX in my hands, so the harness fix does what you say it does.

HRX0, poisoned — also as you say, and worse than CPU on the decode shape:

$ GGML_TEST_FA_NAN_PAD=1 ./test-backend-ops test -b HRX0 -o FLASH_ATTN_EXT -p pad_nan
[FLASH_ATTN_EXT] NaN at index 0 (HRX0=nan CPU=-0.312988)   ...kv=1024,nb=1,...,permute=[0,2,1,3],pad_nan=1): FAIL
  2/8 tests passed      (all of pad_nan=1,2,3 fail, in both the prefill and the decode shape)

On CPU alone the same flag gives 5/8 — the decode shape survives there and the prefill shape does not. So HRX reads masked K/V in the decode layout where the CPU does not, which is exactly the invariant the allocator fix is protecting, and it makes the pad_nan=1..3 cases more than a curiosity: they are the difference between the two backends. That strengthens my point that the sentence in the comment ("the stricter property the CPU reference has for free") should go — but it also means the mechanism you shipped is the right one, and the CHANGES on this PR are about wording, the per-request cost claim and the missing test, not about the fix.

Two things anyone reproducing this needs (worth a line in the PR body or the test's comment):

  1. IREE_HAL_AMDGPU_LIBHSA_PATH must point at TheRock's libhsa-runtime64.so.1 at run time, e.g. /opt/rocm-therock/lib/python3.14/site-packages/_rocm_sdk_core/lib/libhsa-runtime64.so.1. Without it hrx_gpu_initialize(0) fails, the HRX backend registers an empty device list (ggml-hrx.cpp:1300-1313), test-backend-ops prints Testing 1 devices and tests the CPU only, and the run exits 0 — a green result that measures nothing. The engine's own build sets this (cmake/hrx.cmake → ONEBIT_HRX_LIBHSA); a bare llama.cpp build does not.
  2. -b is an exact device name (strcmp, tests/test-backend-ops.cpp:10719), so -b HRX silently skips every device (Backend 1/2: HRX0 / Skipping, 2/2 backends passed, exit 0). Your body uses -b HRX0, which is right; my first two attempts used -b HRX and got two green runs that tested nothing.

…ml-org#528)

A KV cache's padded columns must be finite. Every attention kernel masks the columns past
the sequence end with -INFINITY and relies on those columns holding zeros: -infinity + NaN
is NaN and 0 * NaN is NaN, so one padded column with garbage in it makes a whole output row
NaN. llama.cpp does clear the KV buffer when it allocates it ("allocate tensors and
initialize the buffers to avoid NaNs in the padding"), but on HRX that clear is best-effort
- ggml-hrx's buffer_clear logs a failed fill and carries on - and a clear that did not take
leaves whatever the device memory held before.

src/llama-kv-zero.cpp verifies the padding instead of trusting the clear, at allocation and
on every reset (llama-kv-cache.cpp, marked [1bit]). The fast path samples three 4 KiB windows
in each of three tensors spread over the buffer - the clear is one fill submit per buffer, so
that says as much as scanning it would, and keeps the cost at a handful of readbacks because
a server resets the cache in request handling, not only at load. Measured on HRX0 with a
1152 MiB KV cache: 0.202 ms per verification. When the sample is not zero the buffer is filled
through the backend's own tensor writes and verified in full; a repair that still leaves
non-zero padding fails the allocation (the constructor throws, like the allocation failure
above it) or aborts the reset, instead of serving the NaN this exists to prevent.

Reproduced the incident's condition on HRX0 end to end with a local, uncommitted switch that
makes buffer_clear leave 0x7E (f16 NaN) in buffers over 64 MiB - i.e. a clear that does not
take - and Qwen3-4B `--parallel 4 -kvu`:

  clear only        (ONEBIT_KV_ZERO=0): 32-64 x "HRX returned NaN logits: count=151936 of
                                        151936, index range [0..151935], contiguous=yes"
  verify + repair   (default):         "KV cache was not zero after the clear (HRX0, 12288
                                        bytes non-zero in 3 samples): zero-filling 1152.00
                                        MiB and verifying again", 0 NaN logits, 60/60 requests
                                        clean, 4/4 slots

The first is the abort in engine#528 line for line (same vocabulary count, same contiguous
range), which is what makes this the fix for that class and not only for the test case.

tests/test-kv-zero.cpp covers the sampler and the repair on CPU buffers: a clean buffer is
verified, a poisoned one is repaired, each of the three sampled windows is checked
individually, and a 6 MiB buffer exercises the 1 MiB chunking and the second, full verification.

Also in tests/test-backend-ops.cpp, the harness bug the issue comment names: the support gate
asked ggml_backend_supports_op about every tensor *before* allocation, including the k/v alias
nodes, and ggml-hrx claims only what its dispatcher executes, so a lone VIEW made every
FLASH_ATTN_EXT case "not supported [HRX0, HRX0]" and no upstream flash-attention case had ever
run on HRX. Alias nodes are now skipped by that gate, and the pad_nan regression case stays:
pad_nan=0 (finite padding, the property this commit guarantees) is always run and passes on
HRX0 vs CPU for the prefill window (q=175 over n_kv=256) and for decode (n_kv=1024 in the
model's cache layout). pad_nan=1..3 poison the padding and are opt-in diagnostics
(GGML_TEST_FA_NAN_PAD=1); they do not show a CPU-vs-HRX difference in tolerance but the
opposite - measured at this pin, the batched prefill shape returns NaN on the CPU backend for
all three poisonings, only the decode shape survives there, and HRX returns NaN in both - which
is why the padding is zeroed and verified rather than tolerated by any kernel.

FLASH_ATTN_EXT matrix on the default path: 419 OK / 0 FAIL. MOE/softmax/norm/GET_ROWS ops:
0 FAIL. A kernel-side select on the mask was measured at -2..-4 % pp512 and is not part of
this change, by decision.
@bong-water-water-bong

Copy link
Copy Markdown
Author

All three points taken; pushed as f7d22ac68 (force-push on 1bit/528-pad-nan), PR body rewritten.

1. The CPU claim was wrong, and you were right for exactly the shape I added the case in. Reproduced your run on this box (-b CPU, GGML_TEST_FA_NAN_PAD=1): prefill kv=256,nb=175 returns CPU=nan at index 0 for all three poisonings, decode kv=1024,nb=1 survives — 5/8, same as you. So the sentence is gone. What the comment says now is that no backend promises to skip a non-finite padded column before reading it — the reference skips a masked key in ggml_compute_forward_flash_attn_ext_f16_one_chunk, but the batched paths multiply and a -INFINITY mask cannot undo a NaN — and that this is precisely the argument for zeroing the padding rather than for kernel tolerance. The cases stay, opt-in, labelled as diagnostics that show both backends leaking (and, per your HRX run, HRX leaking in both shapes where the CPU leaks in one).

2. "Load-time only" was wrong and is withdrawn. clear(true) is called from request handling, and you are right that llama-bench cannot see it. Two changes rather than a wording fix:

  • the fast path now samples three windows in three tensors spread over the buffer (the clear is one fill submit per buffer, so a spread sample says what scanning all 56-112 tensors would) instead of reading every tensor;
  • measured it on the shipped path, on HRX0, with a 1152 MiB KV cache: 0.202 ms per verification (verify: 0.202 ms per call (20 calls)). At one reset per request that is 0.2 ms against a ~60 ms request; in my served runs the cache was reset 3-4 times per 25 requests, which is why request time does not separate the arms. The body now says "per reset, which is request handling in a server, 0.202 ms measured", and the old bench-based claim is gone.

3. All three loose ends closed.

  • llama_kv_zero_chunk_bytes() deleted (dead accessor, no caller).
  • Return value handled: allocation throw std::runtime_error (same shape as the allocation failure three lines above), reset GGML_ABORT — the existing NaN-logits guard in common/sampling.cpp aborts for the same reason, so stopping beats serving NaN. A repair is still verified in full (not by sample) before it is believed.
  • tests/test-kv-zero.cpp added (147 lines, CPU-only, so it runs anywhere): clean buffer verified; poisoned buffer repaired; each of the three sampled windows poisoned in turn (start/middle/end of first and last tensor); a 6 MiB buffer exercising the 1 MiB chunking and the second verification. ./bin/test-kv-zero → all pass, and it is registered with llama_build_and_test.

On your HRX half: thanks for running it — and your two reproduction notes are now in the PR body, because the IREE_HAL_AMDGPU_LIBHSA_PATH one cost me the same afternoon (a silent empty device list, exit 0). Your conclusion that HRX reads masked K/V in the decode layout where the CPU does not is consistent with what I see, and it does not change the fix: the padding is zeroed, so neither path is ever handed a non-finite column.

Re-verified after the changes, same box: FLASH_ATTN_EXT matrix on the default path 419 OK / 0 FAIL; pad_nan=0 both shapes 2/2 OK on HRX0 vs CPU; MUL_MAT,MUL_MAT_ID,SOFT_MAX,GET_ROWS,RMS_NORM 0 FAIL; test-kv-zero all pass; and the negative control (a local, uncommitted switch that makes buffer_clear leave 0x7E, i.e. a clear that does not take) still gives 32-64 × HRX returned NaN logits: count=151936 of 151936, contiguous=yes without the verification and 0 with it, with the repair line in the log.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Re-review at f7d22ac. All four things I raised are fixed and the fixes are verified on this box; READY from my side.

The new test exists and passes. test-kv-zero is registered in tests/CMakeLists.txt and covers the clean path, a whole-tensor poison, each of the three sampled windows (start, middle, end) on the first and last tensor, and a chunked repair over 6 MiB:

$ ./bin/test-kv-zero
llama_kv_zero_fill: test was not zero after the clear (CPU, 12288 bytes non-zero in 3 samples): zero-filling 6.00 MiB and verifying again (engine #528)
llama_kv_zero_fill: test zero-filled and verified (CPU, 6.00 MiB) (engine #528)
clean buffer verified / poisoned tensor repaired / all sampled windows checked / chunked repair over 6 MiB
test-kv-zero: all tests passed
$ ctest -R kv-zero --output-on-failure
1/1 Test #23: test-kv-zero .....................   Passed    0.01 sec

The per-request cost claim is now true and the cost is a fraction of what it was. The fast path samples 3 tensors of the buffer (first/middle/last) x 3 windows instead of 3 windows of every tensor, and the docs say "once per request in a server". Measured, llama-server -c 2048 -np 1 -lv 4, three requests:

I llama_kv_zero_fill: KV cache verified zero (CPU, 224.00 MiB, 3 of 112 tensors sampled) (engine #528)      <- allocation
I llama_kv_zero_fill: KV cache reset verified zero (CPU, 224.00 MiB, 3 of 112 tensors sampled)              <- request 1
                                                        ... x3, one per request

i.e. 9 readbacks per reset instead of 336 for this model (112 KV tensors), and the fact that it runs per request is now in the header and in llama-kv-cache.cpp's comment.

The failure path is no longer silent: allocation throws and clear() GGML_ABORTs, and llama_kv_zero_chunk_bytes() (no callers) is gone.

The test-backend-ops comment now says what the backends actually do — CPU NaN in the batched shape, decode surviving there, HRX NaN in both — which matches what I measured at both ends:

$ ./test-backend-ops test -b CPU -o FLASH_ATTN_EXT -p pad_nan            -> 2/2 passed, Backend CPU: OK
$ GGML_TEST_FA_NAN_PAD=1 ... -b CPU                                     -> 5/8 (the three batched poisonings fail)
$ GGML_TEST_FA_NAN_PAD=1 ... -b HRX0   (earlier, HRX build)              -> 2/8 (all six fail)

One wording nit, since it is the kind of sentence that gets quoted later: "The clear is one fill submit per buffer, so sampling a few tensors out of it says as much as reading all of them would" is stronger than the code supports. The sampled indices are i * (n - 1) / 2 for i in 0..2, i.e. tensors 0, n/2 and n-1 of the context — for the 112-tensor 0.6B cache those are 0, 55 and 111 — so a fill that failed on, say, tensor 1 while 0, 55 and 111 landed would be reported as verified. That is fine for the failure mode you are defending against (HRX's clear is one submit per buffer: it either took or it did not), but call it a canary rather than a proof, and if you want it pinned, add a case that poisons a tensor between the sampled ones and asserts the documented outcome.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

One more nit from the finished build, since it is a warning the new file introduces: tests/test-kv-zero.cpp:137

/home/bcloud/wt/tprs-llama/tests/test-kv-zero.cpp:137:40: warning: format '%zu' expects argument of type 'size_t',
  but argument 2 has type 'int' [-Wformat=]

the printf("chunked repair over %zu MiB\n", (2 * 3 * 1024 * 1024) / 1024 / 1024) — the expression is int, so it needs %d or a (size_t) cast. Everything else in the build at f7d22ac is warning-free, and the test itself passes (test-kv-zero: all tests passed, ctest -R kv-zero 1/1, 0.01 s).

@bong-water-water-bong
bong-water-water-bong merged commit b8861a9 into 1bit/hrx-vulkan-patched Oct 30, 2026
@bong-water-water-bong
bong-water-water-bong deleted the 1bit/528-pad-nan branch October 30, 2026 13:54
bong-water-water-bong pushed a commit that referenced this pull request Nov 11, 2026
…m's dead register_*_cases layer

Answers the CHANGES at 9f65ede, and the review was right on both counts.

1. It did not compile: the kept upstream layer registers support.activation_publication_contract -> that function is
   defined nowhere on our line (upstream has it), and a static function's body is compiled whether or not anything
   calls it.
2. #155's own case never ran: the layer's entry point, register_hrx_ops_cases(), was defined and never called - main()
   calls add_cases() - so everything registered only there was dead, including gdn_snapshot.cpu_reference.{2..5},
   the reference for the recurrent-MTP-snapshot fix the commit exists for.

What is kept is only what #155's cases need: run_gdn_snapshot_cpu_reference_case() and
run_dynamic_generic_ops_cpu_reference_case() with their helpers, registered in our add_cases() with our add(suite, ...)
idiom, plus the two upstream-only helpers (glu_op_name, type_name) removed because the layer was their only caller.

Checked mechanically, since this branch has no CI (gh pr checks 280: no checks reported):
  - every run_*/add_* named inside add_cases() has a definition in the file (46 referenced, 0 missing) - the class of
    failure the review found, checked rather than assumed;
  - no register_*_cases reference remains;
  - the only unreferenced static left is kquant_decode_expectation, which was already unreferenced on the base branch.

Not verified: a build of test-hrx-ops, which needs the HRX/libhrx superbuild. That is the one thing this PR cannot
show by itself, and the reviewer said so first.
bong-water-water-bong pushed a commit that referenced this pull request Nov 12, 2026
## Overview

The packaged HRX suites fail 16 cases at the current backend pin. This fixes concat launch-bound compilation and updates stale dispatch expectations while retaining numerical comparisons and negative coverage.

- Reuse the concat bound fix and dynamic-reuse regression from #155; the existing element limit guarantees at most 4,194,304 workgroups.
- Check the current RoPE capacity class, aligned publication kernels, IQ2_S specialization, and low-token RMSNorm selection.
- Explicitly verify rejection of in-place RMSNorm, matching the kernels' no-alias contract.
- Verify supported Gemma Add-before-Add fusion parameters and add CPU-reference coverage.

## Additional information

Validated on gfx1100 with HRX `5f4dfc8731a1b37fdd380c566c7babf7ae3548cd`: **436 passed, 0 failed** across buffer (5), backend (99), JIT (6), and ops (326). CTest wall time was 62.09 seconds with two concurrent suites and internal worker counts 1/4/2/4. Three standard backend CONCAT CPU-comparison cases also passed. Numerical tolerances were unchanged.

gfx1151 CI qualification **passed: 436 cases, 0 failures, 59.03 seconds CTest wall time**: [workflow run 40393012701](https://github.com/ROCm/ggml-staging-automation/actions/runs/40393012701), testing this PR's exact backend commit `0230f1b29ee2d009602a7b2c6cbce64f1b1290d2` through the packaged test workflow. The separate packaging integration is ROCm/ggml-staging-automation#110. This PR overlaps only the concat fix/regression in #155; it does not include that PR's recurrent-state changes.

## Requirements

- [ ] I have read and agree with the [contributing guidelines](https://github.com/ggml-org/llama.cpp/blob/master/CONTRIBUTING.md) (contributor confirmation).
- AI usage disclosure: YES. Codex investigated the 16 failing cases through sequential subagents, reviewed the changes, and ran focused and full-suite validation. The user requested this submission.
bong-water-water-bong pushed a commit that referenced this pull request Nov 12, 2026
## Overview

Fix two HRX failures encountered while running Qwen3.5-35B-A3B-MTP-GGUF with multi-token drafting:

- Give the dim-0 concat launch count an explicit range so Loom can compile the 2048+2048 hidden-state concat used by MTP. Add dynamic executable-reuse coverage for 1 and 128 rows.
- Compute recurrent snapshot decay ratios as `exp(log_decay_j - log_decay_i)` in both fused Gated DeltaNet snapshot publication paths. Dividing cumulative exponentials could produce `0/0` after underflow, corrupting saved states used for speculative rejection/rollback.

Add CPU-reference regressions for attention and every saved state with 2 through 5 verification tokens, ordinary and underflowing decay, fused dispatch, and repeated graph execution. The snapshot regression fails with NaNs for 3 through 5 tokens before the fix.

## Additional information

Prior validation on gfx1100 (RX 7900 XTX):
- Focused HRX ops: 5/5 pass, including all four snapshot cases and dynamic generic ops.
- Loom JIT suite passes, including the new concat workloads.
- Full-model drafting lengths 2, 3 and 4 pass repeated requests and a 477-token prefill. Default length 3 matches all three non-MTP baseline texts; traces cover full, partial and zero acceptance with recurrent rollback and no checkpoint fallback. Lengths 2/4 match counting and arithmetic; open-ended chat has minor wording differences.

Rebased onto `hrx-graph-develop-v2` at 7fd4e51 with an identical patch; whitespace checks pass. GPU tests have not been rerun after this rebase. gfx1151 validation remains outstanding.

Follows the MoE-routing fix in #153, already on the target branch. Lemonade automatic MTP enablement and ROCm/ggml-staging-automation#109 are separate changes; this PR contains only the backend kernels and their regressions.

## Requirements

- [ ] Contributor confirmation: I have read and agree with the [contributing guidelines](https://github.com/ggml-org/llama.cpp/blob/master/CONTRIBUTING.md).
- AI usage disclosure: YES. Codex assisted with investigation, implementation, regression tests, validation and preparation of this draft at the contributor's request.
bong-water-water-bong added a commit that referenced this pull request Nov 13, 2026
)

* vulkan: fix CI llvmpipe by allowing dim 3 broadcast in MUL_MAT (#31239)

* vulkan: allow dim 3 broadcast in MUL_MAT

supports_op rejected every MUL_MAT whose src0 and src1 differ in ne3,
although mul_mm, mul_mmq and mul_mat_vec already broadcast src0 over
dim 3 through broadcast3. Such a matmul then ran on the CPU with a
copy of the weight, and the split layout changed with the number of
streams in the ubatch.

Keep the strict check for MUL_MAT_ID only, and route the broadcast
cases away from mul_mat_vec_nc, the one path that requires equal ne3.

* tests : harden MUL_MAT with permuted dim 3 broadcast cases

Harden the MUL_MAT coverage with a weight broadcast over dim 3 against
a permuted per-stream activation, the shape of an MLA output
projection with a non unified KV cache, for a single token, several
heads and several tokens per stream.

* tests : speed up tensor data generation and model saving (#31145)

* tests : speed up tensor data generation and model saving

Refactor save_models to create only the model, not a llama_context,
which is not needed for saving. Replace the slow std::normal_distribution
draw with a splitmix64 + box-muller normal generator.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4-Flash-Vision-Exp-GGUF (Mac Studio, M2 Ultra, 192GB)

* tests : use a shared pool of normal draws for tensor data

Generate a pool of normal draws once with std::mt19937 and
std::normal_distribution, then have every tensor copy a cyclic slice of
it instead of running a per-tensor box-muller. The name-keyed slice
selection keeps the draw deterministic.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4-Flash-Vision-Exp-GGUF (Mac Studio, M2 Ultra, 192GB)

* tests : log the size of saved models

Report the produced file size in bytes and MB after each save.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4-Flash-Vision-Exp-GGUF (Mac Studio, M2 Ultra, 192GB)

* tests : simplify the model save log

Put the model name, target and size on one line per saved model.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4-Flash-Vision-Exp-GGUF (Mac Studio, M2 Ultra, 192GB)

* rpc : catch std::length_error in recv_msg (#31204)

* llama : build the k-pool sparse selection independently of the kq_mask shape (#31243)

* llama : build the k-pool sparse selection independently of the kq_mask shape

qwen4exp (QSA) and glm5-next pick cache cells by index and no longer read the kq_mask values, but they still shaped the selection like the dense kq_mask. Build the selection as [n_kv, n_tokens] over the cache cells instead, and split it into the streams of the K view right before the attention.

This lets the dense mask change its layout (e.g. per-sequence row lists) without touching the sparse layers.

* improve comment

Co-authored-by: Georgi Gerganov <[email protected]>

* llama : drop the unused build_fused_top_k_mask args, review nits

---------

Co-authored-by: Georgi Gerganov <[email protected]>

* cmake: WASI doesn't support spawning (#30751)

* model : add LiquidAI/LFM3-1.7B and LiquidAI/LFM3-VL-2B (#31252)

* model : add LiquidAI/LFM3-1.7B and LiquidAI/LFM3-VL-2B

Co-authored-by: Sigbjørn Skjæret <[email protected]>
Co-authored-by: Xuan-Son Nguyen <[email protected]>
Assisted-by: Claude Opus 5.5

* tests : set the SWA rope base of the LFM3 test model

Assisted-by: Claude Opus 5.5

* llama : enable recurrent state rollback for LFM3

Assisted-by: Claude Opus 5.5

* Apply batched suggestions from code review

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

* gguf-py : align the lfm3vl mapping comments

Assisted-by: Claude Opus 5.5

* llama : fix CRLF line endings from the review suggestions

Assisted-by: Claude Opus 5.5

* tests : add the LFM3 Metal fusion baseline

Assisted-by: Claude Opus 5.5

* llama : keep the LFM3-VL depthwise conv kernels in F32 when quantizing

Assisted-by: Claude Opus 5.5

---------

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

* snapdragon: switch QDC artifact upload and log download to v2 API (#31240)

Signed-off-by: Mengsheng Wu <[email protected]>

* common : support deferred tools and tool_reference content parts (#31256)

* common : support deferred tools and tool_reference content parts

Assisted-by: Claude Opus 5.5

* common : credit the deferred tools co-author

Co-authored-by: Aldehir Rojas <[email protected]>

Assisted-by: Claude Opus 5.5

* tests : fix the type check of the deferred tools test

Assisted-by: Claude Opus 5.5

* model : add LiquidAI/LFM3-Audio-2B and LiquidAI/LFM3-Omni-2B (#31257)

* model : add LiquidAI/LFM3-Audio-2B and LiquidAI/LFM3-Omni-2B

Co-authored-by: Xuan Son Nguyen <[email protected]>
Assisted-by: Claude Opus 5.5

* convert : read the LFM3-Audio config.json as released

A transformers that knows lfm3_audio rewrites the config into another layout (no lfm/encoder keys).

Assisted-by: Claude Opus 5.5

* mtmd : disable flash attention for the LFM3-Audio depthformer

Assisted-by: Claude Opus 5.5

* tts : add a voice option for LFM3-Audio and LFM3-Omni

The model card offers a female and a male voice; --tts-voice for llama-tts, "voice" for the server /tts.

Assisted-by: Claude Opus 5.5

* clean up template handling

* convert : detect LFM3-Audio and LFM3-Omni by model_type

Assisted-by: Claude Opus 5.5

* move banned tokens --> logits bias --> mtmd_helper

* leave mtmd-cli unchanged

* no more template_asr_system

* left over

* llama : keep the LFM3-Audio encoder convs and codec unquantized

Assisted-by: Claude Opus 5.5

* common, mtmd : shorten comments

Assisted-by: Claude Opus 5.5

---------

Co-authored-by: Xuan Son Nguyen <[email protected]>

* HIP/CUDA: remove pragma unroll from loops in conv2d where itteration count cant be infered at compile time (#31255)

* tests: fix CI riscv timeout in test-llama-context (#31265)

In --models mode the thread count per model is computed and printed,
but never set in the params, so every context runs on the common
default, the number of physical cores. With several models in
parallel this oversubscribes the CPU, and the busy-wait barriers of
the CPU backend make it collapse.

Set the count in cpuparams and cpuparams_batch.

* server: expose the reasoning effort levels of the chat template (#31271)

* server: expose the reasoning effort levels of the chat template

The capability probe renders a user turn for each candidate level
(minimal, low, medium, high, xhigh, max) and for an unknown level. A
level is honored when it renders without raising and differently from
the unknown level, which shows the template fallback. Levels sharing a
render are aliases and the highest one is kept.

The caps serialize to JSON, and chat_template_caps in /props reports
the list as reasoning_effort_levels, from lowest to highest.

* jinja: keep the caps free of the json dependency

The caps keep reporting their flags as a map, and the effort levels
stay a plain member. common_chat_templates_get_caps() builds the JSON
the server reports from both, so jinja depends on json only for the
probe inputs.

* model : add LiquidAI/d1-2B and LiquidAI/d1-omni-2B (#31275)

* model : add LiquidAI/d1-2B and LiquidAI/d1-omni-2B

Assisted-by: Claude Opus 5.5

* convert : keep the speech task templates out of the d1 GGUFs

Assisted-by: Claude Opus 5.5

* small refactoring: no_batching

---------

Co-authored-by: Xuan Son Nguyen <[email protected]>

* server : add realtime conversation and transcription on /v1/realtime (#31269)

* server : add realtime conversation and transcription on /v1/realtime

Co-authored-by: Xuan Son Nguyen <[email protected]>
Assisted-by: Claude Opus 5.5

* examples : default the realtime client to the server port 9931

Assisted-by: Claude Opus 5.5

* server : sample realtime responses right after their own decode

Slots respond in turns on one context: sampling at the start of the next step read the logits of whichever slot decoded last, so concurrent sessions mixed their outputs.

Assisted-by: Claude Opus 5.5

* move more stuff to server-realtime, making it self-contained

* examples : fix the type check of the realtime client

Assisted-by: Claude Opus 5.5

* examples : use the model card prompts in the realtime client

Assisted-by: Claude Opus 5.5

---------

Co-authored-by: Xuan Son Nguyen <[email protected]>

* ui : Search dialog (#31173)

* ui : replace the sidebar search mode with a search dialog

Search opens a spotlight dialog (Cmd+K or the Search entry under New chat in the sidebar) with keyboard navigation over recent chats and sidebar actions. Phones keep the search page.

Sidebar actions show their shortcuts, with new ones for Settings (Cmd+,) and Models (Shift+Cmd+M).

Assisted-by: Claude (Opus 5.5 Medium)

* ui : ignore search dialog keys while an IME is composing

Enter confirms an IME candidate and the arrow keys move through the candidates, so the search field leaves them to the IME instead of opening the highlighted result or moving the highlight.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: Fix draft for new message disappearing after using "Add System Message" action (#31214)

* ui: keep new chat draft when adding a system prompt

Fixes #24338

Assisted-by: Claude (Opus 5.5 Medium)

* ui: remove unused initialMessage from chat form

Assisted-by: Claude (Opus 5.5 Medium)

* ui: Support OGG audio attachments by converting them to WAV (#31237)

* ui: support OGG audio attachments by converting them to WAV

Fixes #24164

Assisted-by: Claude (Opus 5.5 Medium)

* ui: convert all non WAV/MP3 audio uploads to WAV

Assisted-by: Claude (Opus 5.5 Medium)

* ui : show save and reset settings buttons only when relevant (#31248)

* ui : show save and reset settings buttons only when relevant

Assisted-by: Claude (Opus 5.5 Medium)

* ui : move reset settings button next to reload app, pad settings caption

Assisted-by: Claude (Opus 5.5 Medium)

* chat : stop qwen3-coder reasoning and content before template separators (#30557)

* chat : strip trailing whitespace from parsed reasoning and content

Assisted-by: Claude Fable 5.1

* chat : stop qwen3-coder reasoning and content before template separators

Assisted-by: Claude

* tests : remove the Qwen parser case from the chat session tests

Assisted-by: Claude

* common : handle partial prefix until match at end of generation

---------

Co-authored-by: Zeshawn Zahid <[email protected]>
Co-authored-by: Alde Rojas <[email protected]>

* vulkan: clamp A prefetch to end_k in coopmat1 int8 matmul (#30283)

* fix: clamp the A prefetch to end_k in the Vulkan coopmat1 int8 matmul, like the B prefetch

* fix: zero the A scale for k steps past end_k in the Vulkan coopmat1 int8 matmul instead of relying on the clamped block

* cuda : add top-k MoE fusion for 384 experts (#31288)

Assisted-by: Codex

* tests : adjust constants to reduce irrelevant warnings (#31254)

* ui: build the reasoning menu from the template effort levels (#31273)

* ui: build the reasoning menu from the template effort levels

When the chat template reports effort levels, the menu offers Default,
Off and those levels, and a pick is sent as reasoning_effort. A
template that reports none keeps the token budget menu.

Picking a model other than the one that produced the last answer resets
the conversation effort to Default, and an effort the current menu
lacks resolves to Default.

* ui: wait for a cold router model before building the request

A router serves the props of a loaded model only, so a request sent to
a cold model was built without its template effort levels and fell
back to a token budget. The request now waits for the model to load,
joining a load already in flight, and a stop during the wait sends
nothing.

Status waiters hold a list per model so a load and the requests that
wait on it each get theirs, and a props request in flight is shared
with a second caller instead of answering null.

* ggml : bump version to v.28.0 (ggml/1676)

* ggml : bump version to 0.28.0

* authors : update

* sync : ggml

* server : support tool calls in /v1/realtime (#31287)

* server : add tool calls to /v1/realtime

Assisted-by: Claude Opus 5.5

* refactor

---------

Co-authored-by: Xuan Son Nguyen <[email protected]>

* mtmd: enable video input support for LFM3 model family (#31283)

* mtmd : add LFM3-VL and LFM3-Omni video input

Co-authored-by: Xuan Son Nguyen <[email protected]>
Assisted-by: Claude Opus 5.5

* mtmd : reserve the soundtrack command to avoid a GCC 11 warning

---------

Co-authored-by: Xuan Son Nguyen <[email protected]>

* llama.cpp : bump version to 0.8.0 (#31309)

* llama.cpp : bump version to 0.8.0

* authors : update

* gguf-py: fix np_roundf dropping the sign (#31310)

* gguf-py: fix np_roundf dropping the sign

* Update requirements/requirements-convert_legacy_llama.txt

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

* requirements.txt

* Update tools/server/tests/requirements.txt

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

---------

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

* cuda: fuse MoE (MUL_MAT_ID) gate/up and GLU in MMQ (#31188)

* sycl: work-group argmax for short TOP_K rows (#31110)

* sycl: work-group argmax for short TOP_K rows

Used angelX to optimize SYCL/drama 3 coordination, results are as follows

Rows with ncols <= max work-group size: one work-item per column, k rounds of work-group argmax. Ties take the lower column, NaN is never picked. Longer rows keep the existing paths.

Arc Pro B70, oneAPI 2026.1, test-backend-ops perf (existing short-row cases), base 9b56ccf00 vs patch, median ratio of 6 rotating A/B/A rounds:

| ncols | nrows | k | base us | patch us | speedup |
|---|---|---|---|---|---|
| 16 | 1024 | 1 | 19.97 | 2.88 | 6.95x |
| 16 | 1024 | 2 | 23.83 | 2.90 | 8.25x |
| 16 | 1024 | 8 | 66.12 | 4.66 | 14.21x |
| 16 | 8192 | 1 | 110.42 | 5.96 | 18.51x |
| 16 | 8192 | 2 | 130.21 | 8.82 | 14.77x |
| 16 | 8192 | 8 | 420.62 | 27.27 | 15.42x |
| 128 | 1024 | 1 | 20.49 | 2.94 | 6.97x |
| 128 | 1024 | 2 | 25.89 | 3.45 | 7.52x |
| 128 | 1024 | 8 | 101.67 | 8.95 | 11.36x |
| 128 | 8192 | 1 | 112.19 | 13.29 | 8.44x |
| 128 | 8192 | 2 | 141.18 | 20.60 | 6.85x |
| 128 | 8192 | 8 | 643.21 | 67.60 | 9.51x |
| 1024 | 1024 | 1 | 17.32 | 14.98 | 1.16x |
| 1024 | 1024 | 2 | 28.77 | 24.02 | 1.20x |
| 1024 | 1024 | 8 | 151.87 | 77.88 | 1.95x |
| 1024 | 8192 | 1 | 156.49 | 138.78 | 1.13x |
| 1024 | 8192 | 2 | 201.47 | 209.18 | 0.96x |
| 1024 | 8192 | 8 | 1006.25 | 632.60 | 1.59x |

The 1024 x 8192, k=2 case is 3.7% slower.

Correctness: test-backend-ops -o TOP_K 533/533 and -o ARGSORT 98/98 on the patch, again on the rebase onto 3f03b1772.

Full test-backend-ops aborts on base and patch alike at the non-F32 SWIGLU_OAI assert (element_wise.cpp:1187, see #30857). With only those cases excluded: 20145/20173 on base and patch. One CPY f16->q2_0 [256,2,3,4] failure was seen once on the patch, and 3/3 re-runs pass on base and patch. All other patch-run failures also fail on base.

Assisted-by: Claude Opus 5.5

* made changes as suggested

Assisted-by: Claude Opus 5.5

* codeowners : refresh teams and maintainer PRs link (#31316)

* codeowners : refresh teams and maintainer PRs link

Update the CODEOWNERS team legend with the current `ggml-org` team
memberships, and extend the maintainer PRs link in the README to cover
all current members of the `maintainers` team.

Assisted-by: pi:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (MacBook, M5 Max, 128GB)

* codeowners : list remaining backend sub-teams

Add the `ggml-*` sub-teams that were missing from the team legend at the
top of the file: base, cpu, et, hip, openvino and riscv. The legend now
covers every sub-team of the `ggml` and `llama` maintainer groups.

No ownership rules change - only the comment block is extended.

Assisted-by: pi:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (MacBook, M5 Max, 128GB)

* codeowners : use ggml-hip team for HIP backend

Route `/ggml/src/ggml-hip/` to `ggml-org/ggml-hip` instead of a single
collaborator, so review requests reach the whole team.

Assisted-by: pi:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (MacBook, M5 Max, 128GB)

* codeowners : add llama-examples team

List the newly created `llama-examples` team in the team legend at the
top of the file.

Assisted-by: pi:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (MacBook, M5 Max, 128GB)

* codeowners : use llama-examples team for examples

Collapse the per-directory rules that only listed a single collaborator
into a single `/examples/` rule owned by `ggml-org/llama-examples`.
Directories owned by other collaborators keep dedicated rules, since the
last matching pattern takes precedence in CODEOWNERS.

Assisted-by: pi:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (MacBook, M5 Max, 128GB)

* cont : update zdnn

* codeowners : use llama-base team for src

Route `/src/` to `ggml-org/llama-base` and list the new team in the
legend at the top of the file. Rules for individual `src` files are kept,
since the last matching pattern takes precedence; `/src/models/` drops
its individual owner, which is already covered by `llama-models`.

Assisted-by: pi:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (MacBook, M5 Max, 128GB)

* llama : remove simple batch splitting for DSV4 (#31300)

* llama : fix DSV4 compressor padding for simple batches

Count actual tokens per sequence when padding compressor writes. Add a graph reuse regression test for odd-sized DeepSeek V4 and V4.1 batches.

Assisted-by: Codex

* tests : cover multiple sequences in DSV4 padding regression

Exercise one and two sequences at different positions while keeping a fixed ubatch shape.

Assisted-by: Codex

* llama : remove simple batch splitting for DSV4

Use the existing sequence splitting to keep n_seq_tokens consistent with
the compressor padding calculation. Extend the graph reuse regression to
6-token batches.

Assisted-by: Codex

* ci(s390x): switch to Ubuntu 26.04 runners (#31317)

* ggml-cpu: SVE 256-bit Implementation of mxfp4 gemv kernel (#28141)

* mxfp4 sve 256 impl completed

* working with pretty good perf improvement

* review comments addressed

* review comments for SVE 256 check

* trailing white spaces removed

---------

Co-authored-by: Anubhav Srivastava <[email protected]>

* ggml-cpu: SVE 256 bit implementation of gemm_q6_K_8x8_q8_K kernel (#27472)

* q6_k GEMM working

* cleanup

* review comments

* review comment addressed - removed pg16_8

* incorporated the review comments - replaced switch with if and other points

* marking q8_k_blocklen UNUSEDto disable warning for non-i8mm cases

* Speed up IQ4 quant creation with pre-computed halfway points (#31201)

* hexagon: add conv2d support (#30995)

* hexagon: add conv2d op

* hex-conv2d: add double-buffered staging

* hex-conv2d: full 64-wide activation block transpose straight from staged buffer

* hex-conv2d: implicit gemm

* hex-conv2d: remove scalar path and kernel

* hex-conv2d: unify conv2d kernel params for all paths

* hex-conv2d: scale HMX result before f16 storage and then restore during unpacking to prevent overflow

* hex-conv2d: fix f16 overflow in HMX paths

* hex-conv2d: refactor to rebase to new op fusion machinery

* hex-conv2d: restructure DMA pipelines and trace scopes

* hex-conv2d: removed the HVX_WIDTH and HVX_TILED paths

* hex-conv2d: remove in-loop vector spills

* hex-conv2d: refactor kparams, vtcm-layout and dma-pipeline to match the other ops

* hex-conv2d: add basic support for CONV_2D_DW

Co-Authored-By: Pranav Dhinakar <[email protected]>

* hex-conv_2d_dw: use DMA in all paths

* hex-conv_2d_dw: support for chunking larger inputs

* hex-conv_2d_dw: remove scalar/hvx access for w tensor (replaced with sync dma copy)

* hex-conv-2d: fix warnings

* hex-conv2d-dw: vectorize all paths

* hex-conv-2d-dw: tree-based reductions and unrolling to optimize

* hex-conv-2d-dw: uninline compute loops from dma loops

* hex-conv-2d-dw: move all kernel selection into the host solver and simplify/specialize kernel dispatch

* hex-softmax: update obsolete gates to enable SOFT_MAX for mmproj

---------

Co-authored-by: Max Krasnyansky <[email protected]>
Co-authored-by: Pranav Dhinakar <[email protected]>

* opencl: add tiled q4_k GEMM for adreno (#30412)

* opencl: run the tiled q4_K lm_head through a tiled GEMM at batch > 1

* opencl: split tiled dp4a q4_k gemm into its own file and test for dp4a

Assisted-by: Codex

---------

Co-authored-by: Li He <[email protected]>

* common, mtmd: bound control vector layer indices and M-RoPE position loops (#31336)

* common: bound control vector layer indices by the model layer count

A direction tensor layer index is parsed from the tensor name with no
upper bound, and the buffer size and write offset are computed in int.
A large index overflows both, so the accumulation writes before the
start of the buffer.

Pass the model layer count to the loader, reject indices above it like
the existing zero index check, and compute the sizes in size_t.

* mtmd: fill M-RoPE positions by whole merge tiles

The position loops of the Qwen-VL, GLM, PaddleOCR and Qwen2.5-VL
encoders hardcode a 2x2 merge inside a stride of n_merge, so a patch
grid that is not a multiple of the merge writes past the positions
buffer. Iterate over whole merge tiles with n_merge inner steps, which
bounds the writes by the patch count and gives the same positions on
aligned grids.

PaddleOCR also requires a merge aligned image at graph build, as the
Qwen-VL family already does.

* ggml-hrx: add AMD ROCm HRX native ggml backend

Proposal for a new AMD/ROCm backend.

See RFC discusion: `Insert discussion link`

* ggml-hrx: squash development through 8108322b7

Co-authored-by: Aaryaman Vasishta <[email protected]>
Co-authored-by: Rob Suderman <[email protected]>
Assisted-by: Codex

* ggml-hrx: adopt canonical Loom divisibility predicates (#139)

Loom kernels failed to parse after HRX replaced the mul predicate with multiple_of. Migrate the kernel contracts and require d8da4382863fef59d2deb914a287e5cda9f3f349, which introduced the canonical predicate spelling.

Relevant hrx PR: https://github.com/ROCm/hrx-system/pull/1372

* hrx: accept empty MoE expert views when matching graphs (#140)

## Overview

Qwen3 MoE microbatches that request no output logits produce empty expert views with nonzero slot offsets. HRX rejected these valid GGML views because their offsets exceed the zero-byte source extent, preventing graph matching during prefill and decode-like perplexity evaluation.

Skip byte-span bounds checks for empty tensors while preserving storage-root and alias-offset validation. Add a regression test covering all eight empty expert views, cache reuse, and rejection of a changed alias offset.

## Validation

- Final source builds successfully; all 7 focused graph matching, cache UID, and zero-output tests pass.
- Earlier end-to-end validation on gfx1100: Qwen3-30B-A3B Q4_K_M perplexity with `-c 512 --chunks 2 -b 512 -ub 1` completes with HRX PPL 6.7431 versus Vulkan 6.7573. The original code fails graph matching.
- Server boundary checks with `-ub 256`: original backend passes 256 prompt tokens and fails at 257; the repair completes 256, 257, and 513-token requests. These are execution checks, not generated-text quality checks.
- gfx1151 is covered by host-side graph construction, not GPU execution. The reported 262144-token all-GPU context could not be tested on the local 24 GiB GPU because its KV cache did not fit.

No HRX dependency update is required.

## Requirements

- [ ] I have read and agree with the [contributing guidelines](https://github.com/ggml-org/llama.cpp/blob/master/CONTRIBUTING.md).
- AI usage disclosure: YES. Codex assisted with investigation, implementation, tests, explanatory comments, and PR preparation under human review.

* ggml-hrx: prove packet bounds before view linearization (#141)

HRX per-axis footprint verification rejects aligned matmul, attention, and normalization packets whose remainder bounds omit the packet width.

The stricter view contract prevents flattening from hiding axis overruns. State the existing two- and four-element packet bounds and the guarded query-head bounds before accesses are linearized.

Relevant hrx PR: https://github.com/ROCm/hrx-system/pull/1512

* ggml-hrx: size fused router launch for target expert tiles (#146)

## Motivation

Qwen3 MoE decode-like perplexity is wrong on gfx1151 while prefill-like is right, and the same binaries are right for both on gfx1100. In https://github.com/ROCm/ggml-staging-automation/actions/runs/38275322264, Qwen3-30B-A3B-Instruct-2507 Q4_K_M measured HRX decode-like PPL 20503 against Vulkan 6.7573 on gfx1151 (`-c 512 --chunks 2 -b 512 -ub 1`); on gfx1100 the CI binaries give 6.7431.

The fused decode router (`qwen3_moe_router_projection_top8_fused_decode_f32`) hard-coded four experts per wave when sizing its launch, but the gfx1151 projection template handles two experts per wave. On gfx1151 the kernel therefore launched half the expert tiles it needed. The launch now reads experts-per-wave from the same template the projection uses, so the workgroup count follows the target's tile width. Every other wave64 target resolves to the previous constant of four.

This path only runs when the token count is exactly one, so it affects single-token decode and nothing else. It became reachable on 2026-10-12 when https://github.com/AMD-Ecosystem/llama.cpp/pull/140 let the graph matcher accept these microbatches; before that the regime did not execute on HRX at all.

## Testing

**gfx1151, staging CI.** A perplexity-only run of Qwen3-30B-A3B-Instruct-2507 alone, with llama.cpp pinned at this PR's head and hrx-system at the current staging pin 7696b5b3c02a, and the model's `perplexity: fail` relaxation removed so a pass is a strict PASS: https://github.com/ROCm/ggml-staging-automation/actions/runs/38580145237 (branch `ppl/qwen3-30b-router-fix-gfx1151`, dispatched with `skip_benchmarks=["lemonade-benchmark"]`, `model_tier=full`). Result: strict PASS.

| Regime | HRX gfx1151, before (run 38275322264) | HRX gfx1151, this PR | Vulkan |
| --- | ---: | ---: | ---: |
| decode-like, `-ub 1`, 2 chunks | 20503.1356 | 6.7431 | 6.7573 |
| prefill-like, `-ub 512`, 32 chunks | 6.0732 | 6.0732 | 6.0628 |

**gfx1100, regression.** Built against hrx-system 7696b5b3c02a. Qwen3-30B-A3B-Instruct-2507 Q4_K_M on wiki.test.raw, RX 7900 XTX, before and after this commit, four runs each, identical per-chunk values:

| Regime | Before | After | Vulkan |
| --- | ---: | ---: | ---: |
| decode-like, `-ub 1`, 2 chunks | 6.7431 | 6.7431 | 6.7573 |
| prefill-like, `-ub 512`, 32 chunks | 6.0732 | 6.0732 | 6.0760 |

gfx1100 is unchanged by construction: the default template returns the old constant, and the measured values agree to the last digit. The 182 kernel specializations from the CI failure logs also compile with this corpus against hrx-system main (2a13b0bc) via `loom-check`.

No HRX dependency changes; the minimum HRX commit is unchanged.

## Requirements

- [x] I have read and agree with the [contributing guidelines](https://github.com/ggml-org/llama.cpp/blob/master/CONTRIBUTING.md).
- AI usage disclosure: YES. Codex produced the fix; Claude Code performed the gfx1100 regression validation, set up the gfx1151 CI run, and prepared this PR under human review.

* ggml-hrx: adopt exclusively owned Loom link-index builders (#147)

HRX commit 771711d49befd397f10c3c6deb66f1c5c89e5042 removed the Loom link-index builder create/release API, breaking the JIT build. Use allocate/free and require that commit because builders are exclusively owned, while create/retain/release is reserved for reference-counted objects.

Relevant hrx PR: https://github.com/ROCm/hrx-system/pull/1597

* ggml-hrx: reuse block metadata in dense and paired tiled matmul (#148)

Load use optimization for scales etc that are re-used when dequantizing several 16x16 blocks destined for WMMA ops. Specifically, dense and paired gate/up tiled matmul currently reload Q5_K/IQ4_XS block metadata for each K32 group. This change loads it once per K256 block and retains it across the eight groups, explicitly inside each matmul kernel.

## Generic preload & dequantize helper functions?

This was tried, it ends up being pretty ugly. Each kernel really needs explicitly own what gets retained and for how long to reach peak performance and a generic solution pulls against that. Preloading exactly where and exactly what the kernel wants to when it wants to requires an `if/else` block for quantization types can get a little unwieldy but it all gets stripped out by the compiler.

## Validation

- Current inline implementation commit: `4e6fb071096d27af05298157d7d8469cdd329928`.
- Base: `hrx-graph-develop-v2` at `dbe1d6e1a27ea78e432f3da84778ecb591f196a6`.
- Local HRX SDK: `771711d49befd397f10c3c6deb66f1c5c89e5042`; pinned RX 7900 XTX (`gfx1100`).
- Current inline implementation rebuild passed; all 17 CPU-reference cases passed normally and with Loom access + HAL ASAN instrumentation.
- All 19 exact captured configurations (9 dense including fallbacks, 10 paired) compile to byte-identical native `.text` compared with the benchmarked template candidates. No performance rerun is claimed for this source-only refactor; the native-code comparison preserves the link to the recorded timings.
- Separate candidates previously passed 36 dense/16 gate native compile checks and 18 dense/20 gate exact captured-config checks. No spills; captured Qwen fallback machine code unchanged.
- All 30 baseline/dense/gate model perplexity runs matched printed estimates (five models, prefill and decode). These are independent-candidate results, not a combined performance claim.

## Direct kernel measurements

Actual Llama 3.2 3B production entry points/configurations, 512 tokens, original model weights and identical deterministic nonzero synthetic activations. Ten alternating before/after process pairs. Batch-normalized host queue-completion time per dispatch, batch16, binding ring8; compilation and warmup excluded. Speedup is before/after throughput; 95% intervals use paired log ratios.

| Kernel | Before | After | Speedup (95% CI) |
|---|---:|---:|---:|
| dense_q5 | 956.7 us | 868.0 us | +10.22% [+9.80, +10.65] |
| gate_q5 | 2303.0 us | 1928.9 us | +19.39% [+18.02, +20.79] |
| gate_iq4 | 2173.8 us | 1879.6 us | +15.65% [+15.14, +16.16] |

Dense shape K8192/N3072; paired shapes K3072/N8192. These differ in shape and epilogue, so this is not an isolation of the cause of their different gains.

## Independent model measurements

Original UD-Q4_K_XL models, pp512, ten alternating process pairs with five repetitions each, same GPU/toolchain. Per-model 95% intervals are exploratory and unadjusted. No outliers removed; pilots excluded. Columns compare each change independently against the baseline; gains must not be added together.

| Model | Dense change (95% CI) | Gate/up change (95% CI) |
|---|---:|---:|
| llama-3.2-1b-instruct | +1.14% [+0.14, +2.16] | +7.63% [+6.28, +9.00] |
| llama-3.2-3b-instruct | +0.44% [-0.03, +0.92] | +5.58% [+5.19, +5.98] |
| qwen3.5-0.8b | -0.21% [-0.83, +0.42] | +1.36% [+0.90, +1.81] |
| qwen3.5-2b | +0.23% [-0.36, +0.84] | +3.81% [+3.43, +4.20] |
| smollm3-3b-128k | +0.45% [+0.14, +0.75] | +4.46% [+4.14, +4.77] |

Every model exercises five affected Q5 dense residual dispatches and nine or ten affected paired Q5/IQ4 dispatches. Decode does not exercise these tiled reuse paths. Dense IQ4 has focused numerical/compiler coverage, not a model-level speedup claim. No broad split-count sweep or other-GPU performance claim.

## ggml-staging-automation

Current [ggml-staging-automation CI run 38642793413](https://github.com/ROCm/ggml-staging-automation/actions/runs/38642793413) is queued, with smoke benchmarks and perplexity enabled (`skip_benchmarks=[]`). Staging commit `ce208c65eda6a1ab75d978ed372fb90840d7033f` pins this PR's inline revision `4e6fb0710` and retains HRX `dbda3434868da87540e7e093314c3f4dca867930`. Staging uses a different SDK from the local timings, and no passing staging result is claimed yet.

The [earlier run 38635190536](https://github.com/ROCm/ggml-staging-automation/actions/runs/38635190536) targeted the superseded template commit and was canceled.

Local raw evidence is retained under `build/decoder-reuse-head-refresh/`: `timing/paired-summary.json`, `timing/evidence.txt`, `kernel-timing/kernel-summary.json`, `combined/correctness-{normal,access}.{json,log}`, and each arm's native reports. These workspace paths are provenance notes, not publicly accessible artifact links. The staging run supplies shareable CI evidence.

* ggml-hrx: reuse IQ3_S metadata and Q5 loads (#150)

## Overview

Retain reusable IQ3_S metadata and Q5 headers/payloads across repeated work in HRX kernels, following the format-specific preload/fallback structure introduced in #148. This reduces repeated loads and decoding while preserving generic fallbacks and numerical operation order.

The IQ3_S metadata preload uses byte-aligned loads: the metadata at offset 106 in a 110-byte block cannot promise four-byte alignment. This fixes an alignment error found during integration.

## Scope

The hidden-2048 RMSNorm retained-input specialization was removed in `ba5cf74512097303b19f5518760ce9a78370fdb7`; `rmsnorm_binary_f32_f16.loom` exactly matches the PR baseline. Generic caller-parameterized RMSNorm unrolling is a separate workstream. This PR now changes only IQ3_S metadata and Q5_K header/payload reuse.

## Reproduced local benchmark results

Compared exact revised head `ba5cf74512097303b19f5518760ce9a78370fdb7` against `43b0ec2c41cc671cc0add797a4b8c0aae87b2f1a` (includes #148), on Radeon RX 7900 XTX (gfx1100), with the original pinned HRX `61c152ac4b40dd758803a2cbcd237184a8dfb669` SDK and ROCm/toolchain. The original baseline binary/SDK hashes were verified; the revised candidate was rebuilt with the original build options. All 27 original manifest model files were SHA256-verified.

- Clean run: October 21, 2026, 00:08:27–01:14:31 UTC; 756/756 fresh-process calls succeeded. 540 scored calls and 216 control calls cover 54 model/mode comparisons.
- Same original protocol: llama-bench pp512/tg128, 8 threads, batch 512, microbatch 512, full GPU offload, 5 inner repetitions per process. Default warmup enabled: a full 512-token prompt pass for prefill and one generated token for decode, outside measured repetitions. Five balanced ABBA blocks give 10 disjoint process pairs per model, with 4 baseline control pairs. Original deterministic model order.
- Seven decode gains (+0.73% to +1.71%) survive simultaneous 95% intervals across all 54 comparisons; Holm correction agrees. All seven are positive in both AB/BA order subsets and five-block sensitivity intervals. No prefill change or regression survives the same threshold. Three additional comparisons are nominal improvements only; all remaining results are inconclusive. Inconclusive does not establish equivalence.
- Same-arm adjacent control variation reached 2.67% for prefill and 2.74% for decode; maximum absolute before/after baseline drift was 1.36% and 0.90%, respectively. Effects below use paired log ratios, not comparison of unpaired aggregate means. Inner repeats are not independent observations.
- An earlier 241-call attempt (29 load failures) overlapped confirmed GPU activity from an independent MTP correctness investigation. It was excluded **in full**, with raw results retained. The full original schedule was restarted after both GPU workstreams confirmed release. All reported results come from the single clean restart; no individual scores were selected and no outliers removed. The shared exclusive GPU lock was held throughout scoring.

The same seven models improved in the earlier combined-patch measurement, with effects of similar magnitude. This is a reproduction of the reduced changeset's gains; separate-session differences do not isolate RMSNorm's contribution.

<details>
<summary>Full 27-model prefill/decode results for revised head (simultaneous 95% confidence intervals)</summary>

Rates are arithmetic means of process means. Percentage changes use paired log ratios; intervals use Bonferroni across 54 comparisons. AB/BA order, five-block sensitivity, controls, drift and Holm diagnostics were retained alongside raw measurements.

| Model | Mode | Baseline tok/s | Candidate tok/s | Paired delta | Simultaneous 95% CI |
|---|---|---:|---:|---:|---:|
| qwen3-30b-a3b-instruct-2507 | pp512 | 4661.02 | 4662.73 | +0.037% | [-0.288, +0.362]% |
| qwen3-30b-a3b-instruct-2507 | tg128 | 198.89 | 198.44 | -0.226% | [-1.078, +0.633]% |
| gemma-4-12b | pp512 | 2675.80 | 2675.59 | -0.008% | [-0.143, +0.128]% |
| gemma-4-12b | tg128 | 62.92 | 64.00 | +1.712% | [+1.453, +1.971]% |
| llama-3.1-8b | pp512 | 5039.77 | 5035.94 | -0.076% | [-0.312, +0.161]% |
| llama-3.1-8b | tg128 | 129.11 | 129.15 | +0.038% | [-0.066, +0.142]% |
| minicpm5-1b | pp512 | 29712.67 | 29596.55 | -0.393% | [-1.567, +0.795]% |
| minicpm5-1b | tg128 | 537.07 | 537.01 | -0.011% | [-0.702, +0.684]% |
| minicpm3-4b | pp512 | 5313.59 | 5300.23 | -0.256% | [-2.739, +2.290]% |
| minicpm3-4b | tg128 | 67.34 | 67.32 | -0.023% | [-0.665, +0.623]% |
| minicpm-v-4.6 | pp512 | 26316.86 | 26365.37 | +0.184% | [-0.742, +1.119]% |
| minicpm-v-4.6 | tg128 | 408.73 | 409.13 | +0.100% | [-0.174, +0.374]% |
| minicpm-v-4.6-thinking | pp512 | 26425.27 | 26560.66 | +0.514% | [-0.466, +1.503]% |
| minicpm-v-4.6-thinking | tg128 | 409.87 | 409.85 | -0.005% | [-0.290, +0.280]% |
| qwen3-0.6b | pp512 | 30620.85 | 30593.63 | -0.088% | [-2.153, +2.021]% |
| qwen3-0.6b | tg128 | 460.46 | 460.33 | -0.027% | [-0.602, +0.552]% |
| gemma-3-270m-it | pp512 | 52961.82 | 53586.24 | +1.181% | [-0.921, +3.328]% |
| gemma-3-270m-it | tg128 | 456.47 | 453.33 | -0.663% | [-4.186, +2.990]% |
| qwen3-1.7b | pp512 | 12439.81 | 12377.94 | -0.495% | [-2.034, +1.068]% |
| qwen3-1.7b | tg128 | 317.14 | 316.50 | -0.204% | [-0.766, +0.362]% |
| qwen3-4b | pp512 | 4723.80 | 4721.72 | -0.045% | [-1.007, +0.927]% |
| qwen3-4b | tg128 | 183.51 | 183.67 | +0.086% | [-0.311, +0.484]% |
| qwen3-4b-instruct-2507 | pp512 | 8508.20 | 8500.54 | -0.090% | [-0.814, +0.641]% |
| qwen3-4b-instruct-2507 | tg128 | 183.73 | 183.65 | -0.047% | [-0.728, +0.638]% |
| bonsai-8b | pp512 | 2571.80 | 2572.18 | +0.015% | [-0.363, +0.394]% |
| bonsai-8b | tg128 | 158.08 | 158.04 | -0.025% | [-0.345, +0.297]% |
| bonsai-4b | pp512 | 5004.24 | 5021.44 | +0.348% | [-1.306, +2.029]% |
| bonsai-4b | tg128 | 222.83 | 222.58 | -0.115% | [-1.236, +1.018]% |
| bonsai-1.7b | pp512 | 12405.81 | 12413.46 | +0.061% | [-0.977, +1.111]% |
| bonsai-1.7b | tg128 | 358.11 | 359.09 | +0.270% | [-1.203, +1.765]% |
| phi-4-mini-instruct | pp512 | 9842.45 | 9851.63 | +0.093% | [-0.217, +0.405]% |
| phi-4-mini-instruct | tg128 | 189.14 | 191.45 | +1.223% | [+0.922, +1.525]% |
| lfm2-1.2b | pp512 | 28715.64 | 28738.45 | +0.081% | [-1.036, +1.212]% |
| lfm2-1.2b | tg128 | 523.44 | 523.23 | -0.042% | [-0.239, +0.156]% |
| lfm2.5-1.2b-instruct | pp512 | 28544.30 | 28540.05 | -0.018% | [-4.134, +4.274]% |
| lfm2.5-1.2b-instruct | tg128 | 523.25 | 523.56 | +0.058% | [-0.323, +0.440]% |
| promptbridge-0.6b-alpha | pp512 | 34693.11 | 34681.71 | -0.041% | [-2.906, +2.907]% |
| promptbridge-0.6b-alpha | tg128 | 442.55 | 443.57 | +0.230% | [-0.228, +0.691]% |
| jan-nano-128k | pp512 | 8523.09 | 8522.00 | -0.013% | [-0.503, +0.479]% |
| jan-nano-128k | tg128 | 184.08 | 184.18 | +0.052% | [-0.692, +0.802]% |
| jan-v1-4b | pp512 | 8529.04 | 8543.25 | +0.167% | [-0.329, +0.665]% |
| jan-v1-4b | tg128 | 183.89 | 184.26 | +0.198% | [-0.374, +0.772]% |
| llama-3.2-1b-instruct | pp512 | 19935.02 | 19902.70 | -0.166% | [-2.545, +2.272]% |
| llama-3.2-1b-instruct | tg128 | 470.43 | 475.08 | +0.990% | [+0.764, +1.216]% |
| llama-3.2-3b-instruct | pp512 | 9236.47 | 9238.47 | +0.022% | [-0.387, +0.432]% |
| llama-3.2-3b-instruct | tg128 | 227.63 | 229.28 | +0.725% | [+0.501, +0.950]% |
| smollm3-3b-128k | pp512 | 8470.96 | 8477.20 | +0.073% | [-0.324, +0.472]% |
| smollm3-3b-128k | tg128 | 217.14 | 218.73 | +0.730% | [+0.558, +0.902]% |
| ministral-3-3b-instruct-2512 | pp512 | 11015.70 | 11014.01 | -0.015% | [-0.472, +0.444]% |
| ministral-3-3b-instruct-2512 | tg128 | 233.78 | 233.97 | +0.080% | [-0.492, +0.654]% |
| qwen3.5-0.8b | pp512 | 24610.85 | 24617.16 | +0.027% | [-1.608, +1.690]% |
| qwen3.5-0.8b | tg128 | 387.55 | 390.49 | +0.757% | [+0.400, +1.116]% |
| qwen3.5-2b | pp512 | 13809.41 | 13829.31 | +0.144% | [-0.301, +0.591]% |
| qwen3.5-2b | tg128 | 263.97 | 267.56 | +1.360% | [+1.003, +1.718]% |

</details>

## Correctness and CI provenance

For the revised head, the restored RMSNorm kernel was linked and compiled for gfx1100 (H2048,multiply,T9), both benchmark arms passed separate unscored loader/device smoke checks, and the diff passed whitespace checks. An initial smoke check failed to locate libomp because the historical build used the old workspace path; adding the original ROCm llvm/lib directory to both arms' library search path resolved it. No binary or SDK substitution was made.

No new full-model perplexity campaign or ggml-staging-automation run was requested or performed. The following evidence is historical and applies to combined commit `01d0a3ad5054231298806d547eae33c283336a70`, which included RMSNorm retention:

- [Full ggml-staging-automation CI — successful attempt 3](https://github.com/ROCm/ggml-staging-automation/actions/runs/38806373681/attempts/3).
- All 27 expected-pass manifest models passed unchanged local CI-equivalent perplexity on both arms: 108 HRX/Vulkan comparisons, 216 measurements; maximum ratio 1.00655 against threshold 1.10. Prefill c512/b512/ub512/32chunks; decode c512/b512/ub1/2chunks. Expected-fail/report-only models excluded as documented in the frozen manifest.
- Captured production/tail checks, alignment fixtures and 36/36 fallback checks passed. Focused checks 52/56 passed; four failures were the same inherited IQ3_S K2048/N256/T32 synthetic mismatch on both arms in normal/access modes, with all 8192 outputs bit-identical. The discrepancy remains unresolved; tolerances were not relaxed.

## Requirements

- Contributing guidelines reviewed; draft submitted for human review and ownership of the changes.
- AI usage disclosure: YES. Codex assisted with investigation, implementation, testing, statistical analysis, and drafting this PR under the contributor's direction.

* ggml-hrx: unify MoE partition descriptors and cover all experts (#153)

## Overview

Fix HRX inference for Qwen3.5-35B-A3B-MTP-GGUF, which faults during multi-token prefill and produces decode perplexity around 19.8 million in [the failing run](https://github.com/ROCm/ggml-staging-automation/actions/runs/38806373681).

The router packs expert partitions using the legacy 7-bit expert layout, while the generic expert matmul reads a 9-bit layout. This turns valid descriptors into out-of-bounds row offsets. The router also launches only 128 partition-builder threads for a model with 256 experts.

Use a shared 9/6/5-bit expert/partition/row-count layout across generic and specialized consumers, including the fused partition producer, and launch one partition-builder thread per supported expert. Update compiler fixtures and CPU references together.

Add end-to-end router-to-matmul regressions for 128, 256, and 512 experts with 1, 2, and 512 tokens, including high expert IDs, multirow partitions, and graph replay.

## Validation

[Single-model, perplexity-only upstream gfx1151 run](https://github.com/ROCm/ggml-staging-automation/actions/runs/39495823554): **PASS**, with the model's expected-failure exemption removed. Artifact metadata confirms this fix commit and HRX runtime `4341b71ab812e618b92b016176528363718e6667`.

| Regime | HRX perplexity | Vulkan perplexity |
| --- | ---: | ---: |
| Prefill: context/batch/ubatch 512, 32 chunks | 5.4237 | 5.4282 |
| Decode: context/batch 512, ubatch 1, 2 chunks | 6.0322 | 6.0373 |

Local gfx1100 validation:
- All 9 new regression cases pass; the 256-expert one-token regression fails with the original backend.
- All 7 existing specialized MoE/router checks and 3 focused dispatch/fused-partition checks pass.
- JIT compile checks: 5/5 pass.
- Full backend suite: 95/99 pass. The four failures reproduce on unmodified upstream: `rope_set_rows_dispatch`, `generic_swiglu_k16_publication_edges`, `tiled_matmul_alternate_publish`, and `rmsnorm_binary_k16_output`.
- Full JIT suite including device materialization: 5/6 pass. The concat topology-range compile failure also reproduces on unmodified upstream.

The single-model automation manifest is on a separate validation branch and is not part of this PR.

## Requirements

- [ ] I have read and agree with the [contributing guidelines](https://github.com/ggml-org/llama.cpp/blob/master/CONTRIBUTING.md). Contributor confirmation pending.
- AI usage disclosure: YES. Codex assisted with root-cause investigation, implementation, regression coverage, validation, and this draft PR.

* hrx: publish decode attention output before Q8 packing (#154)

## Motivation

Fixes required to bump [`hrx-graph-develop-v2`](https://github.com/AMD-Ecosystem/llama.cpp/tree/hrx-graph-develop-v2) up to hrx-system: https://github.com/ROCm/hrx-system/commit/5f4dfc8731a1b37fdd380c566c7babf7ae3548cd.

Decode attention writes F32 results into global memory, then Q8 packing reads values written by other lanes. The intervening barrier fenced workgroup memory only. Fence global memory before packing in both reduction paths to prevent stale values from producing nonfinite Q8 scales and NaN perplexity.

This appears to be a pre-existing llama.cpp synchronization bug, not a newly introduced HRX regression. The previous green PR105 package uses the same llama.cpp revision and older HRX `4341b71`; it also reproduces the failure locally. Newer HRX may have made the race more common by changing execution timing or generated code, but the controlled local comparison did not establish that: older and newer packages both produced NaNs in all ten alternating fresh-process repetitions. A second local comparison used the September 29 package from https://github.com/ROCm/ggml-staging-automation/actions/runs/36638317205, whose saved report explicitly passed this exact model and checksum with decode PPL 10.0045. That package (HRX `32b86d4`, llama.cpp `2ba2ddc`) and the current unfixed package each failed 10/10 alternating repetitions locally. Its llama.cpp revision differs, so this is a historical package comparison rather than an HRX-only comparison. Both old reduction paths already contain the same workgroup-only pre-packing barriers. Neither local comparison provides evidence of an increased failure rate with newer HRX.

No introducing HRX commit is attributed. The HRX PR referenced by the fix commit documents the barrier API, not the introduction of this bug.

### Breaking changes

| Breaking hrx-system PR | Fix |
| --- | --- |
| None identified; pre-existing llama.cpp race | https://github.com/AaronStGeorge/llama.cpp/commit/103a47dd80e760f00c4421f6c2d03c6d26b64977 |

## Testing

Tested in `ggml-staging-automation` full all-model CI with llama.cpp `103a47dd80e7` and hrx-system `5f4dfc8731a1`.

- Bump PR: https://github.com/ROCm/ggml-staging-automation/pull/108
- Full all-model CI: passed on strixhalo-10, https://github.com/ROCm/ggml-staging-automation/actions/runs/39701697708, staging head `1bad5e0d6acb`. The release benchmark and security checks passed. Llama-3.2-1B-Instruct decode PPL was 10.0408 +/- 1.32270; prefill PPL was 14.4414 +/- 0.45819. Both numerical checks and Vulkan references passed. The staging workflow supplies missing GPU device groups on canary runners and launches benchmarks with refreshed membership; no model expectations were changed.
- Focused numerical validation: https://github.com/ROCm/ggml-staging-automation/actions/runs/39519720454. On DT241, DT243, and strixhalo-10, the original package failed 5/5 repetitions per host and the fix passed 5/5. Fixed decode PPL was 10.0408 +/- 1.32270; prefill PPL was 14.4414 +/- 0.45819. Vulkan reference checks passed. The run was red because DT245 could not initialize either package; it produced no model measurements.
- Local CPU decode reference: 10.0388 +/- 1.32349. All 37 existing attention tests passed.
- Compatibility floor remains `771711d49befd397f10c3c6deb66f1c5c89e5042`. Rebuilt HRX, Loom, the backend, and embedded kernel bytecode at that floor and ran the same fixed decode command successfully: PPL 10.0408 +/- 1.32270.
- Reproduction command: `ROCR_VISIBLE_DEVICES=0 llama-perplexity -m Llama-3.2-1B-Instruct-UD-Q4_K_XL.gguf -f wiki.test.raw -c 512 --chunks 2 -b 512 -ub 1 --device HRX0` on gfx1151. Model and corpus are the pinned, checksum-verified inputs in the staging manifest.

Device initialization hangs are separate from this numerical fix. DT239's captured stacks block in ROCr `BlitKernel::SubmitLinearCopyCommand` during HRX device-library initialization with both packages, even with Vulkan disabled, before any model executes. The underlying cause of that runtime hang is unresolved.

Historical endpoint search for a llama.cpp frequency bisect: the September 7 package cannot execute this model's Q5_K matrix multiplication; September 16 produces PPL 41875.0725; September 23 produces NaNs. None is a locally correct good endpoint. Source history places the workgroup-only pre-packing barriers in `f43c5b4d9` (August 28), the initial Llama support change. This is source-history attribution of the missing fence, not a completed runtime bisect or proof of a later frequency increase.

* ggml-hrx: fix suite dispatch expectations and concat bounds (#156)

## Overview

The packaged HRX suites fail 16 cases at the current backend pin. This fixes concat launch-bound compilation and updates stale dispatch expectations while retaining numerical comparisons and negative coverage.

- Reuse the concat bound fix and dynamic-reuse regression from #155; the existing element limit guarantees at most 4,194,304 workgroups.
- Check the current RoPE capacity class, aligned publication kernels, IQ2_S specialization, and low-token RMSNorm selection.
- Explicitly verify rejection of in-place RMSNorm, matching the kernels' no-alias contract.
- Verify supported Gemma Add-before-Add fusion parameters and add CPU-reference coverage.

## Additional information

Validated on gfx1100 with HRX `5f4dfc8731a1b37fdd380c566c7babf7ae3548cd`: **436 passed, 0 failed** across buffer (5), backend (99), JIT (6), and ops (326). CTest wall time was 62.09 seconds with two concurrent suites and internal worker counts 1/4/2/4. Three standard backend CONCAT CPU-comparison cases also passed. Numerical tolerances were unchanged.

gfx1151 CI qualification **passed: 436 cases, 0 failures, 59.03 seconds CTest wall time**: [workflow run 40393012701](https://github.com/ROCm/ggml-staging-automation/actions/runs/40393012701), testing this PR's exact backend commit `0230f1b29ee2d009602a7b2c6cbce64f1b1290d2` through the packaged test workflow. The separate packaging integration is ROCm/ggml-staging-automation#110. This PR overlaps only the concat fix/regression in #155; it does not include that PR's recurrent-state changes.

## Requirements

- [ ] I have read and agree with the [contributing guidelines](https://github.com/ggml-org/llama.cpp/blob/master/CONTRIBUTING.md) (contributor confirmation).
- AI usage disclosure: YES. Codex investigated the 16 failing cases through sequential subagents, reviewed the changes, and ran focused and full-suite validation. The user requested this submission.

* ggml-hrx: normalize test names and CTest invocation (#157)

## Overview

Normalize the HRX suite source, target, executable, and CTest names to `hrx-*-test`. Label the four suites `hrx` and put their complete invocation in CTest: workers 1/4/2/4, full case selection and output, a 900-second timeout, and failure on missing-device skips. Suite concurrency stays caller-controlled.

Document discovery through `ctest -L '^hrx$' --show-only=json-v1`: test names identify build targets before building, and commands/properties supply packaging and execution metadata afterward. Numerical assertions and case registrations are unchanged.

## Validation

- Built all four targets in a separate Release build against HRX `5f4dfc8731a1b37fdd380c566c7babf7ae3548cd`.
- Full CTest run with `--parallel 2 --verbose` on gfx1100: all four suites passed (buffer 5, backend 99, Loom JIT 6, ops 326 cases).
- Verified JSON discovery contains exactly four renamed suites with the expected executable paths, arguments, timeout, and failure regex.
- Missing-device buffer run fails through the registered failure regex (CTest exit 8).
- Verified all case registrations and numerical assertions are unchanged; `git diff --check` passes.

## Requirements

- Contributing guidelines reviewed; this draft targets the AMD-Ecosystem development fork under explicit user authorization.
- AI usage disclosure: YES. Codex implemented the naming/CTest changes and ran validation. Human review remains required before merge.

* ggml-hrx: fix concat launch bounds and recurrent MTP snapshots (#155)

## Overview

Fix two HRX failures encountered while running Qwen3.5-35B-A3B-MTP-GGUF with multi-token drafting:

- Give the dim-0 concat launch count an explicit range so Loom can compile the 2048+2048 hidden-state concat used by MTP. Add dynamic executable-reuse coverage for 1 and 128 rows.
- Compute recurrent snapshot decay ratios as `exp(log_decay_j - log_decay_i)` in both fused Gated DeltaNet snapshot publication paths. Dividing cumulative exponentials could produce `0/0` after underflow, corrupting saved states used for speculative rejection/rollback.

Add CPU-reference regressions for attention and every saved state with 2 through 5 verification tokens, ordinary and underflowing decay, fused dispatch, and repeated graph execution. The snapshot regression fails with NaNs for 3 through 5 tokens before the fix.

## Additional information

Prior validation on gfx1100 (RX 7900 XTX):
- Focused HRX ops: 5/5 pass, including all four snapshot cases and dynamic generic ops.
- Loom JIT suite passes, including the new concat workloads.
- Full-model drafting lengths 2, 3 and 4 pass repeated requests and a 477-token prefill. Default length 3 matches all three non-MTP baseline texts; traces cover full, partial and zero acceptance with recurrent rollback and no checkpoint fallback. Lengths 2/4 match counting and arithmetic; open-ended chat has minor wording differences.

Rebased onto `hrx-graph-develop-v2` at 7fd4e515d with an identical patch; whitespace checks pass. GPU tests have not been rerun after this rebase. gfx1151 validation remains outstanding.

Follows the MoE-routing fix in #153, already on the target branch. Lemonade automatic MTP enablement and ROCm/ggml-staging-automation#109 are separate changes; this PR contains only the backend kernels and their regressions.

## Requirements

- [ ] Contributor confirmation: I have read and agree with the [contributing guidelines](https://github.com/ggml-org/llama.cpp/blob/master/CONTRIBUTING.md).
- AI usage disclosure: YES. Codex assisted with investigation, implementation, regression tests, validation and preparation of this draft at the contributor's request.

* ggml-hrx: adapt to latest upstream and HRX interfaces

* hrx: preserve caller inputs during metadata initialization (#162)

Port the focused fix from 602f1204e onto the upstream-rebase branch. Keep initializer accesses for uploads and hazards, but copy back only writes made by main commands. Add the replay regression for deferred input replacement, outputs, in-place writes, and prepared-cache reuse.

Assisted-by: Codex
(cherry picked from commit a5bf921a985725866b23b18dc8592b48a95c8f90)

* ggml-hrx: restore correctness after upstream interface rebase (#163)

* hrx: preserve caller inputs during metadata initialization

Port the focused fix from 602f1204e onto the upstream-rebase branch. Keep initializer accesses for uploads and hazards, but copy back only writes made by main commands. Add the replay regression for deferred input replacement, outputs, in-place writes, and prepared-cache reuse.

Assisted-by: Codex
(cherry picked from commit a5bf921a985725866b23b18dc8592b48a95c8f90)

* ggml-hrx: restore recurrent RMS-scale normalization fusion

Recognize the rebased GDN Q/K normalization graph and preserve its additive epsilon semantics while retaining L2 clamp support. Cover CPU-reference numerics, snapshot/projection entry points, and fusion boundaries.

Bead: lemonade-ws-7mt.1

Assisted-by: Codex
(cherry picked from commit 48263e20267d8328ea8e79e403afe38f9b184e5d)

* hrx: preserve RoPE offsets for MiniCPM3 queries (lemonade-ws-7mt.3)

Assisted-by: Codex
(cherry picked from commit 9791711cfdd0f6264cd7b5837154bcf4b939fd2c)

* hrx: honor compute masks in graph import and replay caches

Skip inactive branch storage and scheduling, invalidate cached programs when branch selection changes, and preserve compute masks in graph snapshots. Add host and device regressions for inactive SET_ROWS and stable-UID selection changes.

Assisted-by: Codex
(cherry picked from commit 760fe39af35d424745bc4b4f4cc293c406623065)

* hrx: keep contiguous F32 duplicates on the device (#164)

## Summary

Keep contiguous F32 `DUP` operations on HRX by reusing the existing copy dispatch. The mixed-embedding input duplicate otherwise runs on CPU and introduces a backend boundary. Advertise support only for nonempty contiguous F32 tensors with matching shapes, a distinct contiguous output, and at most 2^30 elements. Extend the existing CPU-reference test to execute and compare the duplicate.

This is one commit on `hrx-graph-develop-v2` at `2120f7434eeb8d958cd0c0fab3be581e12a8f29b` (after #162 and #163), cherry-picked from `73f49408113923d48bcb7df7602cf43075dc2900`.

## Performance against the current base

Local before/after measurements used the Radeon RX 7900 XTX (`gfx1100`), Qwen3-0.6B Q4_0, context 4096, one slot, 16 CPU threads, and a 17-token prompt. Both builds used `sources/build.py` and the same HRX revision, `82214dfb029975205d1c3a59164b678e2e21fc41`. The only source difference for this comparison is the DUP patch. Each server handled three 20-token requests followed by three warm 256-token requests.

The before-DUP source tree at `760fe39af` is identical to the current target branch at `2120f7434`. The after-DUP tree is identical to this PR.

| 256-token generation | Base, ms | Base + DUP, ms |
| --- | ---: | ---: |
| Warm request 1 | 715.798 | 669.302 |
| Warm request 2 | 622.058 | 596.952 |
| Warm request 3 | 608.892 | 585.599 |
| Mean | 648.916 | 617.284 |

This is **5.12% higher throughput**, or 4.87% less generation time, for these warm requests. Generated text was byte-identical before and after. Scheduler diagnostics showed three partitions (HRX / CPU / HRX) becoming one HRX partition, removing the CPU F32 DUP (4 KiB for a single-token input).

These are three sequential warm requests from one server session per version. The result is a limited local measurement, without repeated alternating sessions or a confidence interval. The separate compiler optimizations are not included; their previously reported 2.71x gain does not quantify this change.

## Validation

- Local `build.py` build passed on pinned gfx1100.
- Local `test-backend-ops` F32 DUP comparison passed against CPU; unsupported types and noncontiguous inputs remained rejected.
- The existing `dynamic_generic_ops.cpu_reference` test now checks HRX placement, copy-kernel selection, and exact numerical agreement for the active DUP.
- **Completed single-model CI:** [41059144662](https://github.com/ROCm/ggml-staging-automation/actions/runs/41059144662), SUCCESS on gfx1151. Qwen3-0.6B chat checks, prefill/decode perplexity comparisons, and all four packaged HRX suites passed. Perplexity was HRX 20.4920 / Vulkan 20.4695 for prefill and HRX 19.2819 / Vulkan 19.2796 for decode.
- **Completed full-tier CI:** [41061540987](https://github.com/ROCm/ggml-staging-automation/actions/runs/41061540987), SUCCESS: all 31 HRX chat cases and 30 perplexity models passed their underlying checks, plus all four packaged HRX suites.

Both CI runs used staging `c6985eaf0ad6f254f973ed122d46e6faec610eb6`, llama.cpp `73f49408113923d48bcb7df7602cf43075dc2900`, and unchanged HRX `82214dfb029975205d1c3a59164b678e2e21fc41`. This PR head `6945a7fe669a84c68b842a894e7759f1773848e0` and the tested llama.cpp revision have exactly the same Git source tree, `a1356018805a971e51fa8de997987117e083ad94`; only commit history differs. The existing single-model run therefore covers the proposed source state, and no duplicate run was dispatched. CI timings are not used to claim an isolated DUP speedup.

Assisted-by: Codex

* ggml-hrx: add opt-in compilation diagnostics (#165)

## Overview

Add `GGML_HRX_TRACE_COMPILE=1` to diagnose runtime kernel compilation during prefill and decode. It emits JSON records to stderr with graph execution and cache IDs, kernel keys and specialization parameters, compiler timing, failures, and unresolved-compilation waits. Asynchronous compiler events retain their originating execution ID. Graph-end records include zero compilation counts so repeated cycles can show cache reuse.

The caller chooses the workload and repetitions. Records are informational; backend graph IDs do not claim to identify token steps or prefill/decode phases. Existing asynchronous compilation and graph replay remain intact. Disabled tracing adds cached-state checks without timestamps, JSON construction, logging locks, or file I/O.

All changes are inside `ggml/src/ggml-hrx`. The README documents activation, events, timing limits, and JSON extraction.

## Validation

Built `llama-bench`, `hrx-backend-test`, and `hrx-loom-jit-test` with HRX `82214dfb029975205d1c3a59164b678e2e21fc41` on a pinned gfx1100 GPU.

- Llama-3.2-1B-Instruct UD-Q4_K_XL, `-p 0 -n 0 -pg 64,16 -b 64 -ub 64 -r 2 --no-warmup --progress`: async and sync JIT both produced 68 backend graph executions and 43 initial compilation requests. Counts for the first four graphs were `[1, 23, 1, 18]`; all remaining graphs, including the entire second cycle, requested zero compilations.
- Parsed records to reconcile graph counts and match request/begin/end identities, timestamps, originating executions, and wait attribution. Sync and async compiled identical keys. Async recorded 16 waits; sync recorded none, as expected.
- Existing backend cases `add_f32`, `scale_f32`, and both `same_uid_distinct_graph_reuses_graph_program` variants: 4 passed with tracing disabled and 4 passed with tracing enabled. Disabled tracing emitted no trace records.
- Deliberately invalid `GGML_HRX_LOOM_SANITIZER` produced a matching failed compile-end record with `compiler_started=false`, the initialization error, and a failed graph-end record.
- Modified translation-unit syntax checks and `git diff --check` passed. The full backend suite was not run.

The existing compatibility floor is stale and is being corrected separately. Validation used the compatible HRX revision above; this PR does not change that floor or migrate kernel syntax for newer HRX revisions.

## Requirements

- Reviewed the contributing guidance; this submission targets the AMD-Ecosystem fork.
- AI usage disclosure: YES. Codex implemented, reviewed, and tested the change and prepared this PR under user direction.

* ggml-hrx: materialize weights on demand and keep them resident (#160)

# Problem

On `hrx-graph-develop-v2`, standard GPU model loading makes the native weight representation resident up front. When a kernel requests a repacked layout, HRX materializes an additional GPU allocation while keeping the original native weights resident. A repacked weight therefore occupies **both native and repacked storage, even if no selected kernel needs the native layout**. The original allocation is unconditional; the repack is added on demand.

This duplication consumes memory that should be available for KV cache and execution buffers. On the tested 24 GiB RX 7900 XTX, **Qwen3.8-27B Q4_K_M** (16.55 GiB GGUF) and **Mistral-Small-3.2-24B Q4_K_M** (13.35 GiB GGUF) cannot complete Lemonade `chat-long-output` at context 4096 with the tested HRX offload settings, despite their model files being substantially smaller than the GPU's capacity. Baseline failures explicitly report HSA resource exhaustion while allocating the transient arena.

# Solution

**Materialize weights on demand and keep each requested representation resident.** Ordinary imported GGUF weights describe borrowed, immutable source bytes without eagerly creating a GPU copy. When a selected command first requests a weight layout, the cache materializes that representation, allocates its GPU storage, and uploads it. Later requests and prefill/decode transitions reuse the cached allocation. Unused layouts are never materialized. Existing directly bindable coherent storage is reused, and uploaded device weights, CPU weights, and HRX host buffers retain their native-only eligibility r…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant