Repository navigation
llama-memory-hybrid-idx : take the indexer cells' image 2D position from the attention cache on restore - #272
Conversation
…rom the attention cache on restore The qwen4exp indexer cache has no rope of its own (rope_type NONE), so has_cell_ext() is false for it unless PLE is on. Its saved state then has no x/y and a restore leaves image cells at 0,0. The MTP draft head has no PLE keys, so after a prompt-cache restore the draft context saw no 2D cells, qsa_scalar_visibility_cells() allowed the scalar route with several sequences in the cache, and unranked image cells collided in set_input_qsa_scan(). The indexer is restored into the attention cache's cell layout, and the attention cache (M-RoPE) carries the 2D position, so copy x/y from it index for index. The state format does not change. Assisted-by: Claude Opus 5.5
dzannotti
left a comment
There was a problem hiding this comment.
Verdict
No blocking issues. After a restore, the indexer cells now get the image 2D positions from the attention cache, and the QSA scalar route is refused again when an image sequence shares the cache with other sequences. It needs one maintainer approval because it changes KV state restore code.
Direction
Accept. This is the smallest fix for the root cause behind #261. It adds one member to llama_kv_cache and one call in llama_memory_hybrid_idx::state_read, and it does not change the state format. Upstream llama-memory-hybrid-idx.cpp has the same restore path without the copy, so the next upstream sync should keep this hunk.
Asks
- Should fix: add a regression test. No test calls
llama_memory_hybrid_idx::state_readtoday. A small one fails on master and passes here. Use a tiny qwen4exp model as intest_mtp_cache_only_devintests/test-llama-archs.cpp, PLE off, one image block with 2D positions,llama_state_seq_get_data,llama_state_seq_set_datainto a fresh context, then check that each indexer cell has the same x/y as the attention cell. A host-only version next totest_scan_foreign_imageintests/test-qsa-prefix.cppalso works. CONTRIBUTING.md asks for a regression test where it is practical, and here it is. - Should fix: draft #276 changes the same lines in
src/llama-memory-hybrid-idx.cpp:389(aroundstate_read_sinfo) and the 2D check insrc/prefix.h. The conflict is small. Whichever PR lands second must keep theext_2d_copy()call directly after the indexerstate_read_sinfo().
Nits: the commit title has 103 characters (for example "llama-memory-hybrid-idx : copy indexer 2D positions from the attention cache on restore"). The GGML_ASSERT on the stream count in ext_2d_copy() is in a path that otherwise throws and drops the state; it cannot fire today.
Correctness
PASS for the claimed case on Vulkan and ROCm (not a full-suite pass). A restore test on a tiny random qwen4exp model shows the bug on master and the fix here. With PLE off, master restores every indexer cell with x=y=0, and the scalar visibility check changes its answer, also for an image sequence restored next to another sequence (the #261 trigger). With this PR, every cell matches the attention cache in all restore paths, and the next-token logits are byte-equal to a context that never saved. The state blobs are byte-identical, and each side loads the other's blobs.
Normal inference does not change. On the qwen4exp target and on a dense model, the f32 final logits, prompt tokens, greedy decode and KLD files are identical on all four corpora (KLD on the target at -c 1024, see the details). test-llama-context, test-llama-archs and the test-qsa-* tests give the same results on both trees. The full test-backend-ops suite did not run, because no op changed.
Verification
Strix Halo (gfx1151), Vulkan (RADV) and ROCm, with ROCm checks at HIP_LAUNCH_BLOCKING unset and =1. We merged the PR into master 093c552 (the PR was 42 commits behind master) and compared that merge against master. A llama-bench sanity check (pp512/tg128) is within noise on both backends.
Not tested
The full #261 reproduction with the MTP draft and an mmproj on the real model, draft state in slot files, the llama-bench depth sweep, and the full test-backend-ops suite.
Thanks for tracking this down to the root cause.
Review made with AI on behalf of the strix-llama.cpp maintainers.
Full verification (for reproduction and agents)
Environment
- Ubuntu 26.04.1 LTS, kernel 7.0.0-43-generic, gcc 15.2.0, cmake 4.2.3, ninja 1.13.2
- ROCm 10.1 (hipconfig 7.16.26385), AMD clang 24.0.0git d6f6cb691863
- Mesa RADV 26.0.8, Vulkan loader 1.4.341, glslc shaderc 2026.1; Radeon 8060S (gfx1151)
Compared
- master tip (base): 093c552
- PR head: 2960345
- PR merged into master (head side, local only): 8faddce7005be3f7f81a45db302f88ca94411766
- merge base: ec97a34, 42 commits behind master. Clean merge; the merged diff equals the PR diff.
Build
Same flags for both trees:
cmake -S <tree> -B <tree>/build-vk -G Ninja -DCMAKE_BUILD_TYPE=Release -DGGML_VULKAN=ON -DGGML_HIP=OFF
cmake -S <tree> -B <tree>/build-hip -G Ninja -DCMAKE_BUILD_TYPE=Release -DGGML_HIP=ON -DGGML_VULKAN=OFF -DGPU_TARGETS=gfx1151 \
-DCMAKE_HIP_COMPILER=$(hipconfig -l)/clang -DCMAKE_PREFIX_PATH=$(hipconfig -R)
cmake --build <tree>/build-<be> -j 16
Models
| Model | Source | sha256 |
|---|---|---|
| qwen4exp target (85.65 GiB) | agentionai/Qwen3.8-Flash-Next-Gyro-GGUF, Qwen3.8-Flash-Next-Gyro-M-TQ2_0.gguf | 7aa36d15131d255179ab6c87fa9c9f81a0b541fc9e81e959d4c3e29eb20feb5f |
| qwen2.5-1.5b-instruct-q4_k_m.gguf (dense) | Qwen/Qwen2.5-1.5B-Instruct-GGUF | 6a1a2eb6d15622bf3c96857206351ba97e1af16c30d7a74ee38970e434e9407e |
| granite-4.0-h-1b (hybrid, test-llama-context) | granite-4.0-h-1b-Q4_K_M.gguf | da3d737121a96f3c9a316685212376257a7f167b74380855666dd488d6af3bcb |
| tiny random qwen4exp | generated in memory: get_gguf_ctx(LLM_ARCH_QWEN4EXP, true) and set_tensor_data from tests/test-llama-archs.cpp, seed 1234, stdev 0.1; IMROPE sections 16/16/16/16, indexer on (compress ratio 4), PLE on (ple.layers=[0]) or off (ple.layers=[]); MTP variant uses the test_mtp_cache_only_dev overrides (nextn 1, n_embd 32, sections 8/8/0/0, MTP context) |
n/a |
Commands
Targeted restore test (a standalone C++ program built per tree against that tree's src/ headers and libllama, nothing added to the trees):
g++ -std=c++17 -O1 -DNDEBUG -I<tree>/include -I<tree>/ggml/include -I<tree>/src -I<tree>/common restore2d.cpp \
-o restore2d-<side> -L<tree>/build-<be>/bin -lllama -lggml -lggml-base
restore2d-<side> --dev CPU|Vulkan0|ROCm0 --ple 0|1 --unified 0|1 --mtp 0|1 --save-dir <dir> [--load-dir <other side's dir>]
What it does: n_ctx 256, n_seq_max 2, ubatch 64. Seq 0 is text 0..9, an image block at t=10 (3 rows x 4 columns, embedding rows, positions [t, t+row, t+col, 0]), then text 14..19. Seq 1 is text 0..5, an image at t=6 (2x2), then text 8..11. It records pos/y/x/tok of every cell of the attention cache and the indexer cache, and qsa_scalar_visibility_cells() on the indexer cells for a text query of seq 0, seq 1 and both. Then it saves llama_state_seq_get_data (seq 0 and seq 1) and llama_state_get_data (full) and restores:
- a1: the seq 0 blob into a fresh context, dest seq 0
- a2: the seq 0 blob into a fresh context, dest seq 1
- b: the full blob (seq_id -1 path) into a fresh context
- c: seq 0 restored into a fresh context that already holds seq 1 (partial restore; with unified KV this is an image sequence next to another sequence)
Checks per restored sequence: attention (pos,y,x) equals pre-save; indexer (pos,y,x) equals pre-save; indexer equals attention cell by cell; with PLE on, indexer tok equals pre-save; scalar visibility equals a never-saved context with the same content; one more text token per sequence and logits byte-equal to the never-saved context. Each side also restores the blobs that the other side wrote, and the blobs are compared byte by byte. Matrix: CPU and Vulkan0 (Vulkan build), CPU and ROCm0 (ROCm build), ROCm0 again with HIP_LAUNCH_BLOCKING=1; PLE on/off x unified on/off, plus MTP context (PLE off) x unified on/off.
Unit tests:
ctest --test-dir <build> --output-on-failure -L main -E 'test-opt|test-llama-archs'
<build>/bin/test-llama-archs -b <dev> -a qwen4exp
<build>/bin/test-llama-archs --mtp-cache-only -s 1234
<build>/bin/test-qsa-prefix; test-qsa-recover; test-qsa-fast
<build>/bin/test-llama-context -m <qwen2.5-1.5b> -ngl 99 -dev <dev>
<build>/bin/test-llama-context -m <granite-4.0-h-1b> -ngl 99 -dev <dev>
Model parity, per corpus <t> in prose, code, structured, numeric:
llama-debug -m <model> -f correctness-<t>.txt -c 16384 -b 16384 -ub 512 -ngl 99 -fa on -ctk f16 -ctv f16 -dev <dev> --save-logits --logits-output-dir <dir>/<side>-<t>
cmp <dir>/base-<t>/*.bin <dir>/head-<t>/*.bin
llama-completion -m <model> -f correctness-prose.txt -n 256 --temp 0 --seed 1 -no-cnv --ignore-eos -ngl 99 -fa on -ctk f16 -ctv f16 -dev <dev> -c 16384 # base, base again, head
llama-perplexity -m <model> -f <four corpora joined> -c <ctx> -b 512 -ub 512 -ngl 99 -fa on -ctk f16 -ctv f16 -dev <dev> --kl-divergence-base <side>.kld
Prompt cache reuse with two slots: llama-server -m <model> -np 2 -c 16384 --cache-ram <N> -fa on -ngl 99 -dev <dev>. Two different prompts (6000 bytes of the prose and code corpora) are sent at the same time, then two short prompts pinned to slots 0 and 1 move them into the RAM prompt cache, then the two prompts again (restored from the RAM cache, 1-4 new prompt tokens), and a third round. temp 0, 64 tokens.
Performance sanity: llama-bench -m <qwen2.5-1.5b> -p 512 -n 128 -r 3 -fa 1 -ngl 99, base and head alternated, 2 rounds.
Results
Restore test, failed checks (the same pattern on CPU, Vulkan0, ROCm0, and ROCm0 with HIP_LAUNCH_BLOCKING=1):
| Config | master | PR | PR loads master blobs | master loads PR blobs |
|---|---|---|---|---|
| PLE on, unified | 0 | 0 | 0 | 0 |
| PLE on, split | 0 | 0 | 0 | 0 |
| PLE off, unified | 14 | 0 | 0 | 14 |
| PLE off, unified, MTP | 16 | 0 | 0 | 16 |
| PLE off, split | 10 | 0 | 0 | 10 |
| PLE off, split, MTP | 15 (14 on Vulkan) | 0 | 0 | same |
| state blobs seq 0 / seq 1 / full, master vs PR | identical in all 30 configs |
Master failures, PLE off, unified, CPU (the other configs fail the same way):
FAIL a1 seq0: indexer cells (pos,y,x) == pre-save (n=28, 2d=0, pre 2d=11)
FAIL a1 seq0: indexer == attention cell by cell (idx,pos,y,x)
FAIL a1: QSA scalar visibility == never-saved context (111 vs 110)
FAIL b: QSA scalar visibility == never-saved context (111 vs 000)
FAIL c seq0: indexer cells (pos,y,x) == pre-save (n=28, 2d=0, pre 2d=11)
FAIL c: QSA scalar visibility == never-saved context (100 vs 000)
On master the restored indexer cells have x=y=0 for every cell, and the attention cells keep their x/y. On master the continuation logits of the target context are still byte-equal at this size (top_k covers every cell). The MTP context differs by up to 7e-10. With the PR, every case is byte-equal. Neither side printed an assert or the #261 warning.
Unit tests:
| Test | vk base | vk head | hip base | hip head | hip base HLB=1 | hip head HLB=1 |
|---|---|---|---|---|---|---|
| ctest -L main (65) | 63/65 | 63/65 | 64/65 | 64/65 | 64/65 | 64/65 |
| test-llama-archs -a qwen4exp | pass | pass | pass | pass | pass | pass |
| test-llama-archs --mtp-cache-only | pass | pass | pass | pass | pass | pass |
| test-qsa-prefix / recover / fast | pass | pass | pass | pass | pass | pass |
| test-llama-context qwen2.5-1.5b | 12 pass, 3 skip | same | same | same | same | same |
| test-llama-context granite-4.0-h-1b | 13 pass, 2 skip | same | same | same | same | same |
Both sides fail the same ctest cases: test-tokenizers-ggml-vocabs (vocab files are not in the tree), and on Vulkan the test-llama-context ctest entry (GGML_SCHED_DEBUG_REALLOC=1 aborts with an unexpected graph reallocation). Both failures are on master too.
Model parity:
| Model / backend | f32 final logits (4 corpora) | prompt tokens (4 corpora) | greedy 256, base A/A | greedy 256, base vs head | KLD files |
|---|---|---|---|---|---|
| qwen4exp target, Vulkan0 | identical x4 | identical x4 | identical | identical | identical (-c 1024, 16 chunks) |
| qwen4exp target, ROCm0 | identical x4 | identical x4 | identical | identical | identical (-c 1024, 16 chunks) |
| qwen2.5-1.5b, Vulkan0 | identical x4 | identical x4 | identical | identical | identical (-c 16384, four corpora joined) |
| qwen2.5-1.5b, ROCm0 | identical x4 | identical x4 | identical | identical | identical (-c 16384, four corpora joined) |
Prompt sizes on the qwen4exp target: 12386 (prose), 11089 (code), 8682 (structured), 12952 (numeric) tokens.
Prompt cache reuse, two slots:
| Model / backend | base vs head |
|---|---|
| qwen2.5-1.5b, Vulkan0 | identical |
| qwen2.5-1.5b, ROCm0 | identical |
| qwen4exp target, ROCm0 | identical |
| qwen4exp target, Vulkan0, concurrent requests (base, base, head, head) | all identical |
| qwen4exp target, Vulkan0, sequential requests (base, base, head) | all identical |
In one first Vulkan run on the qwen4exp target, the outputs already differed in round 1 on a fresh server, before any restore. In that run, the order in which the two prompts entered the batch was different. The reruns above are identical. This path restores the hybrid-idx state of the real model, but with text cells only.
Performance sanity (t/s, stddev in parentheses):
| Backend | Side | Round | pp512 | tg128 |
|---|---|---|---|---|
| Vulkan0 | base | 1 | 6762.74 (174.0) | 194.62 (0.04) |
| Vulkan0 | head | 1 | 6780.47 (34.92) | 193.54 (1.27) |
| Vulkan0 | base | 2 | 6649.00 (43.05) | 191.67 (1.29) |
| Vulkan0 | head | 2 | 6761.90 (146.36) | 191.57 (0.62) |
| ROCm0 | base | 1 | 6245.24 (548.69) | 155.64 (0.37) |
| ROCm0 | head | 1 | 6226.30 (574.73) | 155.46 (0.68) |
| ROCm0 | base | 2 | 6233.08 (574.77) | 155.67 (0.42) |
| ROCm0 | head | 2 | 6244.98 (547.78) | 155.53 (0.44) |
Correctness
| Check | Method | Result |
|---|---|---|
| Restore keeps indexer x/y (seq, dest seq, full, partial; PLE on/off; unified/split; target/MTP) | standalone restore test, CPU, Vulkan0, ROCm0 (HLB unset and =1) | PASS: master fails with PLE off, PR passes everything |
| State format unchanged | blobs byte-compared, cross loading | PASS: identical, both directions load |
| test-llama-context | qwen2.5-1.5b (dense), granite-4.0-h-1b (hybrid), both backends | PASS: same as master |
| test-llama-archs qwen4exp, MTP cache-only, test-qsa-* | both backends, HLB unset and =1 | PASS |
| f32 final logit parity, 4 corpora | llama-debug + cmp, qwen4exp target and dense model, both backends | PASS: byte-identical |
| KLD/PPL long | llama-perplexity, four corpora joined | dense model: identical .kld files at -c 16384; qwen4exp target: identical .kld files at -c 1024 (16 chunks), Mean KLD 0.000000, same top p 100 %; -c 16384 needs more memory than we have next to the 85 GiB model |
| Multi-step decode reusing context, several sequences | llama-server -np 2 with prompt cache restore, base A/A and base vs head | PASS |
| llama-bench depths up to 64000 | not run | restore-only host code; pp512/tg128 sanity check within noise |
| test-backend-ops full suite | not run | no op, kernel or graph change |
| #261 sequence with MTP draft and mmproj on the real model | not run | needs more memory than we can give it next to the 85 GiB target model |
Findings in full
- Should fix: no regression test for
llama_memory_hybrid_idx::state_read. The restore test above fails 10 to 16 checks on master and none on this PR. A trimmed version (PLE off, one image block, seq restore into a fresh context, indexer x/y equal to attention x/y) is enough. - Should fix (merge order): draft #276 edits
llama_memory_hybrid_idx::state_readaround the samestate_read_sinfo()call and the 2D check insrc/prefix.h. The conflict is textual. Keepext_2d_copy()directly after the indexer read. - The fix also repairs things the description does not mention: the ranked sort in
set_input_qsa_scan()for a single restored image sequence, andqsa_rebuild_prefix()after a restore. Both read the indexer x/y. - Nit:
GGML_ASSERT(src.n_stream == n_stream)sits in a path that otherwise throws and drops the partial state. Both caches have the same stream count by construction, so it cannot fire today. - Nit: the commit title has 103 characters.
- Upstream has the same restore path without the copy. Keep the hunk when you sync, and drop it only if upstream fixes the gap in the same place.
Claims
| Claim | Status | Evidence |
|---|---|---|
| After a restore, indexer cells get the attention cache's image x/y, index for index | reproduced | restore test, all configs |
| Root cause of the #261 assert: with x=y=0 the scalar route is taken next to another sequence | reproduced at the gate | case c: scalar visibility is 1 on master, 0 with the PR and in a never-saved context |
| State format does not change | reproduced | blobs byte-identical, cross loading works |
| test-qsa-prefix, test-qsa-recover, test-qsa-fast pass | reproduced | both backends |
| No assert in the #261 prompt-cache sequence; answer matches -np 1 | not tested | needs the MTP draft and an mmproj on the real model |
| Image follow-up text identical to master + #261 | not tested | same reason |
| Draft context counts the same 2D cells as the target after a restore | reproduced at small scale | tiny MTP context: 11/11 and 3/3 image cells keep x/y with the PR, 0 on master |
| Whole-cache restore (seq_id -1), not covered by the author | tested | case b passes with the PR |
Not tested
- The full #261 reproduction (real model with MTP draft and mmproj, image chat,
-np 4 -kvu): too much memory next to the 85 GiB target model. - Draft state in slot files (
--slot-save-path). llama-benchPP2048 depth sweep 0 to 64000: restore-only host code, so we ran only a short sanity check.- Full
test-backend-opssuite: no op changed. - KLD at -c 16384 on the qwen4exp target: the logits buffer does not fit in memory next to the model. The -c 16384 f32 final-logit comparison and the greedy decode cover long context on that model.
The rewrite rebased onto master b620b0d. The master commits past 50c2c8c (#272, #280, #284) touch no HIP file, so the baseline should hold; this commit is the regeneration that checks it. Pinned image rocm/dev-ubuntu-26.04@sha256:4f5ed1bf..., git archive of c456e6e (the rebased head before this commit), the two build steps of hip-quality-check.yml in a clean build directory (scripts/qsa-validation/harness/w13/vgpr_in_image.sh of the evidence branch, unchanged): - -Werror -Wno-tautological-compare build: rc 0; 18 warnings, none fatal under the CI flags (the same 18 as on the previous base); - test_vgpr_check.py: 21 tests OK; - EXPORT_METRICS On build: rc 0, 167 *.lto.s. Checker against the committed baseline: PASS, 6824 kernels across 162 TUs, 0 VGPR-spilling symbols, 11 SGPR-spilling symbols, all 11 bounded by baseline entries (3 sgpr_lane_spill, 8 sgpr_lane_spill_slower). Regeneration with scripts/hip/README.md's python, verbatim: minimum_kernel_count 6824 -> 6824, TUs 162 -> 162, copies 7164 -> 7164, no TU count changed. Only source_revision moves, 6805faa -> c456e6e (and three TU keys move in the file's key order, values unchanged). Checker against the regenerated baseline: PASS. The compiler string is the image's (AMD clang 24.0.0git d6f6cb691863). The regeneration python and the checker ran on the host, reading the image's assembly, as in W13. Assisted-by: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
REBASE3.md: rebase onto b620b0d (#272 conflict, its regression test) and verification. PROOF-final3.md: remaining coverage gates (M1, M2, M5, M6, AT-O at ub512/1024, Q1-C, Q3, Q4, Q8, Q11, P1, P4, Vulkan decode). REBASE4.md: rebase onto 1dd4c92 (#271 deleted with the maskless path, #225/#249/#254 kept), the M5 multi-slot reserve fix and its verification. Assisted-by: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LzX5gGXu1HutDf5C55PuKJ
Follow-up to #261, as agreed there. After a state restore, the qwen4exp indexer cache now takes the image 2D position of its cells from the attention cache. This is the root cause of the MTP draft assert that #261 guards against.
rope_typeNONE), sohas_cell_ext()is false for it unless PLE is on. Its saved state has no x/y, and a restore leaves image cells at 0,0. The shared MTP head has no PLE keys, so after a prompt-cache restore the draft context saw no 2D cells.qsa_scalar_visibility_cells()then allowed the scalar route with several sequences in the cache, and unranked image cells collided inset_input_qsa_scan().llama_kv_cache::ext_2d_copy()copies x/y from it index for index after the mirrored restore. The state format does not change.Strix Halo (gfx1151, RADV, Mesa 26.2.4), Qwen3.8-Flash-Next UD-IQ3_XXS with the shared MTP Q4_K_M draft and mmproj, the server line from #261 (
-np 4 -kvu --cache-ram 2048 -c 131072), on this branch alone and with #262 merged on top:-np 1Before this change, the draft context's guard counted 0 cells with a 2D position after the restore, against 195 in the target, and took the scalar route. With it, both count 195 and take the masked route (checked with temporary logging, not part of this PR). test-qsa-prefix, test-qsa-recover and test-qsa-fast pass. Not covered: the whole-cache restore (
seq_id == -1), which the copy handles but no test here runs, and draft state in slot files (#171), which rcfa offered to run on gfx1150. #262 should land first.Written with Claude, tested by me.
Assisted-by: Claude Opus 5.5