Skip to content

llama-memory-hybrid-idx : no abort on image cells sharing a tail slot when unranked - #261

Merged
Nathanw1014 merged 1 commit into
halo-box:masterfrom
rcfa:pr/qsa-tail-slot
Nov 9, 2026
Merged

Nathanw1014 merged 1 commit into
halo-box:masterfrom
rcfa:pr/qsa-tail-slot

Conversation

@rcfa

@rcfa rcfa commented Nov 7, 2026

Copy link
Copy Markdown

Overview

set_input_qsa_scan ranks a stream's cells (by position, then ext.y, ext.x) only when the stream holds one
sequence. With several sequences, an image's cells keep their repeated M-RoPE position. Two cells of the ubatch's own
sequence can then map to the same group slot, and filling group_members aborts. On master 62a3f41:

src/llama-memory-hybrid-idx.cpp:853: GGML_ASSERT(group_members[slot]<0 || group_members[slot]==j) failed
#6  llama_memory_hybrid_idx::set_input_qsa_scan(...)
#7  llama_memory_hybrid_idx::set_input_qsa_blocks(...)
#8  llama_model_qwen4exp::llm_graph_input_qsa::set_input(llama_ubatch const*)
...
#11 llama_context::decode(llama_batch_ext const&)
#12 common_speculative_impl_draft_mtp::process(common_batch const&)

group_members is only read for the query's tail block. This PR marks such a slot ambiguous (-2) and does not abort.
If a tail block ever reads an ambiguous slot, that cell is left out of the tail, with a one-time warning. We have not
seen that happen.

Repro on master (qwen4exp, -np 4 -kvu, MTP draft, mmproj, RAM prompt cache on). An image chat that comes
back from the prompt cache, next to other sequences, brings its draft state with it:

  1. Fill all four slots: an image chat in slot 1, 16k tokens of text in slot 0, and 512 tokens each in slots 2 and 3.
    The image chat is the least recently used.
  2. Send a 256-token prompt without id_slot. LRU takes slot 1, so the image chat goes to the prompt cache with its
    draft state.
  3. Send the image chat's follow-up without id_slot. LRU takes slot 0, and the image chat is loaded back from the
    cache into slot 0. The draft's process() then aborts.

