Skip to content

kv share: a provider in another process maps the region as fds, the decoder adopts the cells (TZEROCOPY target 1, step 2) - #164

Merged
bong-water-water-bong merged 4 commits into
1bit/hrx-vulkan-patchedfrom
1bit/kv-share-fds
Nov 1, 2026
Merged

bong-water-water-bong merged 4 commits into
1bit/hrx-vulkan-patchedfrom
1bit/kv-share-fds

Conversation

@bong-water-water-bong

@bong-water-water-bong bong-water-water-bong commented Nov 1, 2026 •

Copy link
Copy Markdown

kv share: the region crosses processes as fds (target 1, step 2)

#163 made the shared KV region work with the provider and the decoder in one process, because that was the
only way the region could travel. This carries it out: the decoder exports, a unix socket carries the
dma-buf fds, a provider in another process maps them as its own KV tensors, and the decoder adopts the cells.

Base branch 1bit/hrx-vulkan-patched (as #163 was).

What it adds

  • POST /slots/<id>?action=share {"socket": PATH} — the slot's KV region, exported and sent to PATH as
    {fd, offset, size, layout} per region: one sendmsg carrying a length-prefixed JSON header and
    SCM_RIGHTS. The reply carries the region layout, the context params a provider has to reproduce, and a
    share_id. /proc/<pid>/fd cannot be reopened for a dma-buf on Linux (measured), so a socket is the
    only way the fds reach another process.
  • POST /slots/<id>?action=adopt {"tokens": [...], "share_id": N} — cells 0..N-1 become positions 0..N-1 of
    the slot's sequence with no data movement (llama_kv_cells_adopt), and the slot's prompt is set so the next
    request hits that cache. The share_id is required and single-use: without it a client could adopt cells no
    export just produced, and whatever bytes sat there would silently become a prompt's cache. Both actions are
    new server task types (SLOT_SHARE, SLOT_ADOPT) and run on the context thread like save/restore, so a
    share never races a decode.
  • llama_kv_share_params() — n_ctx, n_batch, n_ubatch, n_seq_max, flash attention and K/V types. The layout
    hash can only say yes or no; this says what to build. K/V types now live in llama_cparams (they were only
    in llama_memory_params, which does not outlive init). The struct is llama_kv_share_cparams because a
    function of the same name shadows it in every TU that includes llama-ext.h.
  • tools/kvshare-prefill — the reference provider, in both transports: --fds prefills into the decoder's
    KV memory, --out writes the sequence state the decoder restores. It is a CPU prefill on purpose: the fd
    plumbing can be gated with no NPU, and the NPU runtime is the same program with its own BO import.

Measured (strixhalo, Qwen3-0.6B-Q4_K_M, ctx 20480, -fa on, greedy 16 tokens)

The decoder is llama-server on HRX0; the provider is llama-kvshare-prefill on the CPU; the engine drives
the handoff. Region 2240 MiB in 3 dma-buf chunks (28 layers × 8 kv heads × 128 × f16 × K+V × 20 480).

prompt tokens file transport: restore shared transport: share + adopt bytes moved by the handoff
251 4 ms 0.43 ms + 0.00 ms 0
3 189 39 ms 0.49 ms + 0.00 ms 0
12 722 198 ms 0.57 ms + 2.00 ms 0

(share is export + the fd handoff, from the engine's stderr line; the file column is the same provider, same
model, same decode, writing a 1.46 GB state file at 12.7k tokens. Server-side export+sendmsg alone is
0.016-0.021 ms.)

The gate: identical greedy text on fd vs file, three prompts at three lengths. That is the transport
check, and it needs the same provider on both sides — which is why kvshare-prefill grew --out. It passes
at 251 / 3 189 / 12 722 tokens. The reply is not always identical to --device hrx: a CPU prefill and an
HRX prefill differ numerically, and the greedy token after a long prompt flips (it matches at 3 189 tokens
and differs at 251 and 12 722 on this model). That is the provider's math, not the handoff — the same CPU
provider through the file route gives the same text as through the fds at every length.

Limits, stated as limits

  • The region is llama_kv_cache: a hybrid model's recurrent half is not shared, and ?action=share refuses
    a hybrid cache rather than hand over half a prompt. Verified, not assumed, on two hybrids: Qwen3.8-Flash-Next
    (linear attention) and the 27B itself (bonsai2-unrot-q4_0, 48 GDN layers) — both answer 501 ("no
    shareable region: either the server was not created with ONEBIT_KV_SHARE=1, or the model is hybrid and its
    recurrent state is not shareable"), the engine falls back, and the request is answered identically
    ('Red, Orange, Yellow' / the same 27B answer on every route). 0 gfxhub faults. The folded ternary 27B cannot
    exercise this — it is hrx-only, so 1bit serve refuses the hybrid route before the handoff is reached.
  • Both sides must be the same pinned llama.cpp, the same model, and the same -fa/-c/-b/-ub/KV types.
    A mismatch is a refusal (share_import checks the layout hash), not a wrong answer.
  • The measured provider is a CPU prefill — a stand-in. The NPU prefill provider is pi-bonsai's lane
    (TBONSAI-SPEED); it maps the same descriptors as XDNA BOs. So these numbers price the handoff, not the
    route: a hybrid still only wins if the provider beats the backend's own prefill, which is the conclusion
    docs/hybrid.md already records.
  • A shared handoff that fails says why and the engine forwards the request as it came.

The environment these numbers were taken in

strixhalo, kernel 7.3.0-rc4-1bit-perfopt+, HRX's HSA runtime = TheRock's nightly libhsa
(/opt/rocm-therock/…/_rocm_sdk_core/lib/libhsa-runtime64.so.1, md5 c455cf0e, 5 141 585 B — what
cmake/hrx.cmake bakes in via ONEBIT_HRX_LIBHSA), and every arm with
HSA_USE_SVM=0 HSA_USERPTR_FOR_PAGED_MEM=0 HRX_ALLOW_NO_SVM=1
.

That last part is not cosmetic: on this runtime the SVM path produces gfxhub PERMISSION_FAULTS: 0x8
(UTCL2 client CPF) from llama-server on some runs — pi-attn pinned it on the SVM path, and the CWSR-style
env above is how every HRX arm runs from now on. The gate run quoted above added 0 gfxhub faults, and a
separate 3-run A/B of the env on vs off found no throughput cost worth the name (122.8 vs 125.4 ms median,
spread 120.6-125.7, identical answers): the workaround is free, which is why it is used everywhere rather
than debated.

Re-run at the final heads of this branch (engine 312592c + fork 39a72359) reproduced the transport gate
(PASS) and 0 gfxhub faults; its absolute times are not quoted because the box was at 54 GB used with 14 lanes
loaded at the time, which inflated the file-side restore to 17/80/513 ms. The numbers in the table are from the
run with the die to itself.

Verified against the merged engine

The engine half is in main (engine ggml-org#714, merge 9e1164a). Re-gated this branch on top of it —
engine 4d56634 + fork 39a723593, five routes, no-SVM env, gpu-hold:

prompt tokens file restore share adopt
251 5 ms 0.29 ms 0.00 ms
3 189 56 ms 0.94 ms 1.00 ms
12 722 208 ms 0.56 ms 2.00 ms

transport gate PASS, 0 gfxhub faults. And the plumbing now has a CI-runnable test on the engine side
(engine ggml-org#740): the fake decoder speaks ?action=share/?action=adopt, the fake provider fails unless it was
handed one readable fd per region, 11 checks, no model/GPU/exporter.

pi-zerocopy added 2 commits October 31, 2026 20:42
…fill into it (target 1, step 2)

#163 left the provider and the decoder in one process, because that is the only way the region could
travel. This adds the plumbing that carries it out: the decoder exports, a unix socket carries the
dma-buf fds, the provider maps them, the decoder adopts the cells. Nothing about the KV ever touches a
file, and the only bytes that cross a process boundary are the fds and a few hundred bytes of JSON.

- server: POST /slots/<id>?action=share {"socket": PATH} exports the slot's KV region and sends
  {fd, offset, size, layout} per region to PATH (AF_UNIX, SOCK_STREAM, SCM_RIGHTS in the same sendmsg as
  a length-prefixed JSON header; Linux cannot reopen a dma-buf from /proc/<pid>/fd, measured). The reply
  carries the region layout and the context params a provider has to reproduce to match it.
- server: POST /slots/<id>?action=adopt {"tokens": [...]} takes cells 0..N-1 as positions 0..N-1 of the
  slot's sequence with no data movement (llama_kv_cells_adopt), and sets the slot's prompt so the next
  request hits that cache. New task types SLOT_SHARE / SLOT_ADOPT run on the context thread like
  save/restore, so sharing never races a decode.
- llama_kv_share_params(): the params a provider needs (n_ctx, n_batch, n_ubatch, n_seq_max,
  flash attn, K/V types), because the layout hash can only say yes or no. Type K/V are now kept in
  llama_cparams (llama_memory_params does not outlive init).
- tools/kvshare-prefill: the reference provider. Maps the fds as its own context's KV tensors
  (llama_kv_share_import -> ggml-cpu's buffer_from_dmabuf), prefills the prompt into them, exits. It is
  a CPU prefill on purpose: the fd plumbing can be gated with no NPU in the loop, and the NPU runtime
  is the same program with its own BO import.
… too

The transport gate needs one variable: how the KV travels. With --out the reference provider prefills
into its own context and writes the sequence state (llama_state_seq_save_file) that the decoder's
?action=restore reads; with --fds it prefills into the decoder's memory. Same model, same math, same
engine -- so identical greedy text on both is a statement about the transport, and the difference from
--device hrx is a statement about the provider's numerics.

@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

Built and exercised at 2742299e9. The plumbing works and fails safely in the cases I could reach without an HRX build; the blocker is a trust boundary the endpoints do not have.

Built: ninja llama-server llama-kvshare-prefill → both link, rc 0 (17 files, +919 −18 over the base).

Exercised on a CPU-only build (so share cannot export; that is the point — it shows the error paths):

call result
POST /slots/0?action=share with no exportable region 501 This server's KV cache has no shareable region; start it with ONEBIT_KV_SHARE=1 — clear, actionable, no wedge
POST /slots/0?action=adopt {"tokens":[1,2,3]} on a fresh, empty cache 200 {"id_slot":0,"n_adopted":3,...}
same adopt with the 6 ids of a prompt whose cells are already occupied 500 Cannot adopt the shared cells: this slot's cache does not hold the provider's prompt — the occupied-cell guard works
server after both still serves a correct greedy completion

The blocker: adopt trusts the caller completely, and there is nothing that ties it to a share. On a fresh cache it returned 200 for [1,2,3] — a slot now claiming three positions of KV that no provider ever wrote. In the intended flow the cells are empty at adopt time too (the provider writes tensor data, not cell metadata — that is the whole point of adopt), so "cells are empty" cannot distinguish "the provider filled the region" from "nobody did". Two concrete consequences, both silent:

  1. Any local client can set a slot's cached prompt with one adopt call and skip prefill for it, producing an answer computed over uninitialised KV. No authentication, no epoch, no state that a share happened.
  2. More importantly for the engine: ggml-org#714 checks n_adopted != ids.size() and treats a match as success. A provider that exits 0 but fills only part of the region yields n_adopted == ids.size() and an engine that believes the handoff worked — so a partially-filled KV produces wrong output with nothing to detect it.

Cheapest fixes, in increasing order of effort: (a) have the provider write a small header into the region (magic, version, token count, and the layout hash) that adopt verifies before marking cells — this is the same idiom the region already carries; (b) at minimum, require that the slot had a successful share since its last decode, and return 4xx otherwise, so a bare adopt cannot fabricate cache state. Also worth one line in the body: the trust boundary is "whoever holds the fds may write the region", and it is currently implicit.

Structure note for merge order: this branch is stacked — it carries #163's +245 −14 and #162's +30 −2 under it (tests/test-backend-ops.cpp, src/llama-kv-share.*, ggml-cpu are the same commits). Merge #161 → #162 → #163 first, then this rebases to its own diff; merging in another order will look like a much larger change than it is.

Not verified, and cannot be here: the measured table and the "identical greedy text on the fd route vs the file route" gate. Both need an HRX decoder exporting dma-bufs; this box has no HRX build after the rebuild. The reference provider compiles and links, and the endpoint error paths behave, which is what this tree can show.

No tprs-ready. The tool (tools/kvshare-prefill, 230 lines) I read but did not run end to end — it is gated behind the same missing HRX exporter.

pi-zerocopy added 2 commits October 31, 2026 23:37
The two endpoints were safe only as a pair driven by our own engine: nothing stopped a client from adopting
cells that no export had just produced, and `llama_kv_cells_adopt` would then make whatever bytes sat in those
cells a prompt's cache -- silent corruption of exactly the kind this feature must not have.

So `?action=share` now issues a per-slot id (monotonic, one outstanding per slot) and returns it, and
`?action=adopt` has to quote it back: unknown, stale or zero ids are refused with a message that says which
call produces one. Adopting consumes the id, so one export means one adopt. Nothing else changes: the regions,
the layout check and the cell metadata path are as they were.
Measured on Qwen3.8-Flash-Next (a linear-attention hybrid) on the hybrid route: ?action=share answers 501 with
"This server's KV cache has no shareable region; start it with ONEBIT_KV_SHARE=1" -- while the server *was*
started with ONEBIT_KV_SHARE=1 and the real reason was that a hybrid cache has no shareable region at all
(llama_kv_share_regions returns 0 for llama_memory_hybrid, whose recurrent state this code does not cover).

The refusal is right, the message sent the reader after the wrong thing, so it now names both causes. Same
status code, same behaviour: the engine falls back to prefilling the request itself and answers identically
('Red, Orange, Yellow' on both routes in that run).
@bong-water-water-bong bong-water-water-bong added the tprs-ready TPRS: review verdict READY posted by the standing reviewer; merge gate satisfied label Nov 1, 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: READY

At 39a72359 (+676 −2, 11 files). My blocker on the previous head was that adopt trusted the caller and nothing tied it to a share; that is fixed, and I re-ran the exact call I used to demonstrate the hole.

Before / after, same request:

previous head:  POST /slots/0?action=adopt {"tokens":[1,2,3]}                      -> 200 {"n_adopted":3}
this head:      POST /slots/0?action=adopt {"tokens":[1,2,3]}                      -> 400 "adopt needs the \"share_id\" that ?action=share returned"
this head:      POST /slots/0?action=adopt {"tokens":[1,2,3],"share_id":12345}     -> 400 "adopt must quote the share_id of the export these cells came from (POST /slots/<id>?action=share first)"

The implementation is the shape it should be: ?action=share mints share_id = ++kv_share_seq and records it per slot (kv_share_issued[id_slot]); ?action=adopt refuses a missing, zero or mismatched id; and on success it does kv_share_issued.erase(issued); // single use, so an id cannot be replayed against a second adopt. Combined with the cells-occupied guard, a slot can now only take cells that the client's own export produced — the two silent-wrong-output paths I described (a bare adopt fabricating cache state, and ggml-org#714's n_adopted == ids.size() check passing over a partially-filled region) both need a share the server issued.

Built at this head: ninja -j4 llama-server llama-kvshare-prefill → both link, rc 0 (40 targets). Endpoints exercised on a CPU-only build, which is enough for the task types and error paths — share still answers 501 "no shareable region; start it with ONEBIT_KV_SHARE=1" when there is no exporter.

The three PRs now interlock, which is worth recording: ggml-org#714 sends the share_id (merged), this validates and consumes it, and ggml-org#740's fake backend tests the contract in CI — so the trust boundary is enforced, and it is enforced by a test that runs on every PR rather than by a device run.

Still not verified by me, unchanged: the measured table and the "identical greedy text on the fd route vs the file route" gate — both need an HRX decoder exporting dma-bufs, and this box has no HRX build. The reference provider (tools/kvshare-prefill) compiles and links.

Merge-order note (unchanged): this branch still stacks #161/#162/#163 under it — merge those first and it rebases to its own diff.

tprs-ready applied.

@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: READY

At 39a72359 — head unchanged since my earlier READY, tprs-ready still on it. Restatement for the merge gate.

The cross-process KV handoff. The blocker I filed on the previous head is fixed and I demonstrated it rather than inferring it: POST /slots/0?action=adopt {"tokens":[1,2,3]} returned 200 n_adopted: 3 on the old head (a slot claiming KV nobody wrote) and returns 400 on this one — both without a share_id and with a forged one — and the code does kv_share_issued.erase(issued); // single use, so an issued id cannot be replayed. share still answers 501 "no shareable region; start it with ONEBIT_KV_SHARE=1" when there is no exporter, and the server keeps serving afterwards.

Built at this head: ninja llama-server llama-kvshare-prefill → both link, rc 0, and the endpoints' error paths were exercised on that binary.

Not verified: the measured handoff table and the "identical greedy text on the fd route vs the file route" gate — both need an HRX decoder exporting dma-bufs, and this box has no HRX build. The reference provider compiles and links; that is what this tree can show.

Merge-order note: this branch still stacks #161/#162/#163 underneath, so merging those first rebases it to its own diff.

tprs-ready stands.

@bong-water-water-bong
bong-water-water-bong merged commit 981904a into 1bit/hrx-vulkan-patched Nov 1, 2026
@bong-water-water-bong
bong-water-water-bong deleted the 1bit/kv-share-fds branch November 12, 2026 21:16
bong-water-water-bong pushed a commit that referenced this pull request Nov 12, 2026
## 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
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

tprs-ready TPRS: review verdict READY posted by the standing reviewer; merge gate satisfied

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant