Repository navigation
qwen4exp: Qwen3.8-Flash-Next on HRX (IMROPE->NEOX rope, CPU-route problem experts) + KLD - #141
Closed
bong-water-water-bong wants to merge 20 commits into
Closed
bong-water-water-bong wants to merge 20 commits into
bong-water-water-bong wants to merge 20 commits into
Conversation
* kv: track token id * rm get_prev_tokens, move it to the main pr * nits * add get_prev_tokens (cherry picked from commit 925e117)
(cherry picked from commit 1269cb1; src/models/deepseek4.cpp left as on this branch)
* llama: model_loader: add TENSOR_GET_ROW_LAZY * add --tensor-read-lazy * rename to TENSOR_READ_LAZY * gen docs * address comments (cherry picked from commit fac889f)
* gguf: add qwen4exp (Qwen3.8-Flash-Next) arch and converter
Adds the GGUF-side plumbing for HF model_type qwen4_exp:
- MODEL_ARCH.QWEN4EXP plus tensors for the low-rank hyper-connection
variant (hc_*_norm/down/up/inject) and the PLE n-gram hash embeddings.
The DeepSeek-V4 hc_*_fn/base/scale tensors are a different
parameterisation, so these are separate entries rather than reuse.
- Reuses the existing indexer, per_layer_token_embd, SSM and
compress_ratios keys unchanged.
- conversion/qwen4exp.py inherits the Qwen3.5 linear-attention V-head
reorder and interleaved mrope, concatenates the 128 PLE embedding
shards, and splits index_qk_proj into separate indexer q/k tensors.
The PLE hash multipliers reach ~2.4e13. prepare_tensors() casts every
non-float dtype to float32 before modify_tensors() runs, and GGUF array
writes infer INT32 from Python ints, so both paths are bypassed: the
constants are read from the pre-cast lazy tensors and written as
explicit UINT64 arrays.
Additive only; no existing arch changes behaviour.
* llama: load qwen4exp (Qwen3.8-Flash-Next) hparams and tensors
Adds LLM_ARCH_QWEN4EXP with its hparams and tensor loading. The graph
comes in the next commit; this makes the model load and report correct
metadata.
- hyper-connections set n_embd_out_impl = hc_count * n_embd, so the
residual stream is 4x wide and there is no output_norm: the final
mixer's hc_norm is the last norm in the model.
- registered as hybrid and given the same recurrent/attention memory
filters as Qwen3-Next and Qwen3.5.
- reuses the existing indexer, per_layer_token_embd, SSM and
compress_ratios keys as-is.
- the PLE table row count is read back from the file rather than
recomputing the vocab padding rule.
llama-model-loader gains UINT64 array support. That branch previously
threw, so no existing caller changes behaviour; it is needed because the
PLE hash multipliers do not fit in int32.
* qwen4exp: shorten comments
* llama: qwen4exp text graph with hyper-connections, GDN and MoE
Implements the decode graph for Qwen3.8-Flash-Next: the hyper-connection
residual stream, gated delta net layers, the MoE block with its gated shared
expert, and dense full attention. The QSA indexer and the PLE n-gram embedding
are not wired up yet and land in later commits.
Hyper-connections are implemented here rather than shared with deepseek4.cpp.
The two formulations agree on the [n_embd, hc, n_tokens] layout and little
else: DeepSeek-V4 mixes with a full-rank projection and Sinkhorn-normalises
it, whereas this model uses a low-rank down/silu/up sigmoid gate and collapses
by a plain mean. Only the ~10 line stream mean is genuinely common, so sharing
would mean touching DSV4's hot path and its three fused CUDA ops to reuse very
little. What is reused is the substantive part: the LLM_KV_HYPER_CONNECTION_*
keys, the n_embd_out_impl wide-residual support already in the loader, and the
layout convention.
Also allows a checkpoint to carry no PLE layers at all, which makes it
possible to bring the graph up and validate it in stages.
Validated against vLLM, the only working reference implementation. On a
scaled-down model with an init scale large enough to give non-uniform logits,
agreement with vLLM sits at the numerical noise floor: llama.cpp f32 against
its own bf16 gives 84.3% top-1 agreement over 255 positions, and this graph
against vLLM gives 85.1%. The comparison was calibrated by seeding three
deliberate bugs (silu instead of sigmoid on the delta net gate, dropping the
1/hc scale in the mix, dropping the 2x in the combine); each drops top-1 to
between 0% and 11%, an order of magnitude below the floor.
* llama: qwen4exp PLE n-gram hash embedding
Adds the per-layer embedding: a custom I32 graph input hashes each token with
its ngram_size-1 predecessors host-side and the result is a plain row gather
over the shared table, the same shape gemma3n's per-layer embedding uses. The
hash has to run on the host because the splitmix64-derived multipliers reach
2^45, so the products need 64-bit integers and an xor, neither of which ggml
has.
Predecessors that fall outside the ubatch come from a small per-sequence
history on the model, mirroring the per-request ngram_context the reference
carries. It is only trusted when contiguous with the incoming position, so a
fresh prompt or a rewound cache falls back to EOS padding rather than hashing
against stale tokens.
The depthwise conv is written out as a sum of shifted, per-channel-scaled
copies rather than through ggml_conv_1d_dw, which carries a correctness
warning upstream.
Verified two ways. The row indices match a transcription of the reference's
tensor formulation exactly, 1024 of 1024 rows, including sequences with EOS
tokens sprinkled through them to exercise the segment reset. Separately, with
PLE placed on layer 0 so its input is just the token embedding, ple_embd and
ple_gated_value match a PyTorch computation from the same checkpoint to every
printed digit.
End to end over 1023 scored positions the port sits the same distance from
vLLM with PLE as without it, 6.3 points of top-1 against 6.0, so PLE costs no
accuracy relative to the rest of the model. That common offset is vLLM's bf16
activations, which cannot be removed: its QSA kernel refuses float32.
Two bugs found along the way, both caught by the row-index check. The history
was read and updated in the same pass, so a token early in a ubatch could pick
up an earlier token of that same ubatch as prior context; it is now snapshotted
first. And an EOS token was cutting its own context, where the reference takes
the last EOS strictly before the position, so a boundary only hides tokens from
the positions after it.
Known gap: the conv carries no state across ubatches, so it is exact only for a
prefill that starts at position 0. Chunked prefill and decode need the conv
state wired into the recurrent memory, and the conv branch itself is still
numerically unverified because the fixture zeroes its weights.
* llama: carry the qwen4exp PLE conv state across ubatches
The PLE depthwise conv was zero-padding on the left, which is only right for a
prefill that starts at position 0. Decode and chunked prefill saw a truncated
history for the first (kernel-1)*ngram_size positions of every ubatch.
The PLE module sits on a layer that is also a delta-net layer, so both need a
conv history in the same recurrent row. Rather than plumb a per-layer state
size through build_rs and build_conv_state, the row is widened once and each
convolution addresses its own slice through a local helper. n_embd_r() gains
the extra span, which is zero for every other architecture because it is
derived from ple_n_heads.
Verified by feeding the same 1024 token sequence in chunks instead of one
shot: at 64 tokens per decode the logits are bit-identical to the single-shot
run, 1023 of 1023 top-1 and a maximum logprob deviation of exactly zero. At
one token per decode they differ slightly, but the no-PLE model differs more
under the same test (94.6% against 97.1%), so that is the usual gemv-versus-
gemm accumulation difference and not the state.
The conv branch is also no longer unverified. With non-zero conv weights the
port sits 6.3 points of top-1 below the numerical floor, the same distance as
with the weights zeroed and as the model with no PLE at all, so the branch
adds no error of its own.
test-llama-archs passes every existing architecture at 0.00e+00, including the
delta-net models that share this code path.
* llama: fix the qwen4exp PLE conv state and unblock test-llama-archs
build_rs writes into the state tensor in place, zeroing one row and copying the
carried-over states, so calling it twice for the same layer let the second call
clobber the first write-back. The PLE layer is also a delta-net layer, so that
is exactly what happened: both convolutions gathered the same row. They now
share a single gather per layer.
The earlier claim that the conv state was carried correctly was tested on a
fixture whose conv weights are zero, where the branch contributes nothing and
chunking matches trivially. Re-running with non-zero conv weights showed the
divergence, growing with the number of ubatch boundaries: 97.1% top-1 at one
boundary down to 90.2% at seven. With the shared gather it is bit-identical to
the single-shot run at every chunk size tried, 512, 128 and 64, with a maximum
logprob deviation of exactly zero over 1023 positions. The delta-net-only model
stays bit-identical too, so nothing regressed there.
Also derive the delta-net conv channel count the way load_arch_tensors sizes
wqkv instead of from ssm_d_inner. The two agree for this model, but n_embd_r()
only bounds the row and the convolution has to match the tensor feeding it.
test-llama-archs previously aborted on this architecture and took every later
architecture with it. qwen4exp is marked MoE-only, given the hyper-connection
keys and an ssm_d_inner consistent with its tensor derivation, and skipped for
now: the hyper-connection keys written by get_gguf_ctx are not reaching the
synthesised file, which needs a separate look. The suite completes again, 124
architectures at 0.00e+00.
* llama: optional indexer key cache in llama_memory_hybrid
Groundwork for qwen4exp's QSA sparse attention. Its indexer needs a per-token
key history for the full-attention layers, but a hybrid model cannot use
llama_kv_cache_dsa: that class derives from llama_memory_i rather than
llama_kv_cache, and llama_memory_hybrid constructs its attention cache
directly. No existing architecture pairs recurrent state with a sparse
indexer, so there was nothing to reuse wholesale.
llama_memory_hybrid therefore gains a third, optional cache, shaped the same
way llama_kv_cache_dsa shapes its lightning-indexer cache: a copy of hparams
with n_head_kv forced to 1 and n_embd_head_k_full set to indexer_head_size.
It is built only when a filter_idx callback is passed, which defaults to
nullptr, so every existing architecture gets exactly what it got before. The
per-sequence operations and the batch preparation forward to it under a null
check, matching how the DSA cache prepares its two caches over the same
ubatches.
test-llama-archs passes all 124 architectures at 0.00e+00, including the 12 in
the hybrid family that share this code. The qwen4exp fixtures are unchanged:
same logits against vLLM, and chunked evaluation still bit-identical to
single-shot.
* llama: QSA sparse attention for qwen4exp
The full-attention layers of this model do not attend to everything. An
indexer scores one mean-pooled key per block of compress_ratio tokens and
keeps a budget of the best blocks, plus the tail of tokens that do not yet
form a complete block. Below indexer_top_k + compress_ratio - 1 cached
tokens every block fits in the budget, so the result is exactly dense.
What is reused rather than rebuilt:
- the mask machinery. build_attn's DSA overload already turns a list of
token indices into a KQ mask via ggml_set_rows, so that block is lifted
out verbatim into build_attn_mask_top_k and shared with a new overload
on llm_graph_input_attn_kv. DSA's node sequence is unchanged; the new
overload exists because llama_kv_cache_dsa assumes MLA and cannot be
dropped into a hybrid model.
- the indexer key cache, which is the optional third cache added to
llama_memory_hybrid in the previous commit. It holds raw keys, because
pooling happens before the norm and the rotation.
The graph expands block scores rather than block indices: giving every
token of a block its block's score needs only a gather, where expanding
indices would need an integer multiply-add that ggml has no op for. Since
the budget is a whole number of blocks and a block's members tie exactly,
the cut still lands on a block boundary.
Everything that depends on cache layout is computed host-side in
set_input_qsa. Blocks are cuts of the position line rather than of the cell
array, so nothing assumes the cache is contiguous.
Measured on the tiny fixture against vLLM, comparing the selected token
indices directly rather than the logits:
below the budget selection identical, and 1024-token logits are
bit-identical to the pre-QSA dense path
above the budget mean jaccard 0.975
The direct index comparison is what made this correct. The reference
rectifies each head's dot product before summing over heads, which an
earlier reading of it had missed; on logits alone the resulting port looked
fine, because on a randomly initialised fixture the known-correct dense
path already disagrees with vLLM by more than the bug did. Comparing the
indices showed 0.794, and fixing the ReLU moved it to 0.975.
* llama: give the qwen4exp indexer cache the attention cache's slots
The indexer cache found its own slots, independently of the attention
cache. Both are the same size and see the same ubatches, so in a
straight-through prefill they agree, which is why every fixture and every
single-shot parity run passed. They drift once the context is being
rewritten between turns, and then the QSA top-k indices, which are applied
against the attention mask, point at the wrong cells.
The seven-turn chat test caught it on the third turn: llama-server aborted
on the assertion that the two caches report the same n_kv.
The cache is a side buffer addressed by the attention cache's cells, so it
now takes that cache's slot layout instead of computing one. Applying that
layout also marks its cells identically, so the two agree cell for cell by
construction rather than by coincidence, and the assertion can no longer
fire.
Inert where the caches already agreed: test-llama-archs green at 126 archs
and 0.00e+00, and the 4096-token tiny fixture is unchanged at max logit
delta 0.0.
* tests: record what the qwen4exp arch-test skip actually observes
The old note guessed that the hyper-connection keys never reach the file.
They do: dumping the gguf_context handed to llama_model_init_from_user
shows both among its 67 KVs, and the loader still reports one missing.
* tests: cover qwen4exp in test-llama-archs
The arch was skipped with a note guessing that the hyper-connection keys
never reached the synthesised file. They did. The suite builds a model, then
saves and reloads it, and llama_model_saver did not re-emit those keys, so
the failure was in the roundtrip leg rather than the first load. Three gaps,
all in shared code and all additive:
- add_kv_from_model wrote no hyper-connection, compress-ratio or PLE keys.
The PLE group only means anything whole, so it is written or omitted
together; the rest follow the file's existing style of writing every key
unconditionally, since an architecture that does not read one is
unaffected by a zero.
- the saver had no uint64 path at all, which the PLE hash constants need.
- add_tensors_from_model enumerates model-level tensors by hand and was
missing per_layer_tok_embd and the three final-mixer tensors.
Two smaller fixes on the qwen4exp side, both found by running the test:
- build_qsa_top_k divided by the compression ratio before asserting it was
non-zero, so a file without the key crashed instead of reporting.
- a layer with no compression ratio now falls back to dense attention,
which is what the model computes below the budget anyway. The test then
has to write a ratio to reach QSA at all, and an indexer key length no
narrower than n_rot, since the indexer ropes with the main attention's
rotary width.
Full suite: 126 archs, qwen4exp at 0.00e+00 with roundtrip OK. The tiny
fixture is unchanged, max logit delta 0.0 against the pre-QSA dense run.
* convert: stream the qwen4exp PLE table instead of concatenating it
The n-gram table arrives as 128 shards that were held in a dict and then
torch.cat-ed, so the peak was the shards plus the concatenation: around
300 GB of RSS on the real checkpoint, which rules out machines that could
otherwise convert this model.
Each shard is now written straight into a memory-mapped file at its final
row offset and dropped, so the resident set is one shard and the rest is
the page cache's problem. The temporary file sits beside the output and is
removed once the write finishes, including on failure.
Shards other than the last must be uniform for direct placement, which is
asserted rather than assumed, and a shard arriving before the stride is
known is held instead of misplaced.
Verified on the tiny fixture: the resulting GGUF is byte-identical to the
one the concatenating path produced (md5 2d274efac91ad1e9a6007efb0687e597).
* quantize: fall back to F16 for 32-block types with an odd ncols
tensor_type_fallback demotes a tensor whose ncols is not a multiple of the
target's block size, but its switch only enumerates the 256-block types. A
target that is already a 32-block type (iq4_nl, q4_0, q5_0, q8_0, ...) falls
into default: and throws, even though the function already knows how to answer
that case: the ncols check right below the switch resolves an unrepresentable
shape to F16.
Route those types into that check instead of throwing. Only paths that abort
today change, so no quantization that currently succeeds is affected.
Found on a 4-wide depthwise conv kernel. llama-quantize reported nothing but
"failed to quantize model from ...", with no tensor name and no exception text,
which made a quant recipe that had simply not pinned the tensor look like a
corrupt model. It now names the tensor and continues.
* quantize: let --tensor-type name per_layer_token_embd
per_layer_token_embd shares the TOKEN_EMBD category with token_embd.weight, so
--token-embedding-type is returned for it before any --tensor-type pattern is
consulted, and there is no way to give it a tier of its own.
That grouping is fine as a default and stays the default. It is a poor fit for
the size, though: on qwen4exp the table is 97.7 GiB of a 337.6 GiB BF16 file and
about 46% of a 4-bit one, roughly eighty times token_embd.weight, and it is
read by ggml_get_rows rather than a matmul so no imatrix ever covers it.
Allow an explicit --tensor-type pattern to name it, and only it. Nothing
changes unless such a pattern is passed, and token_embd.weight keeps the old
precedence in either case.
Measured on Qwen3.8-Flash-Next, Q4_K_M with an imatrix: the table lands at q8_0
(51.9 GiB, 113.5 GiB total) by following --token-embedding-type, and pinning it
q4_1 gives 30.5 GiB for 92.1 GiB total, 19% off the file.
* quantize: size the output buffer exactly instead of nelements * 4
The per-tensor output buffer was sized `nelements * 4`, described as an upper
bound. It is a very loose one: the output is at most 2 bytes per element
(f16/bf16) and usually well under 1.1 (q8_0 and below), so between 2x and 4x of
it is never touched. The exact size is already known here, since it is what the
quantization loop writes, what new_size sums to, and what the GGUF metadata is
asserted against a few lines later.
On a model whose largest tensor is a few GB none of this matters. On
Qwen3.8-Flash-Next it does: per_layer_token_embd is 51.2 G elements, so the
buffer was 205 GB where 54 GB is needed at q8_0 and 32 GB at q4_1.
Measured on that model, VmHWM of a live llama-quantize was 485 GB per process.
Three of them fit in 2 TB and five did not, which is what an OOM-killed quant
ladder looks like. This removes about 150 GB of that.
Byte-identical output, verified against the same binary built at the parent
commit: q4_K, q8_0, q5_K, q6_K and IQ4_XS, over BF16 and F32 sources, with and
without a PLE table present. Six cases, six matching md5s.
* qwen4exp: hash the image placeholder for multimodal batches
The PLE row indices are computed host-side from ubatch->token, and set_input
returned early when that was null. A multimodal ubatch is exactly that case:
the mtmd layer consumes the image placeholder ids and hands llama_decode
embeddings instead. The early return left the I32 index tensor uninitialised,
so ggml_get_rows indexed a 320 M row table with whatever the buffer happened to
contain, and aborted:
GGML_ASSERT(i01 >= 0 && i01 < ne01) failed
ggml_compute_forward_get_rows
mtmd_helper_decode_image_chunk -> llama_decode
Every image request crashed. Nothing caught it because the vision work had only
ever been verified by converting an mmproj, never by running one.
The reference computes the hash over input_ids, where those positions still
hold the image placeholder, so carry that id through as qwen4exp.ple.image_token_id
and hash it. The key is optional: a file converted before it existed falls back
to the PLE EOS token, which is defined and treats the image as a segment
boundary rather than crashing.
Verified end to end with llama-mtmd-cli, a Q4_K_M base and the F16 mmproj, on a
generated image with known content. The model names the red circle, the blue
square, the inverted green triangle and reads "UNSLOTH 42", each with the right
position.
* qwen4exp: support a non-unified KV cache in QSA
set_input_qsa asserted n_stream == 1, so llama-server could not serve this
model with more than one slot unless -kvu was passed. With a non-unified
cache each sequence owns its own cells, and a cell index means a different
token in each stream, so a single shared mapping is wrong.
- cell_blk, blk_cells and bias gain a stream dimension. At n_stream == 1
these collapse to the shapes they had, so the unified path is unchanged.
- Scoring is now batched over streams. ggml_mul_mat matches ne[2] on both
operands, so stream s's queries only ever meet stream s's blocks; without
this sequences would score against each other's context.
- set_input_qsa loops per stream and resolves cells through
v_cells[seq_to_stream[seq_id]], following set_input_kq_mask_impl, instead
of hardcoding v_cells[0].
- llama_kv_cache_context::get_n_stream() is added, mirroring the ns that
get_k and get_v already derive from the slot info.
build_attn_mask_top_k needed no change: it already expects
[n_top_k, n_batch, 1, n_stream], so the top-k result is reshaped to meet it.
set_input_qsa has exactly one caller, so the blast radius is qwen4exp only.
Validation, UD-Q4_K_XL on one B200:
- unified cache unchanged within noise: 1802.9/68.85 -> 1807.2/69.11 t/s at
batch 1, 2262.5/192.43 -> 2270.1/193.75 at batch 4.
- non-unified now runs at npl 1, 4, 16 where it previously aborted, and is
22% faster than the -kvu workaround at batch 16 (1205 vs 984 t/s total),
since per-stream cells avoid the cross-sequence masking a unified cache
pays for.
- no cross-stream contamination: four concurrent sequences each carrying a
distinct secret all recall their own and no other, on both cache modes.
- test-llama-archs green on qwen4exp, deepseek2, gemma3n, qwen3next, llama.
Note on testing: comparing concurrent output against solo output exactly is
not a valid check. It failed 0/4 with no bug present, and the unified-cache
control failed the same way, because batch composition changes the
floating-point reduction order and near-tied tokens flip. The contamination
test above is what the exit code gates on.
* llama: keep the qwen4exp top-k attention mask arch-local
The QSA graph needed a build_attn that attends only to the cells named by a
top_k tensor, and the first version got it by adding a llm_graph_input_attn_kv
overload to llm_graph_context and factoring the mask construction out of the
existing MLA sparse path into a shared build_attn_mask_top_k.
That put a new arch on the shared attention path and made the deepseek32 and
glm-dsa attention build depend on a helper introduced for qwen4exp. Build the
mask in src/models/qwen4exp.cpp instead and leave llama-graph.{h,cpp} exactly as
they were: the MLA path keeps its own copy of the same node sequence.
The nodes emitted are unchanged, so this is bit-identical.
* llama: hold the qwen4exp indexer cache in a new llama_memory_hybrid_idx
The indexer key cache was added by extending llama_memory_hybrid with an
optional third cache, and the host-side cell/block mapping that drives QSA was
added as set_input_qsa on llama_kv_cache. Both are shared classes that every
hybrid and every attention model goes through.
Move both into a new memory type, llama_memory_hybrid_idx, following
llama_kv_cache_msa: the indexer cache and the pos<->cell translation live with
the sparse-attention memory rather than in the classes that serve every other
architecture. llama-kv-cache.{h,cpp} and llama-memory-hybrid.{h,cpp} are
restored to their unmodified state.
init_batch is repeated from llama_memory_hybrid because the indexer cache has to
be handed the attention cache's slot infos, and those are not reachable through
the context the base returns. Allocating them separately lets the two caches
drift, which is what pointed QSA's top-k at the wrong cells before.
The context derives from llama_memory_hybrid_context so build_inp_mem_hybrid
keeps working unchanged, and get_n_stream is computed from the slot infos
exactly as llama_kv_cache_context did.
Behaviour is unchanged: logits over an 8192-token sequence are bit-identical to
the previous implementation, sparse and dense alike.
* llama: save and restore the qwen4exp indexer KV cache
llama_memory_hybrid_idx forwarded clear, seq_rm, seq_cp, seq_keep, seq_add and
seq_div to the indexer cache but not state_write / state_read, so a saved
session dropped the indexer keys and a restored one selected QSA top-k against
an empty cache. The effect is invisible until the context passes
indexer_top_k + compress_ratio - 1 cells, because QSA is exactly dense below
that and the indexer contents cannot change the result.
The indexer section is written last rather than next to the attention cache it
mirrors. As a suffix, a reader that does not expect it stops early and the
trailing bytes are caught by the size check in state_load_file; placed between
the attention and recurrent sections it would instead be parsed as recurrent
state, which can succeed and restore silent garbage. It follows the same
LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY gate as the attention cache, since a partial
checkpoint deliberately skips the token-level attention caches.
The indexer restores its own cells instead of taking the attention cache's
restored slots. The two caches share size, padding and every sequence
operation, and init_batch hands the indexer the attention cache's slot infos,
so both state_read_meta calls run find_slot over identical occupancy and land
on identical cells.
The overrides live on llama_memory_hybrid_idx, the only memory type that owns
an indexer cache, so llama_memory_hybrid and every architecture that uses it
write and read exactly the bytes they did before.
The session and sequence state versions are bumped because the qwen4exp state
layout changed. The session path already rejects a short read via its size
check, but llama_state_seq_load_file accepts one silently, so only the version
check stops a pre-fix blob from being half-restored by a fixed build.
(cherry picked from commit 2721542354f8e158c3217625f4e2e7b83e51e3fe)
* llama: make the qwen4exp PLE n-gram history per context and serialise it
The PLE hash of a token mixes in the ple_ngram_size - 1 tokens before it, which
a decode ubatch does not carry, so they were remembered in a map on
llama_model_qwen4exp. That is the wrong owner twice over.
A llama_model is shared by every context that loads it, and the map was keyed
only by llama_seq_id, so two contexts running the same sequence id - two server
instances on one model, or a draft/target pair - overwrote each other's window.
The next_pos guard turned that into EOS padding instead of a crash, so it
degraded quality silently.
The map was also in no state blob: grep found ple_hist in neither
llama-kv-cache.cpp nor llama-memory-*.cpp nor llama-context.cpp. A restored
context therefore failed the next_pos check on its first ubatch and hashed the
first tokens after the restore against EOS padding. This is why a session blob
round-tripped byte for byte while the restored context computed different
logits: the state was never in the bytes.
It moves to llama_memory_hybrid_idx, which is per context, is the memory type
qwen4exp always builds, and already does the per-sequence bookkeeping this
needs. Every sequence operation now carries the window with it:
seq_rm a rewind (p1 < 0) truncates the window to the surviving prefix and
moves next_pos to p0, so a rollback keeps exact context; a hole
punched in the middle leaves the window non-contiguous, so it is
dropped
seq_cp the destination inherits the source's window, truncated to the
copied position range - a copied sequence continues with the same
n-grams the source would have used
seq_keep every other sequence's window is dropped, like its cells
seq_add a shift that moves the whole window keeps it and moves next_pos with
it, which is the context-shift case; one that cuts through it drops
it
seq_div positions stop being consecutive, so an overlapping window is
dropped
clear everything is dropped
Dropping means next_pos = -1, which set_input turns into full EOS padding: the
same thing a fresh sequence gets, and the same thing this code did before it
followed the sequence operations at all, so no case is worse than before.
The state payload is a self-delimiting list, u32 count then per entry
{ i32 seq_id, i32 next_pos, u32 n_toks, i32 toks[n_toks] }, so a whole-context
save and a single-sequence save share one format and a single-sequence restore
can retarget the window at its destination seq_id. It is written after the
indexer section, last, for the same reason that one is: as a pure suffix an
older reader stops early instead of parsing these bytes as something else.
Unlike the indexer section it is not under LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY.
The window is recurrent state - it is the input the PLE convolution's own
recurrent state is derived from - and the recurrent cache beside it is written
for partial checkpoints too. Gating it would leave the server's speculative
decoding checkpoints restoring the conv state without the window that produced
it.
No further version bump: LLAMA_SESSION_VERSION 10 and LLAMA_STATE_SEQ_VERSION 3
were introduced for the indexer section in the same unreleased series, and both
changes are qwen4exp-only additions to the same blob layout.
Also fixes the padding of a short window. set_input pads a window shorter than
ngram_size - 1 up to that length, but prev() indexes the snapshot with the most
recent token last, and resize() pads at the back, so the filler EOS landed where
the immediately preceding token belongs. It now pads at the front. A window is
short at a sequence start after a one-token prefill, and after a seq_rm rewind,
which the new bookkeeping makes common.
Every architecture other than qwen4exp builds llama_memory_hybrid rather than
llama_memory_hybrid_idx, has no PLE table and never asks for a history, so
nothing about its graph, its sequence operations or its state bytes changes.
(cherry picked from commit de170364c052c68fcf63285cc0028095edb9f23c)
* qwen4exp: tidy comments and simplify image token read
Rewrite the comments this series adds to the AGENTS.md rules: one or two lines,
no prose hard-wrapped mid-sentence, no narrative or history, and no comment that
only restates the code. Net 146 fewer comment lines, no code change.
Correct the PLE image comment: mtmd does not consume the placeholder ids. An
image is decoded as an embeddings-only batch, so ubatch->token is null and the
per-position ids never exist here. gemma3n and gemma4 hit the same case and
stand in row 0 of per_layer_token_embd; qwen4exp stands in the configured image
token id instead.
Read image_token_id straight from self.hparams in the converter. base.py merges
text_config into the root of hparams, and the key sits at the root of
config.json, so the config.json re-read was redundant.
(cherry picked from commit 205840c12169057da3e8d2f65ec4ceec3e18b980)
* qwen4exp: support a quantized KV cache in the QSA attention path
(cherry picked from commit 4c30574f81dc1115d08078c47b6cf8c789c0a842)
* llama: give qwen4exp a large-graph node budget
(cherry picked from commit 37c8c194e6a30e4c46ac29bee3fb264f091596ef)
* qwen4exp: drop an unused variable that breaks -Werror builds
(cherry picked from commit 528d032b51fa3cf935ed3ef6e0fb1c7401df53b5)
* quantize: dequantize and quantize large tensors in row bands
f32_conv_buf held the whole dequantized tensor, which is 204.8 GB for
per_layer_token_embd alone and dies with std::bad_alloc long before the
work buffer is reached. Dequantize and quantize in bands of whole rows
instead, capping the f32 staging at 1 GiB per band.
Rows are independent and the imatrix is indexed by column, so band
boundaries cannot change any output byte. Bands nest inside the existing
per-expert loop so each expert slice keeps its own imatrix, and a band is
kept to at least one quantization chunk per worker thread so the existing
multithreading still has work. F32 sources still stage nothing and are
banded by pointer arithmetic into the tensor.
llama_tensor_dequantize_impl now takes a first element offset; the single
caller is updated.
(cherry picked from commit 658c22549613555dbce57a772be4de8509eba3ee)
* llama: segment the qwen4exp fused QKV for tensor split
qwen4exp was missing from the gated delta net branch of get_split_segments,
so its attn_qkv.weight, shaped {n_embd, 2*key_dim + value_dim}, fell through
to the generic fused QKV rule and tripped
GGML_ASSERT(tensor->ne[axis] == n_embd + 2*n_embd_gqa) while loading with
--split-mode tensor. --split-mode layer was unaffected.
qwen4exp broadcasts K to the V heads by tiling, k_conv is grown with a plain
ggml_repeat_4d over the head axis so that v head j pairs with k head
j % n_k_heads. That is the Qwen 3.5 pattern, not the repeat interleave that
Qwen 3 Next builds explicitly, so qwen4exp takes the else branch and its V is
segmented on the scale of K.
Reported by benklop.
(cherry picked from commit 353d753f595dc81634ae6130188b31f06018f5ae)
* llama: fix the qwen4exp PLE history seq_rm(-1) iterator invalidation and the fatal-warning build
ple_hist_rm recursed over ple_hist with a range-based for and the recursive call
erases the entry it is iterating when the whole sequence is removed (p0 <= 0,
p1 < 0), so the loop then increments an invalidated iterator. It is unreachable
today only because llama_memory_recurrent::seq_rm rejects seq_id < 0 before
llama_memory_hybrid_idx::seq_rm reaches the history, which is a guard in another
class. Advance past the entry before recursing.
Two smaller things in the same area:
- the n_toks sanity bound in ple_hist_state_read was the literal 64, which is
the value of LLAMA_MAX_PLE_HEADS, not of the quantity being checked. The
window is at most ple_ngram_size - 1 tokens, so the bound is
LLAMA_MAX_PLE_NGRAM - 1, eight times tighter.
- build_conv_state_at left mem_size unused, so -DLLAMA_FATAL_WARNINGS=ON does
not compile. Predates this series; drop the line.
(cherry picked from commit 6eba44a89d5f328eb4859b844e1d28fb564cbe3e)
* qwen4exp: include llama-impl.h explicitly for llama_mul_mat_hadamard
(cherry picked from commit b634fd4d250d181ef82bf78bd00c1ae3b96a7af6)
* convert: fix the qwen4exp lint and type-check failures
flake8 flagged an unused MmprojModel import, and ty flagged seven errors in
the PLE streaming path: eos_token_id can be absent, and _ple_map, _ple_path,
_ple_row_dim and _ple_rows_per_shard are all Optional at the declaration but
were dereferenced without narrowing.
The map is opened and the stride fixed before the first shard is written, and
_finish_ple_table only runs once every shard has landed, so the invariants
hold. Assert them so the checker can see it. A missing eos_token_id now raises
with the reason instead of a TypeError from int(None).
* llama: give the qwen4exp indexer cache its own tensor names
The indexer KV cache and the attention KV cache both named their tensors
cache_k_l%d, so the Meta backend matched the indexer cache against the
attention split pattern and aborted in handle_set_rows. Tag the names
instead, and mirror the indexer cache: it has one key head and its
projections are mirrored.
(cherry picked from commit a1cdc8181134659766763a17762545a1f0e5db7b)
* qwen4exp: double the Q split granularity for tensor parallelism
qwen4exp fuses the attention gate into attn_q.weight the same way qwen3next
and qwen 3.5 do, so a device boundary must fall on a whole q+gate pair or the
Q heads stop lining up with the K/V heads and attn_output rows.
(cherry picked from commit 6c9a592f0a425a459ab6efae3b897cf68460e244)
* qwen4exp: keep the indexer cache in step across server slots
The QSA indexer keeps a side cache addressed by the cells of the attention
cache, so cell j has to hold the same token in both: the top-k indices it
produces are applied to the attention KQ mask. init_batch already hands the
indexer the attention cache's slot layout rather than letting it look for its
own, but the restore path did not. state_read called llama_kv_cache::state_read
on the two caches in turn and each ran its own find_slot over its own occupancy.
That agrees only for as long as nothing has already pushed the two caches apart,
which is the property a restore is supposed to re-establish rather than one it
can lean on.
The failure path was the worse half, and it is reachable from the public API
with nothing more than a short buffer. Truncating a good blob at 35 offsets and
feeding it to llama_state_seq_set_data left the two caches disagreeing at 5 of
them, and every one of 23 truncations of a whole-context blob did. Four of those
five land inside the attention section, so the attention cache drops the
sequence and the indexer keeps it; only the cut that lands in the indexer
section gives the opposite direction. llama_kv_cache::state_read cleans up its
own cache and rethrows, so whichever way it falls, nothing is left to bring the
two back together. The server papers over this by clearing the slot when a
prompt cache load fails; a caller of llama_state_seq_set_data that does not is
left with an indexer addressing cells that no longer mean what it thinks.
llama_kv_cache::state_read_sinfo reports the cells a restore landed in, or takes
a copy of them, and state_read_meta uses a supplied layout in place of find_slot
once it has checked that those cells are free here too. The indexer now adopts
the attention cache's restored layout by construction instead of reproducing it
by coincidence, and a layout that does not fit fails the read rather than being
applied over cells that already drifted. The hybrid restore is wrapped so that
any failure drops the sequence, or for a whole-context restore the context, from
all three caches at once, which is a state they do agree on.
* kv-cache: clear the cache once when restoring a whole context
state_read walks the streams of the cache in turn, and for a whole-context restore
each stream went through state_read_meta, which starts by calling clear(). clear()
resets every stream at once, so each stream after the first threw away the streams
already restored, and the K/V buffers with them. A non-unified cache holds one
stream per sequence, so a context saved with N sequences in it came back with only
the sequence in the last stream that carried any cells - the highest sequence id.
A unified cache has one stream and never showed it.
The cache is now emptied once, before the loop, which is what a whole-context
restore means. A blob whose streams are all empty now empties the cache as well,
where before it left the old contents in place.
* kv-cache: check the mirrored slot layout on a whole-context restore too
state_read_meta only looked at the layout it was given on the single-sequence path.
A whole-context restore lays the cells out from 0 in both caches, so they agree as
long as they restore the same number of cells, but nothing checked that they did: an
indexer section belonging to some other context was read over cells the attention
cache had filled from a different one, which is the state the indexer must never be
left in.
* qwen4exp: give the PLE conv history its own mirrored recurrent row
n_embd_r() reserved n_conv + ple_conv_state() so that one cache_r_l row could
carry both the delta-net conv state and the PLE dilated conv history, but the
QWEN4EXP arm of get_split_segments only described n_conv. Under -sm tensor the
segment sum came up short by ple_conv_state() and llama_memory_recurrent
construction aborted in ggml_backend_meta_alloc_ctx_tensors_from_buft.
Widening the segment list is not the fix. The Meta backend propagates a view's
split descriptor from its parent unchanged, so a view of one sub-range of a
split axis is sized as the whole row on every device; declaring the PLE tail as
a second segment merely moves the abort to "shape mismatch for VIEW" at graph
allocation. The two histories also want opposite policies: the delta-net state
is split by head to match wqkv and ssm_conv1d, while per_layer_tok_embd,
ple_conv1d and ple_norm_conv are all mirrored, so every device computes the
whole dilated conv and needs the whole history. One tensor cannot be both, and
the split state has no per-segment mirroring.
Move the PLE history into its own cache_ple_r_l%d row, mark it MIRRORED, and
return n_embd_r() to n_conv. The row is allocated only on layers where is_ple
holds, so mirroring one 92160-element row per device replaces a 92160-element
tail on all 36 recurrent rows: the recurrent R footprint drops rather than
grows. build_conv_state_at now takes its width from the tensor it was handed
and keys its gather on that tensor, which also drops a cont of a strided view.
* no more ple_hist (use master version)
* llama: give the qwen4exp full memory context its indexer cache
graph_reserve() walks a full memory context, and qwen4exp builds its
sparse attention only when the context exposes an indexer cache. the
full-context constructor left ctx_idx null, so the reserved worst case
was the dense fallback: a smaller graph than the one decode executes.
ggml-alloc then had to grow the compute buffer on the first decode,
past the size reported at load.
with -np 4 -c 32768 -fa on -ctk q8_0 -ctv q8_0 on an IQ1_S qwen4exp,
the reserved CUDA0 buffer was 217.00 MiB against 275.71 MiB actually
used, and CUDA_Host 42.31 MiB against 191.14 MiB. reserving the sparse
graph makes both match exactly, in unified and non-unified cache mode.
Co-authored-by: Pascal <[email protected]>
Assisted-by: Claude
* qwen4exp: shrink the PLE hparams storage
llama_hparams is held by value inside llm_graph_params and every llm_graph_input_*,
and llm_graph_params is a stack local in graph_reserve and process_ubatch, so its
width is paid on every worker thread stack.
is_ple_impl spent 2048 bytes carrying 512 bits. It is the one per-layer flag that is
not moved through the loader's uint32 array templates, so a bitset costs nothing in
call sites and also removes the uninitialized read that non-qwen4exp archs had, since
nothing filled the array for them.
The PLE head offsets and vocab sizes are token-space indices; the gather that consumes
them already truncates to int32, so 64-bit storage was never reachable. The gguf arrays
stay uint64 for file compatibility and are narrowed on load.
sizeof(llama_hparams) 34440 -> 31944, sizeof(llm_graph_params) 34872 -> 32376.
* llama: opt-in random-access mmap advice for host-resident gather tables
qwen4exp keeps per_layer_token_embd on the host: 26.8 GiB at IQ4_NL, read
by ggml_get_rows as 16 gathers of ~90-170 bytes per token, spread across
16 head regions ~20M rows apart. Measured over 4.75M gathers, no two
consecutive gathers land on the same 4 KiB page, so the readahead the
loader asks for buys nothing here and the whole table ends up cached to
serve about 4% of itself.
llama_mmap applies POSIX_FADV_SEQUENTIAL, MAP_POPULATE and a whole-file
POSIX_MADV_WILLNEED unconditionally. Those are right for streaming the
file once into buffers and wrong for whatever stays mapped afterwards.
Under LLAMA_MMAP_RANDOM the eager pull-in is skipped and the mapping is
advised random once every tensor has been read, so the load itself keeps
its sequential readahead. That alone drops the table to 4.4% resident but
serializes one NVMe latency per gather.
The second half is what pays for it: the PLE input already computes every
row index for the ubatch before the graph runs, so the pages those rows
fall on are handed to the kernel in one batch and the reads overlap.
POSIX_MADV_WILLNEED on POSIX, PrefetchVirtualMemory on Windows, which
takes the discontiguous ranges in a single call.
Off by default and off for every other model: the batched prefetch keys
off "this mapping was advised random", which nothing sets unless the user
opts in.
-c 512 --chunks 60, cold, IQ1_S, mean of 3:
default 35.3 s 26.82 GiB resident (100%)
advice only 104.5 s 1.19 GiB resident (4.4%)
advice + prefetch 34.2 s 1.19 GiB resident (4.4%)
PPL 4.2346 +/- 0.07862 in all three. IQ1_S KLD is unchanged in every
field, including Mean KLD 0.396070 +/- 0.001931 and Same top p 77.325%.
* llama: narrow the random-access mmap advice to the gather table
The advice was applied per mapping: every mapping the model kept got
POSIX_MADV_RANDOM plus a whole-file POSIX_FADV_RANDOM, and the eager
pull-in was skipped for every file. On qwen4exp that also hit
token_embd.weight, which sits 0.33 GiB past the PLE table in the same
shard and is read densely, not by sparse gathers. Measured over
-c 512 --chunks 60 on IQ1_S it fell to 8.45% resident, against 100% with
the feature off.
A model now nominates its gather tables (qwen4exp: per_layer_tok_embd)
and only those byte ranges are advised. The range is rounded out to
whole pages, which on this model takes in 832 bytes before and 192
after. token_embd goes back to 86.55% resident and the PLE table still
drops to 4.44%; smaps shows one VM_RAND_READ VMA of exactly the table
instead of one over all 27.16 GiB that stays mapped.
posix_fadvise is dropped from the narrowed path. POSIX_FADV_RANDOM
ignores its offset and length and marks the whole open file, and the
FMODE_RANDOM it sets is only read by page_cache_sync_ra() on the read()
path, which a fault on a MADV_RANDOM vma never reaches. POSIX_FADV_
DONTNEED does take a range, so the drop mode keeps it.
The eager pull-in is now skipped only for the files holding a nominated
table, and re-issued as WILLNEED over the rest of such a file, so other
shards load exactly as before.
prefetch_rows() keys off the tensor being nominated rather than off a
mapping-level flag, so the batched readahead lands only where the advice
did.
-c 512 --chunks 60, cold, IQ1_S, mean of 3, total wall:
default 32.50 s
whole mapping 30.05 s
narrowed 30.35 s
PPL 4.2061 in all three. IQ1_S KLD is bit-identical with the feature on
and off, including Mean KLD 0.396070 +/- 0.001931 and Same top p
77.325%. tg128 73.65 +/- 0.33 narrowed against 73.49 +/- 0.34 whole.
Assisted-by: Claude
* llama: fold the random-access prefetch into its own feature flag
LLAMA_MMAP_RANDOM_PREFETCH existed to measure the two halves of the feature
apart, and the measurement is done: on a cold cache over the same wikitext
run, MADV_RANDOM without the batched readahead takes 94.4 s against 36.7 s
for an untouched mapping, while the pair together take 34.1 s. Suppressing
the kernel's readahead only pays if we replace it, so the split let a user
select a 2.6x regression through a documented switch.
Keep the accessor, since the call site reads better than a mode comparison,
but derive it from the mode alone.
* FACP (Fewer Acronym Classes Please)
* qwen4exp: bias the QSA selection per block, not per cell
The QSA bias is a graph input, so it is pinned on the host and uploaded every
decode, and at -c 32768 -np 4 its twelve copies were 768 of the 815 MiB of
reserved host compute buffer.
Only one half of it needs a cell: whether the cell sits in the always-visible
tail, and whether its block was pooled. Both are properties of the block. The
other half - empty, other sequence, or in the future - is the plain visible/not
test the attention mask already carries over the same cells, so add that mask
instead of repeating it. The bias then holds one value per block.
A block sits wholly inside or wholly outside the tail because the tail starts on
a block boundary, so one value per block is exact. Cells no block covers keep
their -inf from the mask.
The mask is F16 and the bias F32, and a mixed ggml_add reinterprets the F16
buffer as float rather than converting it, so the cast is required.
reserved host compute buffer at -c 32768 -np 4:
--kv-unified 814.86 -> 238.86 MiB, CUDA0 721.07 -> 421.07 MiB
--no-kv-unified 214.86 -> 70.86 MiB, CUDA0 317.07 -> 265.07 MiB
Selection is unchanged: over 8192 tokens, four times the budget, every QSA
layer returns identical top-k indices and the logprobs are bitwise equal.
Two things a reviewer should know. A cell whose position divides past the last
block is guarded by an assert rather than handled, because no run reached it.
And the mask's same-position M-RoPE rule cannot fire for text and was never
exercised for images, so the 2D case is unverified.
* clean up code comments
* clean up new comments
* revert LLAMA_MMAP_RANDOM
* nits
* replace some changes with ggml-org#27795
* improve the m-rope image for get_prev_tokens
* LazyChunkedTensor
* fix lint
* add some validations
* reduce input nodes
* trim output tokens
* nits
* some more sanity checks
* fix llm_graph_input_ple reuse
* exclude from webgpu test
---------
Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: Xuan Son Nguyen <[email protected]>
Co-authored-by: Pascal <[email protected]>
Co-authored-by: Sigbjørn Skjæret <[email protected]>
(cherry picked from commit 6c84c7d)
Adapted to 1bit/hrx-vulkan-patched: only QWEN4EXP added to the hybrid/rope/memory lists
(not DEEPSEEK4, MINIMAX_01, QWEN3TTS); LLAMA_MAX_EXPERTS kept at 512; get_arr keeps this
branch's asserts plus a UINT64 case; tensor split rules take only the indexer and PLE caches;
llama_kv_cache::get_cells added from upstream ggml-org#26338.
(cherry picked from commit 6fe7498)
* bench: add --tensor-read-lazy * rm the alias * rename to LLAMA_LAZY_MODE_* (cherry picked from commit 50f068f)
* force lazy tensor on cpu if lazy is on * llama: improve TENSOR_READ_LAZY handling (cherry picked from commit 2578138)
…gml-org#27969) Rename the --tensor-read-lazy CLI argument to --lazy-mode, to match the internal lazy_mode parameter, and add a -lzm shorthand. Sync the READMEs. Assisted-by: pi:llama.cpp/Qwen3.8-27B (cherry picked from commit bebc935)
* qwen4exp: sum the indexer heads by slices The head reduction went through a transpose and a sum_rows over ne[1], which left sum_rows with ne0 = 4, one block per row for a four element reduction, and the transpose copied the whole block by token surface twice on the way in. The heads are adjacent on ne[1], so each one is a strided view and the sum is a short chain of adds. RTX PRO 6000, Qwen3.8-Flash-Next UD-Q4_K_XL, fa on, 55k context, warm runs on top of ggml-org#28011: prompt processing 2170 -> 2366 t/s Generation is unaffected. The removed work scales with n_blocks by n_tokens, so the gain grows with context and with ubatch size. * qwen4exp: drop the redundant cont on the indexer query rope returns a freshly allocated, contiguous tensor, so the reshape that feeds the matmul does not need a copy. ggml_reshape_3d asserts contiguity, so a layout that would need the cont cannot slip through silently. Greedy output is unchanged token for token. Address review from @ggerganov (cherry picked from commit 09412af)
MTP speculative decoding needs the target state to move back by the number of rejected draft tokens. Without rollback support the context is classified as SEQ_RM_TYPE_FULL and the server serializes the whole recurrent state to host memory on every round, which costs more than the drafting saves. The recurrent cache already holds n_rs_seq + 1 snapshot planes and the delta net writes its SSM state into them, but build_conv_state_at wrote a single plane, so a rollback restored a convolution history that was never captured. It now writes one snapshot per slot, each ending one token earlier, for the delta net QKV convolution and for the PLE convolution alike. Measured on Qwen3.8-Flash-Next UD-Q4_K_XL with the standalone MTP draft, n-max 3 and a single slot: decoding reaches 183 tok/s on code and 144 tok/s on prose. The same branch before this change, where the server falls back to checkpointing the state to host memory, reaches 123 and 83 tok/s, for 108 tok/s without a draft. (cherry picked from commit 0eadefe)
…add tests (ggml-org#27941) * qwen4exp: follow up fixes * -kvu NaN collapse fix Assisted-by: Claude * indexer cache ext.x/ext.y restore fix Assisted-by: Claude * kv-cells: rename seq_set to seq_get_all seq_get is already taken by the single-id getter, so the suggested name cannot be overloaded on return type alone. Assisted-by: Claude * memory-hybrid-idx: implement set_input_qsa on the memory class The context held the whole implementation, where the pattern elsewhere is a thin context forwarding to the memory class, as llama_kv_cache_context does for set_input_kq_mask. The body reads no context state, so it moves unchanged and the context keeps a forwarder. Also shortens the seq_get_all comment as suggested. * tests: check that a sequence state survives a save/restore round-trip Saves seq 0, erases it, restores the blob and saves again, requiring the two blobs to match. Compares blobs rather than generated text, which cannot see a field dropped on the way back in. Note this passes on master for qwen4exp, so it does not demonstrate the ext.x/ext.y drop this PR fixes; reaching that needs 2D mrope content. * tests: give the synthetic qwen4exp a PLE so the state test bites has_cell_ext() is n_pos_per_embd() > 1 || ple_n_heads > 0, and the indexer cache sets rope_type = NONE, so without a PLE it serializes no cell ext at all and the round-trip test cannot see a dropped ext.x/ext.y. With one, removing the ext_set restore in state_read_meta fails the test: 198 of 335692 bytes differ, first at offset 282092. Loading such a model needed two fixes: - the row count of per_layer_token_embd came from require_weight(), which a model synthesised from metadata alone has no file to answer. Derive it from the head ranges and prefer the file's padded count where there is one. - the PLE conv history is a row of the recurrent cache, so a PLE on a full attention layer dereferenced a null p_l. Reject it at load time instead. The meta mirror is skipped for qwen4exp. It returned NaN logits before this fixture carried a PLE, which the nmse check passes since a NaN comparison is false, and aborts with one. -sm tensor on real devices works. Assisted-by: Claude * llama: disable -sm tensor for qwen4exp test-llama-archs skipped the tensor split for this arch from inside the test, so the arch still advertised support it does not have. Declare it in llm_arch_supports_sm_tensor instead and drop the test-side exception; the existing llm_arch_supports_sm_tensor branch then does the skipping. Assisted-by: Claude (cherry picked from commit 36b1015) Adapted: tests/test-save-load-state.cpp left as on this branch (the round-trip test builds on tests this branch lacks).
…gml-org#28040) get_prev_tokens() rebuilt a (seq, pos) -> token hash map on every ubatch by walking all used cells, while llama_kv_cells already keeps an ordered index of the positions of each sequence in seq_pos, updated on every cell mutation to serve seq_pos_min() and seq_pos_max(). The index now stores (pos, cell) pairs in a std::set instead of a position -> count map, so a repeated position (cache reuse via rm + add, vision inputs with shared positions) yields distinct entries and the removal of a cell erases its own pair. The new seq_pos_tok_le() returns the token of the cell at the largest position <= p in logarithmic time, which is exactly what the old window lookup and its M-RoPE gap fallback computed together. get_prev_tokens() shrinks to a direct lookup per (token, offset) and for_each_token_in() goes away with its only caller. The kv-cache keeps no n-gram logic of its own. Measured on Qwen3.8-Flash-Next UD-Q4_K_XL at 71k context, alternating two binaries with the first run discarded: tg 69.3 -> 72.7 t/s (+4.9%), pp unchanged at ~2720 t/s, greedy output identical, needle retrieved. (cherry picked from commit b356fa2)
* models: use flash-linear-attention's l2norm for gated delta net q/k
The GDN q/k normalization is defined by flash-linear-attention as
l2norm(x) = x * rsqrt(sum(x*x) + eps)
with eps inside the root. Every GDN call site in the tree uses ggml_l2_norm
instead, which is x / max(sqrt(sum(x*x)), eps), i.e.
torch.nn.functional.normalize - its CUDA kernel cites that page.
The clamp never engages at these magnitudes, so in practice llama.cpp
normalizes with no epsilon at all where the reference has one inside the
root.
transformers made the same substitution when it first added Qwen3-Next and
corrected it three days later in huggingface/transformers#40842, 'Fix the
misalignment between the l2norm in GDN of Qwen3-Next and the implementation
in the FLA library'. vLLM and SGLang vendor FLA rather than reimplementing
it, so neither ever had the clamp.
eps keeps coming from the checkpoint, exactly as every call site already
passed it. The references hardcode 1e-6 for this norm; that is a separate
question and the two agree on every GDN checkpoint in the wild.
ggml_l2_norm itself is correct and unchanged, as is rwkv7-base, its original
caller, which passes normalize's own default eps of 1e-12.
No new ggml op: rms_norm already carries eps inside the root, so
rms_norm(x, eps/n) * (1/sqrt(n)) is exactly x * rsqrt(sum(x*x) + eps).
* Update src/models/models.h
Co-authored-by: Georgi Gerganov <[email protected]>
---------
Co-authored-by: Georgi Gerganov <[email protected]>
(cherry picked from commit 5fdfa62; only src/models/models.h and src/models/qwen4exp.cpp:
the other models on this branch keep ggml_l2_norm)
* qwen4exp: enable rms_norm + mul fusion * use TENSOR_ALLOW_RESHAPE (cherry picked from commit 41abbfd)
(cherry picked from commit 37b53fd) Adapted: Metal, SYCL and Vulkan keep this branch's supports_op (they do not claim the DSV4 hc ops here); HRX has no hc kernel, so these ops run on the CPU.
….cpp PR ggml-org#28243) The net change of ggml-org/llama.cpp PR ggml-org#28243 (danielhanchen/llama.cpp qwen4exp/mtp at 6fcaa16, by Daniel Han and Ryan Monsurate), applied onto release v0.5.0 as one commit. Carried on 1bit/vulkan-upstream until upstream merges it; the engine's bump-llama-vulkan rebases it onto each new release and drops it once it is upstream. (cherry picked from commit 62484fb) Adapted: converter changes (conversion/, convert_hf_to_gguf.py) not taken, the runtime reads Unsloth's GGUFs; n_ff_exp stays a scalar on this branch; only QWEN4EXP joins the hybrid MTP memory condition.
A draft head GGUF may now carry blk.<L>.nextn.shared_head_head.weight with K rows plus an
I64 d2t [K] (draft row -> token id). The draft pass runs the K-row head and scatters its
logits into a full-vocabulary row that is -inf elsewhere, the same set_rows scatter DFlash
uses. The target still verifies every drafted token. Our code is in
src/models/qwen4exp-draft-vocab.{h,cpp}; qwen4exp.cpp keeps two hooks.
Qwen3.8-Flash-Next UD-Q4_K_XL on Strix Halo (Vulkan, greedy, draft length 3, rounds 2-3 of
3): the 65,536-id English + code list from dime-online/qwen3.8-Flash-DGX-UltraFast turns the
borrowed 644 MiB Q8_0 output matrix into a 170 MiB head. Code 47.8 -> 52.1 tok/s, prose
38.6 -> 42.2, 768-token code 45.8 -> 48.3; step 76 -> 70 ms; acceptance 186/207 both. A
French prompt is slower (46.4 -> 39.6): its tokens are outside the list. Text in rounds 2-3
is the same as with the full head; neither is token-identical to decoding without a draft
(near-tie flips from batched verification, present with the stock head too).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
(cherry picked from commit 5ed92e9)
…e or repeated The reduced draft head scatters its K logits into a full-vocabulary row with set_rows at the d2t ids, which trusts them: an id < 0 or >= n_vocab writes outside the row, and a repeated id silently drops a row. The loader now reads the K int64 ids from the file (before any graph uses them) and fails with the offending index and id. Review follow-up to #56. Co-Authored-By: Claude Opus 5.5 <[email protected]> (cherry picked from commit 9a8a872)
…d_norm) HRX rms_norm requires a materialized (non-view) input. qwen4exp feeds strided ggml_view slices into normalization: the gated-delta-net L2-norm of q_conv/k_conv (build_gdn_l2_norm) and the per-head q/k norms via build_norm. Insert ggml_cont for non-contiguous / view-op inputs. No-op for the contiguous residual-stream tensors other arches (e.g. qwen35 27B) pass, so their HRX path is unchanged. Clears the "unsupported HRX node: RMS_NORM<-VIEW" abort on Qwen3.8-Flash-Next. Remaining HRX blockers (IMRoPE mode 40, MoE mul_mat_id input_size=640) are separate kernel work. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…IQ4_NL/IQ2_S/640-wide experts to CPU)
Make the full Qwen3.8-Flash-Next (arch qwen4exp) forward pass complete on the
HRX backend so llama-perplexity runs and a KLD can be measured.
Two blockers fixed, logic in a new owned header (qwen4exp-hrx-support.h), with
only minimal one-line hooks into the AMD matcher/backend files:
1) ROPE matcher rejected qwen4exp's GGML_ROPE_TYPE_IMROPE (mode 40) + 4-section
positions. For text decode llama.cpp sets p_t==p_h==p_w==token pos, p_e==0; for
this model's sections [11,11,10,0] (sect_dims 32 = n_dims/2) ggml_mrope_cache_init
never selects p_e, so the interleaved rotation collapses to a plain NEOX rotation
on the shared position -- which the existing rope_f32 kernel computes bit-exactly.
The matcher now accepts a collapsible IMROPE, admits the 4*token_count positions
layout, and hands the kernel NEOX mode. No kernel change (proven bit-exact).
2) MUL_MAT_ID routed-expert GEMM could not run on HRX: UD-IQ4_XS gate/up experts are
IQ4_NL (shared f16 dequant mis-applies the XOR-12 nibble remap -> garbage),
UD-IQ3_XXS experts are IQ2_S (no HRX MUL_MAT_ID path), and the Q8_0 down-proj has a
640-wide contraction that violates the kernel's 256-multiple input_size constraint
("value 640 violates constraint 'mul'"). device_supports_op now keeps every such
MUL_MAT_ID (bad weight type, or input_size % 256 != 0) on CPU, so the forward pass
completes correctly instead of failing JIT link with no fallback.
Measured (strixhalo, performance mode, power_mode=performance, HRX0, 12 chunks, -c 512
-b 512 -ngl 99 -fa on, wikitext-2 test; MoE experts on CPU):
* "Paris" generation on HRX0: coherent ("...directly state Paris as the answer").
* Correctness vs CPU (UD-IQ4_XS): HRX0 PPL 1.7997 +/- 0.0507 vs CPU PPL 1.8202 +/-
0.0527 (~1.1%, within error bars; benign f16-WMMA rounding, not a bug).
* KLD UD-IQ3_XXS vs UD-IQ4_XS reference (both HRX0): mean 0.3118 +/- 0.0138,
median 0.0179, 99% 3.950, 99.9% 6.076, max 9.243, Same-top-p 87.42%,
PPL(Q)/PPL(base) 1.0927, PPL(Q)-PPL(base) 0.1665.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Author
bong-water-water-bong
pushed a commit
that referenced
this pull request
Nov 12, 2026
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: ROCm/hrx-system#1512
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…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What this does
Brings Qwen3.8-Flash-Next (llama.cpp arch
qwen4exp) onto the HRX (gfx1151) backend: the model now completes a full forward pass +llama-perplexityon-dev HRX0with coherent output. First time Flash-Next decodes on HRX.Two HRX enablement commits (mine), on top of the vendored upstream
qwen4exparch:5a08be1ff— materialize view inputs to HRXrms_norm.build_gdn_l2_norm(GDN L2-norm of the strided q_conv/k_conv views) andbuild_normfed a non-contiguousVIEWinto HRXrms_norm, which needs a materialized input →ggml_contguard. Clears theunsupported HRX node 48: RMS_NORM<-VIEW[128,16,T]->SCALEabort. No-op for 27B/other arches.36fa267b1— decode Flash-Next on HRX (IMROPE→NEOX rope + route problem experts to CPU).GGML_ROPE_TYPE_IMROPE(mode 40) + a 4-section position tensor. For this model (sections=[11,11,10,0], text decode p_t=p_h=p_w, p_e never selected) IMROPE is arithmetically identical to NEOX, which the existingrope_f32kernel already computes. Matcher now accepts a provably-collapsible IMROPE and passes NEOX mode — bit-exact by construction, no new kernel.mul_mat_id: routed to CPU when the weight type has no correct HRX path (IQ4_NL XOR-12 nibble-remap bug; IQ2_S no path) orinput_size % 256 != 0(the 640-wide Q8_0 down-proj), so the graph completes with a clean fallback instead of a no-fallback JIT-link failure.New logic lives in our own Apache-headed
ggml/src/ggml-hrx/qwen4exp-hrx-support.h; AMD files get only minimal hooks.Correctness (strixhalo, HRX0, 12 chunks wikitext-2, -c512 -b512 -ngl99 -fa on; MoE experts on CPU)
KLD deliverable (UD-IQ3_XXS vs UD-IQ4_XS reference, both HRX0, 12 chunks)
Caveat: this is KLD vs UD-IQ4_XS (extra drift beyond IQ4), not vs 16-bit — the box cant hold the ~350 GB BF16 — so it is not comparable to Paitons vs-16-bit W3A8 figures. 12 chunks (queue-contended box); 40-chunk harness
~/lb/fnkld/fnkld.shworks for a quiet-box re-run.Integration notes / not yet mergeable
bd5b2970b, 251 commits behind1bit/hrx-vulkan-patched, and carries the vendored upstreamqwen4exparch (16 upstream commits, original authorship kept) that the HRX line does not yet have. It needs a rebase onto the current tip before merge — opened as a draft.533-gdn-rms-order(overlaps the GDN rms-norm change) and hrx: the absent bias/residual slots of mul_mat_id_postops bind a read-only value (engine #533 verify) #131 (mul_mat_id bias/residual slots). Rebaser should check whether5a08be1ffis subsumed by hrx: the fused GDN selected-snapshot programme keeps its gate producer before the kernel (engine #533) [verify pending] #133.Follow-ups (owner: these are GEAK tasks)
Experts currently run on CPU (decode ~28 s/tok; perplexity fine). Putting them on HRX needs three new kernels — a correct IQ4_NL
mul_mat_id(fix the XOR-12 remap), an IQ2_Smul_mat_id, and a 640-capable/paddedmul_mat_id— being set up as GEAK generation tasks.🤖 Generated with Claude Code