We first hit it with a slot file that also carries the draft state (#171): a text slot and an image chat saved,
restored after a restart, and a text follow-up. That aborts with f16 and q8_0 K/V alike. Master's /slots restore
loads only the target context, so on master alone it is the prompt cache that reaches this.

Measurements

No speed claim: the change only touches a path that aborted before.

Device:     Ryzen AI 9 HX PRO 370 / Radeon 890M (gfx1150, Strix Point - NOT Strix Halo) / Minisforum N5 PRO, BIOS 1.05
Memory:     96 GB DDR5-5600 (2 x 48 GB SO-DIMM, ECC)
Power:      BIOS defaults; amdgpu power_dpm_force_performance_level=auto; cpufreq governor powersave (amd-pstate)
BIOS:       UMA split 48 GB
Kernel:     7.2.15+kali-amd64, amdgpu params: amdgpu.gttsize=73728 ttm.pages_limit=8650752
Backend:    Vulkan RADV, Mesa 26.1.6 (libvulkan1 1.4.363)
Build:      -DGGML_VULKAN=ON -DLLAMA_CURL=OFF -DCMAKE_BUILD_TYPE=Release -DCMAKE_BUILD_RPATH_USE_ORIGIN=ON (gcc 16.2)
Baseline:   master 62a3f4144, built and run in the same session from the same worktree, separate bin directories
Change:     2785e389d
Model:      ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF, IQ3_XXS; MTP: shared head mtp-Qwen3.8-Flash-Next-shared-Q4_K_M
            (Unsloth); mmproj F16 (Unsloth)

Server: GGML_VK_MMV_NO_SPLIT=1 llama-server -m IQ3_XXS -ngl 99 --load-mode none --lazy-mode on-direct -c 131072 -np 4 -kvu --cache-ram 2048 --no-cache-idle-slots -ub 2048 -ctk f16 -ctv f16 --mmproj mmproj-F16 --spec-type draft-mtp -md mtp-shared-Q4_K_M -ngld 99 --spec-draft-n-max 2. The prompts were greedy (temperature 0), with the text taken
from one long English document.

master 62a3f41 this PR
prompt-cache repro above, the follow-up server aborts (assert above) 39 prompt tokens (loaded from the cache), 16.0 t/s, answer quotes the image ("3", "red")
slot files without draft state (master's /slots): 16k text and an image chat saved, restored into slots 2 and 1 after a restart, text and image follow-ups; then the same back no abort no abort
greedy tokens of the four 128-token text continuations in that run reference identical

Correctness:

  • On every step that also ran on master, the PR produced the same greedy tokens, four continuations of 128 tokens
    each, and the same answers.
  • test-qsa-prefix, test-qsa-recover and test-qsa-fast pass on master and on this PR (CPU, no device).
  • No ggml op, kernel or graph changes, so test-backend-ops and llama-bench do not apply.
  • Not run: the corpus logit comparison. A single-sequence llama-perplexity run never reaches this path, because
    it needs several sequences in the stream and image cells.
  • Status: TARGET PASS for the repro. The changed path is the one that aborted, and nothing else changed in our runs.

Requirements

  • I have read and agree with the contributing guidelines
  • This change is Strix Halo specific, or justified by measurements on Strix Halo: it fixes the fork's qwen4exp QSA
    memory, which only this fork has. Our measurements come from Strix Point (gfx1150), not Strix Halo.
  • AI usage disclosure: AGENT-AUTHORED. Claude (Claude Code) found the bug, wrote the fix, this description and the
    repro tools, and ran every measurement. The commit carries Assisted-by: Claude Code. rcfa reviewed and owns it.
  • What was NOT verified:
    • Strix Halo (gfx1151), ROCm, CUDA and CPU-only builds. The change is backend-independent host code.
    • A tail block that really reads an ambiguous slot. We never produced one, so the warning path has not run.
    • Audio or video inputs, and models other than Qwen3.8-Flash-Next.

🤖 Generated with Claude Code

… when unranked

set_input_qsa_scan ranks cells (pos, then ext.y, ext.x) only when one sequence is in the stream.
With several, an image's cells keep their repeated M-RoPE position, so two cells of the ubatch's
own sequence can map to one group slot, and building group_members aborted:

  GGML_ASSERT(group_members[slot]<0 || group_members[slot]==j) failed

group_members is read only for the query's tail block. Such a slot is now marked ambiguous (-2)
instead; if a tail ever reads one, that cell is left out of the tail with a one-time warning.

Repro (Flash-Next GSQ-RCO IQ3_XXS, Vulkan, -np 4 -kvu, MTP shared head, mmproj): a 16k text
conversation in slot 2 and an image chat in slot 1, both saved and restored, then a
text follow-up in slot 1: the MTP draft's process() aborts (the same follow-up without the restores passed). f16 and q8_0 K/V alike; the target
context did not abort in these runs.

Assisted-by: Claude Code

@Nathanw1014 Nathanw1014 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks for this. Approving: we reproduced the assert on gfx1151 with your server line, #261 makes it go away, and we found no cost to it (details below).

It fixes the symptom, though. We traced why the draft reaches the scalar route at all: the cause is in the KV state save/restore, not in the tail loop. A small restore fix is below. You're welcome to fold it into this PR; otherwise we'll open a follow-up PR with it once this one merges.

Repro (Strix Halo, master 62a3f41)

Your server line verbatim (Flash-Next UD-IQ3_XXS, shared MTP Q4_K_M draft, mmproj, -np 4 -kvu --cache-ram 2048). Slot choice was LRU only (--slot-prompt-similarity 0) and thinking was off.

  1. Image chat in slot 1.
  2. A ~16k text prompt in slot 0.
  3. Short prompts in slots 2 and 3.
  4. A short prompt with no id_slot.
  5. The image follow-up with no id_slot. It lands in slot 0 and the image chat comes back from the prompt cache.

On master, step 5 aborts in common_speculative_impl_draft_mtp::process -> set_input_qsa_scan:

src/llama-memory-hybrid-idx.cpp:853: GGML_ASSERT(group_members[slot]<0 || group_members[slot]==j) failed

With #261 there's no abort, and the follow-up answers "3 red", the same as a -np 1 run of the same chat. The new warning never fired in that run, so the skip path itself wasn't exercised.

Root cause

The scalar route should never run here. qsa_scalar_visibility_cells (src/prefix.h) refuses it when the cache holds several sequences and 2-D image cells (multiseq+2d). We logged that check in both contexts on the follow-up's first draft ubatch:

  • target context: 195 cells with a 2-D position -> multiseq+2d, masked route
  • draft context: 0 cells with a 2-D position -> scalar route -> unranked image cells share positions -> collision -> assert

The draft's indexer cells lost their image x/y when the image chat went through the prompt cache:

  • The indexer cache runs with rope_type = LLAMA_ROPE_TYPE_NONE (llama-memory-hybrid-idx.cpp:101).
  • llama_kv_cache::has_cell_ext() is n_pos_per_embd() > 1 || ple_n_heads > 0.
  • The shared MTP head has no PLE keys, so for the draft's indexer this returns false. Its state is written without ext, and the restore rebuilds x = y = 0.
  • The main model's indexer keeps ext only because of PLE (ple_n_heads = 16), which is why the target context is fine.

Fix we tested

After the mirrored indexer restore, copy x/y from the attention cache's cells. The attention cache is M-RoPE, so its state already carries them. The indexer is restored into the same cell indices (sinfos_attn), so the copy is index for index. The save format doesn't change.

--- a/src/llama-kv-cache.h
+++ b/src/llama-kv-cache.h
@@ -186,6 +186,10 @@ public:
     // undo a state_read() of seq_id (-1 for the whole cache) that another memory module failed to complete
     void state_clear(llama_seq_id seq_id);
 
+    // after a mirrored state_read_sinfo(): take the 2D position of the restored cells from src (same layout)
+    // the qwen4exp indexer has no rope of its own, so its saved state has no x/y, yet the QSA visibility rule reads them
+    void ext_2d_copy(const llama_kv_cache & src, const slot_info_vec_t & sinfos);
+
--- a/src/llama-kv-cache.cpp
+++ b/src/llama-kv-cache.cpp
@@ -2546,6 +2546,34 @@
+void llama_kv_cache::ext_2d_copy(const llama_kv_cache & src, const slot_info_vec_t & sinfos) {
+    // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS]
+    if (other || src.hparams.n_pos_per_embd() <= 1) {
+        return;
+    }
+
+    GGML_ASSERT(src.n_stream == n_stream);
+
+    for (const auto & sinfo : sinfos) {
+        if (sinfo.empty()) {
+            continue;
+        }
+
+        const uint32_t strm = sinfo.strm[0];
+
+        auto       & cells     = v_cells[strm];
+        const auto & src_cells = src.v_cells[strm];
+
+        for (const uint32_t idx : sinfo.idxs[0]) {
+            // only x and y: tok is this cache's own (PLE)
+            llama_kv_cell_ext ext = cells.ext_get(idx);
+            ext.x = src_cells.ext_get(idx).x;
+            ext.y = src_cells.ext_get(idx).y;
+            cells.ext_set(idx, ext);
+        }
+    }
+}
+
--- a/src/llama-memory-hybrid-idx.cpp
+++ b/src/llama-memory-hybrid-idx.cpp
@@ -386,6 +386,7 @@
         if (mem_idx) {
             mem_idx->state_read_sinfo(io, seq_id, flags, nullptr, &sinfos_attn);
+            mem_idx->ext_2d_copy(*get_mem_attn(), sinfos_attn);

Results with this patch on master (and without #261):

  • #261 sequence: no assert, and no group-slot collisions. The draft context now sees 195 cells with a 2-D position and takes multiseq+2d, as the target does. The follow-up answers "3 red", the same as the -np 1 run.
  • Slot save, restart and restore: both slots restore and the follow-up answers "3 red".
  • QSA tests: test-qsa-prefix, test-qsa-recover and test-qsa-fast pass.

Not covered:

  • The whole-cache restore path (seq_id == -1). The patch handles it, since sinfos_attn is filled there too, but no test here ran it.
  • The run had extra debug logging applied alongside the patch.

Alternative

Making has_cell_ext() also true when model.hparams.n_pos_per_embd() > 1 fixes it too. We ran that version with the same results. It changes the bytes saved for the indexer of qwen4exp models without PLE, though, and the state format has no version flag. Slot files hold target state only today, so the main exposure is target slot files from a non-PLE qwen4exp model, plus draft state in slot files if #171 lands. The copy avoids that.

On #261 itself

We tested whether the -2 skip costs anything. We also put the image after the question text, so its cells end right before the follow-up. Master still asserts there. With #261 the warning never fired in any run, so the skip itself never ran. The collisions all landed outside the query's tail block, and the assert fires on them anyway.

On a long image description (up to 200 tokens: 108 generated with the image first, 200 with it last) after the prompt-cache restore, #261 alone and the restore fix alone give:

layout text draft accepted, #261 draft accepted, restore fix
image first identical 58/100 58/100
image last identical 113/172 114/170

So here the zeroed positions cost nothing we could measure: same text, same draft acceptance. The assert is stricter than what the tail actually reads. So #261 is fine as a guard, and the restore fix makes the draft see the same image layout as the target. We couldn't build a case that reaches the skip, so what it does when it fires is still untested.

(Side note: these -np 4 answers differ in wording from a -np 1 run of the same chat after about 130-300 characters, in every arm including the restore fix. We haven't looked into why.)

@rcfa

rcfa commented Nov 9, 2026

Copy link
Copy Markdown
Author

Thanks for tracing this and for reproducing it on gfx1151. We read the restore path against your analysis and agree with it.

Please open the restore fix as your follow-up. It's your work and you've tested it, and this PR can stay as the guard you approved.

One point on ordering against #262. With the fix, the draft's indexer sees the image's 2-D cells, so qsa_scalar_visibility_cells returns false in the draft context too. A graph re-reserve there after a memory update could then take the masked route at its worst-case shape, which is the growth #262 removes for the target (+10.95 GiB at -c 131072 on Strix Point). We haven't run that combination on master, and our own stack already has #262. We'd suggest #262 lands first, or together with it.

Once the follow-up is up, we can run the path you couldn't: slot files that carry draft state (#171) on gfx1150 at -np 4. That's where we first hit the abort. The copy leaves the file format alone, which suits us.

Written by Claude Code (an AI agent); rcfa owns it.

@Nathanw1014
Nathanw1014 merged commit ec97a34 into halo-box:master Nov 9, 2026
1 check passed
@rcfa
rcfa deleted the pr/qsa-tail-slot branch November 27, 2026 19:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants