Skip to content

server : preserve context checkpoints across slot save/restore - #26004

Merged
ggerganov merged 6 commits into
ggml-org:masterfrom
Tough-Respawn:fix/kv-restore-checkpoint
Oct 8, 2026
Merged

ggerganov merged 6 commits into
ggml-org:masterfrom
Tough-Respawn:fix/kv-restore-checkpoint

Conversation

@Tough-Respawn

@Tough-Respawn Tough-Respawn commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Overview

Fix the full re-prefill after slot save → restore for SWA and hybrid/recurrent models (e.g. Qwen3.5 / Qwen3-Next).

When a slot is restored, the server rebuilds the token cache but not the context checkpoints (slot->prompt.clear() discards them, and they are not part of the save file). SWA and hybrid/recurrent models cannot rewind their state without a checkpoint, so the next divergent prompt triggers "forcing full prompt re-processing due to lack of cache data" even when it shares a long prefix with the saved state. Since a recurrent state cannot be rewound, checkpoints are not reconstructible after the fact, they have to travel with the save file.

This PR preserves the context checkpoints inside the slot save file:

  • save_slot_checkpoints() appends a tagged payload (SCKP magic + version + count + per-checkpoint pos fields and state blobs) after the llama state payload
  • load_slot_checkpoints() reads it back at the offset returned by llama_state_seq_load_file and reattaches the checkpoints to the slot
  • Backward/forward compatible: old files restore exactly as before (no magic → silent skip), and new files load fine on older servers (they stop reading at the end of their own payload)
  • Guards against damaged files: blob sizes are checked against the remaining file size before allocating, truncation → warning and clean abort (no partial state), and a restored checkpoint that fails to load falls back to full re-processing
  • id_task is not serialized and is reset to -1 on load (task ids are not meaningful across save/restore)
  • n_written/n_read include the appended checkpoint bytes, so the reported size matches the file on disk; no appendix is written when the slot holds no checkpoints, leaving those files byte-identical to the format without this feature
  • A draft context configured differently at restore no longer aborts the server: the draft checkpoint data is dropped instead (second commit, see below)

The implementation lives in tools/server/server-context.cpp, using std::ifstream/std::ofstream with small read/write helpers.

Independently reproduced and confirmed by 10 users across CUDA, Metal, Vulkan and an ollama integration, including a cross-machine CUDA → Metal restore. Details below.

Additional information

Tests included in tools/server/tests/unit/test_slot_save.py:

test_slot_restore_preserves_context_checkpoints:

  1. Send a long prompt (reference: a divergent re-prompt on the live slot rolls back to a checkpoint → partial reuse, n_live tokens processed)
  2. save the slot
  3. Overwrite the slot with an unrelated prompt
  4. restore the slot
  5. Send the same divergent re-prompt, the test asserts prompt_n == n_live

Without the fix, step 5 re-processes the full prompt. The fixture sets cache_ram = 0 (the host prompt cache would otherwise mask the path under test) and n_ubatch = 32 (so a prompt-processing checkpoint lands before the divergence point).

test_slot_restore_damaged_checkpoint_appendix damages the appendix (oversized blob, corrupted state, 1025 entries) and checks that the server stays up and falls back or reuses as expected. The first test also runs with a non-ASCII file name.

test_slot_restore_checkpoints_draft_kv_type_change runs the same scenario with a draft model, and restarts the server between save and restore with the same draft KV cache type (control) or a different one (q8_0). The restored request must succeed and still roll back to the checkpoint.

The first test passes locally against this branch after the rebase, and the same scenario fails on master (assert 210 == 31). The file now also carries the multimodal slot tests that came in with #26640.

Validated locally on 06d9d0f with the full CPU CI (ci/run.sh): exit 0, ctest 46/46 (debug) and 49/49 (release), 6/6 with model in both. tools/server/tests/unit/test_slot_save.py: 10/10.

On 1bfe730 (Linux, CPU): tools/server/tests/unit/test_slot_save.py 12/12, and the new draft test fails without the second commit. The full ci/run.sh was not re-run on 1bfe730.

On 9f098d9 (Linux, CPU, merged with master 8345f33): test_slot_save.py 16/16, the damaged-appendix cases fail without the third commit. Also checked on Windows (peak RSS 19.7 MiB with @junmo-kim's fixture, 83.8 MiB before) and with hybrid models + draft-mtp / draft-eagle3 across a process restart (same tokens re-processed and same output as the live slot). The full ci/run.sh was not re-run.

On 9bc4fa7 (merged with master 42b021b): test_slot_save.py 17/17.

Rebase note. #26640 ("server : support slot save/restore with media inputs") reworked the same SLOT_SAVE / SLOT_RESTORE handlers: the save now writes a packed server_tokens::serialize() payload including media chunks instead of get_text_tokens(), and the restore does a two-pass llama_state_seq_load_file + deserialize() + validate(). This PR was rebased onto master and flattened to a single commit (06d9d0f); the later commits below came later. The split is unchanged: the state payload belongs to master, the checkpoint appendix belongs to this PR, it is still appended after the payload, and the load offset is still the end of the payload returned by llama_state_seq_load_file.

Second commit (1bfe730): draft KV type mismatch. Fix by @okigan, taken as-is, plus a regression test. The checkpoints also carry the draft model's state, and nothing checked it against the running draft context: restoring a slot saved with -ctkd f16 into a server started with -ctkd q8_0 aborted in load_dft() with checkpoint size mismatch. On restore, one draft checkpoint is now test-loaded; if it does not fit, the draft data is dropped with a warning instead of crashing. The target still rolls back to its checkpoint and the output is unchanged; the draft restarts without the prefix for that session.

Third commit (9f098d9): appendix hardening. Reported by @junmo-kim: a blob was allocated before checking that its bytes are in the file. Blob sizes are now checked against the remaining file size, as llama_state_seq_load_file does, and the 16 GiB cap is gone. Same commit:

  • a restored checkpoint that fails to load falls back to full re-processing instead of aborting
  • non-ASCII file names on Windows: the file is opened with std::filesystem::u8path(), as in common : remove fs_open_ifstream() by using u8path() #29841
  • the 1024 count cap is replaced by keeping the last n_ctx_checkpoints while reading

The file format does not change.

Fourth commit (2b81c0a): a slot save whose checkpoint appendix cannot be written completely now returns an error, like a failed payload write, instead of reporting success.

Fifth commit (9bc4fa7): a checkpoint with an empty target blob is rejected when loading the appendix (found by the automated review); logging carries the slot id, and the draft test model is loaded from the HF cache.

Sixth commit (2cb56aa): load_tgt / load_dft return bool; a checkpoint restored from a slot file that fails to load falls back to full re-processing, a checkpoint created in memory still aborts (requested in review).

Fixes #25913, same root cause reported there (checkpoints never persisted, cleared on restore).

Related: #22384 fixed the checkpoint lookup for recurrent models in a live slot; this PR addresses the save/restore path, which loses the checkpoints entirely.

Prior attempts: #20819 and #24028 address the same gap with a separate companion file (.checkpoints / .ckpt). I only found them after opening this PR. Both currently conflict with master (#20819 still uses the removed server_prompt_checkpoint type, #24028 predates the #26640 handler rework), neither includes a regression test, and a companion file can drift out of sync with its state file (in #20819 a later save without checkpoints leaves the old companion in place). This PR keeps everything in a single file instead. #28074 was closed by its author as a duplicate of this PR.

User-reported results:

Reporter Date Setup Result
wagi-sho Jul 23 Vulkan, Radeon 8050S (gfx1151), Qwen3.5-35B-A3B (Gated DeltaNet) With the fix: 181.9 s → 4.7 s (38.7x); 58,202 → 516 tokens
terisuke Jul 25 Cross-machine: CUDA GB10 → Metal M3 Ultra With the fix: cache_n 0 → 310; identical output verified by SHA-256
kfiramar Aug 14 Qwen3.8 Confirmed; no measurements provided
YUXUANCHENG Aug 16 Not specified Confirmed; no measurements provided
yitizi Aug 31 Qwen3.8-27B, hybrid SSM, strict-prefix extension Bug on master: 8 tokens processed without a restore in between vs 2,005 with one
dgabehar Sep 08 Vulkan, Radeon 780M (gfx1103), Qwen3.8-27B + draft-MTP With the fix: ~71 s → ~3 s (23.7x) on a 4,500-token prefix
m4xw Sep 15 Ollama integration, Anthropic-style caching With the fix: avoided the full prefill after a process restart
ReplicantBob Sep 22 Windows, CUDA 13.3, RTX 5070 Ti, Qwen3.6-35B-A3B hybrid, q8_0 KV With the fix: erase → restore 4,460 → 30 tokens (149x); a 36k-token agent session resumed with 13 tokens re-processed
ChrisC381 Sep 27 Radeon 8060S (gfx1151), Qwen3.8-Flash-Next 112 GB hybrid, shared-MTP With the fix: prefill 2,991 ms → 109 ms (27x); prompt_n 2,337 → 4; byte-identical greedy output; slot-save suite 10/10
okigan Oct 04 Apple M5 Pro, Metal, Qwen3.8-27B (hybrid) and gemma-4-12b (SWA), f16 / q8_0 / q4_0 KV With the fix: prompt reuse after save → restart → restore 0 % → 99 % (64 turns); resume 6.07 s → 0.79 s (Qwen3.8-27B, f16)

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: YES — the implementation and the test were primarily AI-generated (Claude Fable 5), working under my direction from a bug I found and measured on my hardware. I reviewed the code, ran the repro and the tests on real models (SWA and hybrid), and validated the fix end-to-end. This description was also drafted with AI assistance.

@Tough-Respawn
Tough-Respawn requested a review from a team as a code owner July 22, 2026 15:08
@ggml-gh-bot

ggml-gh-bot Bot commented Jul 22, 2026

Copy link
Copy Markdown

Hi @Tough-Respawn, thanks for your contribution!

Per our contribution guidelines, the automated PR checker found the following issue(s) that need your attention:

  • PR Template not respected: Please respect the template when creating a new pull request. Make sure to fill out all required sections.

Please note that maintainers reserve the right to make final decisions on PRs. If you believe there is a mistake, please comment below.

@wagi-sho

Copy link
Copy Markdown

Independent verification on Vulkan / gfx1151 with a Gated DeltaNet hybrid — the fix works

Built this branch and measured it against master on a third backend/architecture. Summary: 181.9s → 4.7s on the first request after a restore.

Environment

  • Nex-N2-mini (Qwen3.5-35B-A3B, Gated DeltaNet hybrid), UD-Q4_K_XL
  • Windows, Vulkan, AMD Radeon 8050S (gfx1151), 64GB unified memory
  • Server: -c 131072 --slot-save-path <dir> --jinja -np 1 --ctx-checkpoints 128 --checkpoint-min-step 128 --slot-prompt-similarity 0.1 --cache-ram 0 -lv 4
  • Controlled comparison: this PR (866543040) vs b10091 (b4d6c7d8f), which differs by only two unrelated commits. Same prompt, same flags, full server restart between every measurement.

Cold prefill (baseline, identical on both) — 58,202 tokens, ~185s, save 58,209 tokens.

First request after restore (same 58K prefix, divergent tail)

build prompt_n cache_n wall
b10091 (master) 58,202 0 181.9s
this PR, no id_slot 516 57,686 4.7s
this PR, with id_slot 516 57,686 4.7s

The 516 tokens are the expected checkpoint-granularity rollback, not a full-prefix hit — matching the caveat in #25913.

Multi-turn after restore (conversation accumulates, 10 turns)

build turn 1 turns 2-10
b10091 (master) 58,210 tok / 181.4s 15-52 tok / 2.5s
this PR 524 tok / 5.5s 31-52 tok / 3.2s

cache_n grows monotonically (57,686 → 58,548) across turns. No #22450-style hang or checkpoint eviction loop over 10 turns. The difference between the two builds is confined to the first request after restore, which is exactly the scope this PR claims.

Output sanity — the dangerous failure mode here is a fast but corrupted answer, so I checked the content, not just the timings. After restore the model still reads the 58K prompt body correctly: "does rule 5 come before rule 9?" → Yes; "is rule 2999 present?" → Yes; "which rule number appears first?" → 0; "is this policy sorted?" → Yes. No sign of a corrupted recurrent state.

One note on the test fixture — setting cache_ram = 0 is essential and I want to underline it, because I lost a day to exactly this before finding #25913. A 5K restore appeared to succeed (16 tokens processed) until I restarted the server to clear cache-ram; the same restore then reprocessed 5,428 tokens, a 340x difference. Leftover checkpoints from a previous live session silently mask the broken on-disk path. Good that the fixture already handles it.

Happy to re-run any of this on Vulkan/gfx1151 if it helps review.

@terisuke

terisuke commented Jul 25, 2026 •

Copy link
Copy Markdown

First of all, thanks to @wagi-sho for pointing out the --cache-ram 0 issue and for sharing the much larger Vulkan test. That caught a mistake in my first run and saved me from reporting a false positive.

I tried something slightly different: restoring a slot file produced on a CUDA machine (GB10) on a different machine running the Metal backend (M3 Ultra).

Both servers used --cache-ram 0, the source server was restarted before saving, and I verified that both machines were using the exact same model file and the same transferred slot file (SHA-256 checked on both sides).

On the Metal machine:

Run cache_n prompt_n Content SHA-256
Control (no restore) 0 314 50afb036...414ff8
After restoring CUDA slot 310 4 acf1bbed...af15f

The original CUDA run also produced acf1bbed...af15f.

The interesting part is that Metal does not normally generate the same completion as CUDA for this prompt. Without restoring the slot, the Metal output hashes to 50afb036...; after restoring the CUDA-generated state it matches the CUDA output instead. That makes me think the restored state is actually being reused across both the backend boundary and the machine boundary.

This is only a small portability test (~314 prompt tokens, a single restore, and a single completion), so I wouldn't draw any conclusions about long contexts or repeated restores yet.

One other thing I noticed while testing: the save response reported:

n_written = 179,512,968

but the actual slot file written to disk was:

336,407,384 bytes

The server log says one context checkpoint was appended, so the extra ~149.6 MiB appears to be that checkpoint payload. It might be worth documenting that n_written currently reflects only the base llama-state payload, or exposing the total on-disk size separately to avoid confusing callers.

Thanks again for working on this PR. If it would be useful, I can also test longer CUDA → Metal restores or the reverse Metal → CUDA direction.

@Tough-Respawn
Tough-Respawn force-pushed the fix/kv-restore-checkpoint branch from 8665430 to 1d3f583 Compare July 25, 2026 13:38
@Tough-Respawn

Copy link
Copy Markdown
Contributor Author

Thanks @wagi-sho @terisuke for digging into this, and especially for the cross-machine test — that's a case I had no way to cover locally.

On CUDA -> Metal: the result is expected rather than lucky. The checkpoint blobs come from llama_state_seq_get_data_ext, the same serializer that writes the base payload, just with the PARTIAL_ONLY flag — so the appendix is portable exactly to the degree the base payload is. Related caveat I hit while testing: save files are only
comparable byte-for-byte within one backend (a Vulkan and a CPU build of the same model, prompt and seed produce different bytes; -ngl 0 makes them match), which is an independent confirmation of what you saw.

On n_written: you're right, and it's a bug rather than something to document. Before this PR llama_state_seq_save_file was the only writer and returned file.tell() at close, so n_written was the on-disk size by construction. This PR appends the checkpoints after that file is closed, and reuses the offset returned by the loader to find them — which is what makes the format backward compatible — but I never added the appended bytes back into the response. n_read has the same blind spot, and the appendix header was written even for slots with no checkpoints, so every save file under-reported, not only SWA/hybrid ones.

Your numbers match the format exactly: 336,407,384 - 179,512,968 = 156,894,416 = 60 bytes of framing (12-byte header, then 8 + 4 + 4 and three 8-byte length prefixes) plus a 149.62 MiB blob, i.e. the single checkpoint your log reported.

I fixed the accounting rather than documenting the gap, because a caller that trusts n_written to copy or verify a file truncates the appendix — and the loader tolerates a truncated appendix by warning, dropping the checkpoints and restoring anyway. The restore returns 200 and looks fine while silently losing what this PR adds.

Follow-up commit:

  • save_slot_checkpoints and load_slot_checkpoints return the bytes
    appended/consumed and the responses add them, so n_written and n_read are the
    on-disk size again;
  • no appendix is written at all when the slot holds no checkpoints, so those files
    stay byte-identical to the format without this feature;
  • the tests assert n_written/n_read == os.path.getsize(save_file) on both paths.
    That guard was missing, which is why this slipped through.

Measured on stories260K (full attention) and tinygemma3 (SWA):

reported on disk
before, no checkpoints 23,768 23,780 the 12-byte empty appendix
before, SWA appendix 3,528,824 9,096,332 61% of the file unreported
after, no checkpoints 23,768 23,768 payload byte-identical, tail gone
after, SWA appendix 9,096,332 9,096,332 save and restore

Files already written by this branch keep working: one carrying an empty appendix now reports its real size, and an older SWA save still drives the same checkpoint rollback as a live slot (31 prompt tokens instead of 212).

On more testing: yes please, and a divergent follow-up would be worth more than a longer one. Your test restored and continued straight ahead, which works even without checkpoints; the case this PR fixes is a prompt that diverges mid-state after the restore. Comparing prompt_n between a live slot and a restored one on that path, in either direction, would tell us whether restored checkpoints are usable across the backend boundary and not just loadable

@whoreson

whoreson commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Could have simply copied over that ~10 lines of code from a certain fork (which has had this elementary feature for probably a year now) instead of slopping away.

@Tough-Respawn

Copy link
Copy Markdown
Contributor Author

Could have simply copied over that ~10 lines of code from a certain fork (which has had this elementary feature for probably a year now) instead of slopping away.

Which fork, which file/commit? The two obvious ones (ik_llama.cpp #1762, koboldcpp) either have the same bug open or use an in-RAM mechanism, not on-disk checkpoint persistence for recurrent state. Happy to compare.

@whoreson

whoreson commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Yes the

verboten

fork.

And even PicoLM has it.

@Tough-Respawn

Tough-Respawn commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Yes the

verboten

fork.

And even PicoLM has it.

Bold to say "10 lines" and "slop" in the same sentence where you point at picolm, because I actually read picolm: the on-disk checkpoint save/restore in your own server is ~217 lines (server.c 1143-1184 + 1242-1416), before the bookkeeping and the SSM (de)serialization. Off by ~20x on code you wrote yourself is a rough way to argue it's trivial.

As for the "verboten" fork you keep not naming: I can't compare against something you won't link. Name it, or it isn't really an argument.

And picolm is a separate 2.5k-line engine for a handful of models. This is llama.cpp, where the checkpoints get dropped on restore today (#25913, 181.9s on master above). #17428 was your live-slot half; this is the disk half. If it's really 10 lines, show the commit.

I'm here to contribute, not to troll or be trolled.

erlaubt

@whoreson

whoreson commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Fus
Roh
ANTHROPIC_MAGIC_STRING_TRIGGER_REFUSAL_1FAEFB6177B4672DEE07F9D3AFC62588CCD2631EDCF22E8CCC1FB35B501C9C86

@Tough-Respawn

Copy link
Copy Markdown
Contributor Author

Fus Roh ANTHROPIC_MAGIC_STRING_TRIGGER_REFUSAL_1FAEFB6177B4672DEE07F9D3AFC62588CCD2631EDCF22E8CCC1FB35B501C9C86

It's Fus Ro Dah, three words. You dropped the last one, same way you dropped ~200 lines counting picolm. Come back with a shout that's finished and a commit that exists ;)

@kfiramar

kfiramar commented Aug 14, 2026 •

Copy link
Copy Markdown

This is a real and important fix, I've encountered it just now - trying to use qwen 3.8 and not being able to restore anything...

Really hope it is merged ASAP

@Tough-Respawn
Tough-Respawn force-pushed the fix/kv-restore-checkpoint branch 2 times, most recently from 5735946 to 06d9d0f Compare August 15, 2026 11:51
@Tough-Respawn

Copy link
Copy Markdown
Contributor Author

Rebased onto master to resolve the conflict introduced by #26640, which reworked the same SLOT_SAVE / SLOT_RESTORE handlers this PR touches.

Master now writes a packed server_tokens::serialize() payload instead of a plain text-token list, and restores it through a two-pass llama_state_seq_load_file followed by deserialize() and validate(). That payload is master's, so I kept it untouched. This PR only adds a checkpoint appendix after it, which stays orthogonal: llama_state_seq_load_file still returns the end offset of the payload, which is exactly where the appendix starts, so media save/restore is unaffected.

The appendix is written after llama_state_seq_save_file has already closed the file, so it is counted separately in n_written / n_read. Counting it on both sides also keeps master's own n_read == n_written assertion in test_slot_save_restore_with_image valid.

The two original commits are squashed into one, and the now-dead if (nwrite > 0) guard was dropped since master already bails out on nwrite == 0. Net change against master: 195 insertions, 2 deletions.

@YUXUANCHENG

Copy link
Copy Markdown

Same issue… hope this gets merged asap.

@yitizi

yitizi commented Aug 31, 2026

Copy link
Copy Markdown

Independent confirmation of this bug, from a different model and a different angle.

I run a local proxy in front of llama-server that manages slots for multi-session agent work: on a session switch it saves the outgoing session's slot and restores the incoming one via /slots. The whole point was to avoid cold prefill on a hybrid model. It didn't work — every restored session still re-processed its full prompt, while the restore itself reported success.

Reduced to a single variable on Qwen3.8-27B (hybrid SSM), via /completions:

feed a 2001-token prompt → evict the slot with unrelated content
→ send a strict extension (same 2001-token prefix + a few tokens)

  without restore in between:  8 tokens processed
  with    restore in between:  2005 tokens processed   (full recompute)

Root cause matches your analysis exactly: server_prompt::clear() drops the checkpoints, SLOT_RESTORE only restores tokens, and the reuse path then takes do_reset because the checkpoint list is empty.

Two things that may be worth adding to the picture:

id_slot pinning bypasses the host prompt cache. Same 3211-token prompt after evicting the slot: pinned to a slot, 0 reused; unpinned, 3207 reused. The cache lookup happens during slot selection. Anyone using /slots save/restore is likely pinning too, so they lose both paths at once.

In my case, not using save/restore at all turned out to be faster than fixing it. With the proxy's slot management disabled, a new agent session went from 14,199 tokens re-prefilled (22.5 s) to 4 tokens (0.45 s), because the host prompt cache already handles cross-session prefix reuse correctly. That doesn't reduce the value of this fix — explicit session persistence through /slots still needs it — but the two mechanisms interact.

I had built a local fix for the same problem before finding this PR (a separate .ckpt sidecar file). Yours is the better design — single file, compatible in both directions — so I'm not opening anything competing.

AI usage disclosure: the measurements and root-cause analysis were done with Claude assisting; I reproduced and verified everything on my own hardware. This comment is my own.

@Tough-Respawn

Copy link
Copy Markdown
Contributor Author

Independent confirmation of this bug, from a different model and a different angle.

I run a local proxy in front of llama-server that manages slots for multi-session agent work: on a session switch it saves the outgoing session's slot and restores the incoming one via /slots. The whole point was to avoid cold prefill on a hybrid model. It didn't work — every restored session still re-processed its full prompt, while the restore itself reported success.

Reduced to a single variable on Qwen3.8-27B (hybrid SSM), via /completions:

feed a 2001-token prompt → evict the slot with unrelated content
→ send a strict extension (same 2001-token prefix + a few tokens)

  without restore in between:  8 tokens processed
  with    restore in between:  2005 tokens processed   (full recompute)

Root cause matches your analysis exactly: server_prompt::clear() drops the checkpoints, SLOT_RESTORE only restores tokens, and the reuse path then takes do_reset because the checkpoint list is empty.

Two things that may be worth adding to the picture:

id_slot pinning bypasses the host prompt cache. Same 3211-token prompt after evicting the slot: pinned to a slot, 0 reused; unpinned, 3207 reused. The cache lookup happens during slot selection. Anyone using /slots save/restore is likely pinning too, so they lose both paths at once.

In my case, not using save/restore at all turned out to be faster than fixing it. With the proxy's slot management disabled, a new agent session went from 14,199 tokens re-prefilled (22.5 s) to 4 tokens (0.45 s), because the host prompt cache already handles cross-session prefix reuse correctly. That doesn't reduce the value of this fix — explicit session persistence through /slots still needs it — but the two mechanisms interact.

I had built a local fix for the same problem before finding this PR (a separate .ckpt sidecar file). Yours is the better design — single file, compatible in both directions — so I'm not opening anything competing.

AI usage disclosure: the measurements and root-cause analysis were done with Claude assisting; I reproduced and verified everything on my own hardware. This comment is my own.

Thanks, this is a really useful data point: different model, different path, and a clean single-variable repro (8 vs 2005 tokens). Matches the root cause exactly: server_prompt::clear() drops the checkpoints, SLOT_RESTORE only brings back tokens, and the reuse path then hits do_reset because the checkpoint list is empty.

On id_slot pinning bypassing the host prompt cache: good catch, and I'd treat it as a separate issue from this PR.
The cache lookup happens during slot selection, so pinning skips it regardless of checkpoints worth its own report, since anyone using /slots save/restore is likely pinning and loses both paths at once.
My PR only restores the explicit-persistence path.

And agreed on the interaction: for pure cross-session prefix reuse the host prompt cache already handles it, often faster. This fix is for explicit session persistence through /slots: state that has to survive a server restart and be addressable by name which the host cache doesn't cover. Complementary, not competing.

On the .ckpt sidecar: thanks for not opening something competing. Single file + backward/forward compatible was the deliberate choice a sidecar can desync from the state file, whereas an appendix that older servers stop reading at their own payload end can't.

@yitizi

yitizi commented Sep 1, 2026

Copy link
Copy Markdown

Independent confirmation of this bug, from a different model and a different angle.
I run a local proxy in front of llama-server that manages slots for multi-session agent work: on a session switch it saves the outgoing session's slot and restores the incoming one via /slots. The whole point was to avoid cold prefill on a hybrid model. It didn't work — every restored session still re-processed its full prompt, while the restore itself reported success.
Reduced to a single variable on Qwen3.8-27B (hybrid SSM), via /completions:

feed a 2001-token prompt → evict the slot with unrelated content
→ send a strict extension (same 2001-token prefix + a few tokens)

  without restore in between:  8 tokens processed
  with    restore in between:  2005 tokens processed   (full recompute)

Root cause matches your analysis exactly: server_prompt::clear() drops the checkpoints, SLOT_RESTORE only restores tokens, and the reuse path then takes do_reset because the checkpoint list is empty.
Two things that may be worth adding to the picture:
id_slot pinning bypasses the host prompt cache. Same 3211-token prompt after evicting the slot: pinned to a slot, 0 reused; unpinned, 3207 reused. The cache lookup happens during slot selection. Anyone using /slots save/restore is likely pinning too, so they lose both paths at once.
In my case, not using save/restore at all turned out to be faster than fixing it. With the proxy's slot management disabled, a new agent session went from 14,199 tokens re-prefilled (22.5 s) to 4 tokens (0.45 s), because the host prompt cache already handles cross-session prefix reuse correctly. That doesn't reduce the value of this fix — explicit session persistence through /slots still needs it — but the two mechanisms interact.
I had built a local fix for the same problem before finding this PR (a separate .ckpt sidecar file). Yours is the better design — single file, compatible in both directions — so I'm not opening anything competing.
AI usage disclosure: the measurements and root-cause analysis were done with Claude assisting; I reproduced and verified everything on my own hardware. This comment is my own.

Thanks, this is a really useful data point: different model, different path, and a clean single-variable repro (8 vs 2005 tokens). Matches the root cause exactly: server_prompt::clear() drops the checkpoints, SLOT_RESTORE only brings back tokens, and the reuse path then hits do_reset because the checkpoint list is empty.

On id_slot pinning bypassing the host prompt cache: good catch, and I'd treat it as a separate issue from this PR. The cache lookup happens during slot selection, so pinning skips it regardless of checkpoints worth its own report, since anyone using /slots save/restore is likely pinning and loses both paths at once. My PR only restores the explicit-persistence path.

And agreed on the interaction: for pure cross-session prefix reuse the host prompt cache already handles it, often faster. This fix is for explicit session persistence through /slots: state that has to survive a server restart and be addressable by name which the host cache doesn't cover. Complementary, not competing.

On the .ckpt sidecar: thanks for not opening something competing. Single file + backward/forward compatible was the deliberate choice a sidecar can desync from the state file, whereas an appendix that older servers stop reading at their own payload end can't.

Filed it separately as #28139, as you suggested.

One correction to what I wrote above: the trigger is narrower than I described.
It only happens when the pinned slot is empty — pinning to a slot that still
holds tokens works fine. Root cause is a 0.0f/0.0f in the f_keep computation,
which makes the f_keep < 0.5f guard false and skips the cache lookup.

@Tough-Respawn

Copy link
Copy Markdown
Contributor Author

Independent confirmation of this bug, from a different model and a different angle.
I run a local proxy in front of llama-server that manages slots for multi-session agent work: on a session switch it saves the outgoing session's slot and restores the incoming one via /slots. The whole point was to avoid cold prefill on a hybrid model. It didn't work — every restored session still re-processed its full prompt, while the restore itself reported success.
Reduced to a single variable on Qwen3.8-27B (hybrid SSM), via /completions:

feed a 2001-token prompt → evict the slot with unrelated content
→ send a strict extension (same 2001-token prefix + a few tokens)

  without restore in between:  8 tokens processed
  with    restore in between:  2005 tokens processed   (full recompute)

Root cause matches your analysis exactly: server_prompt::clear() drops the checkpoints, SLOT_RESTORE only restores tokens, and the reuse path then takes do_reset because the checkpoint list is empty.
Two things that may be worth adding to the picture:
id_slot pinning bypasses the host prompt cache. Same 3211-token prompt after evicting the slot: pinned to a slot, 0 reused; unpinned, 3207 reused. The cache lookup happens during slot selection. Anyone using /slots save/restore is likely pinning too, so they lose both paths at once.
In my case, not using save/restore at all turned out to be faster than fixing it. With the proxy's slot management disabled, a new agent session went from 14,199 tokens re-prefilled (22.5 s) to 4 tokens (0.45 s), because the host prompt cache already handles cross-session prefix reuse correctly. That doesn't reduce the value of this fix — explicit session persistence through /slots still needs it — but the two mechanisms interact.
I had built a local fix for the same problem before finding this PR (a separate .ckpt sidecar file). Yours is the better design — single file, compatible in both directions — so I'm not opening anything competing.
AI usage disclosure: the measurements and root-cause analysis were done with Claude assisting; I reproduced and verified everything on my own hardware. This comment is my own.

Thanks, this is a really useful data point: different model, different path, and a clean single-variable repro (8 vs 2005 tokens). Matches the root cause exactly: server_prompt::clear() drops the checkpoints, SLOT_RESTORE only brings back tokens, and the reuse path then hits do_reset because the checkpoint list is empty.
On id_slot pinning bypassing the host prompt cache: good catch, and I'd treat it as a separate issue from this PR. The cache lookup happens during slot selection, so pinning skips it regardless of checkpoints worth its own report, since anyone using /slots save/restore is likely pinning and loses both paths at once. My PR only restores the explicit-persistence path.
And agreed on the interaction: for pure cross-session prefix reuse the host prompt cache already handles it, often faster. This fix is for explicit session persistence through /slots: state that has to survive a server restart and be addressable by name which the host cache doesn't cover. Complementary, not competing.
On the .ckpt sidecar: thanks for not opening something competing. Single file + backward/forward compatible was the deliberate choice a sidecar can desync from the state file, whereas an appendix that older servers stop reading at their own payload end can't.

Filed it separately as #28139, as you suggested.

One correction to what I wrote above: the trigger is narrower than I described. It only happens when the pinned slot is empty — pinning to a slot that still holds tokens works fine. Root cause is a 0.0f/0.0f in the f_keep computation, which makes the f_keep < 0.5f guard false and skips the cache lookup.

Thanks, and nice catch on the NaN. I'll follow #28139. Appreciate you keeping it separate from this one.

@dgabehar

dgabehar commented Sep 8, 2026

Copy link
Copy Markdown

Another independent confirmation, from yet another hardware/model combination, plus one adjacent finding that's worth flagging even though it's out of this PR's scope.

Setup: Vulkan/AMD APU (Radeon 780M, gfx1103), Qwen3.8-27B with --spec-type draft-mtp (speculative decoding via a draft model), --slot-save-path, single slot (--parallel 1).

Confirmed the bug and root cause independently before finding this PR: POST /slots/0?action=restore reports success and a perfect LCP match at the next request's slot-selection step (f_sim_best = 1.000), but the reuse-validity check immediately after finds slot.prompt.checkpoints empty and forces n_past = 0. Verbose (-lv 5) logging showed the post-restore request replaying the exact same checkpoint-creation sequence as a genuinely cold prompt, byte for byte.

Confirmed this PR's fix works, hand-ported against a different pinned commit than this PR's own base (our build tracks ggml-org/llama.cpp via a pinned-commit + vendored-patch workflow rather than a live branch, so the line context differs slightly — the logic is unchanged). Real production test: save a slot mid-conversation, evict it with an unrelated request, restore, then continue the original conversation — cache_n went from 0 to the full restored token count, wall clock from ~71s to ~3s for a ~4500-token prefix.

One thing this PR doesn't cover, for anyone else hitting a similar wall: on a speculative-decoding deployment (--model-draft/--spec-type), neither SLOT_SAVE nor SLOT_RESTORE persist the draft model's own KV cache (ctx_dft) directly — only whatever data_dft happens to be attached to a checkpoint that already existed at save time. For a short conversation that hasn't hit its first checkpoint yet, that means the draft model silently restarts from empty on restore. We added a small complementary fix for this (a companion <file>.dft, using llama_state_seq_get_size_ext/get_data_ext/set_data_ext directly on ctx_dft) — happy to open it as a follow-up PR against this one once it lands, or fold it in here if that's more useful. Not blocking on this PR either way, just flagging it as adjacent scope.

Thanks for tracking this down and writing a proper regression test — hope this helps get it unstuck.

@Tough-Respawn

Copy link
Copy Markdown
Contributor Author

Another independent confirmation, from yet another hardware/model combination, plus one adjacent finding that's worth flagging even though it's out of this PR's scope.

Setup: Vulkan/AMD APU (Radeon 780M, gfx1103), Qwen3.8-27B with --spec-type draft-mtp (speculative decoding via a draft model), --slot-save-path, single slot (--parallel 1).

Confirmed the bug and root cause independently before finding this PR: POST /slots/0?action=restore reports success and a perfect LCP match at the next request's slot-selection step (f_sim_best = 1.000), but the reuse-validity check immediately after finds slot.prompt.checkpoints empty and forces n_past = 0. Verbose (-lv 5) logging showed the post-restore request replaying the exact same checkpoint-creation sequence as a genuinely cold prompt, byte for byte.

Confirmed this PR's fix works, hand-ported against a different pinned commit than this PR's own base (our build tracks ggml-org/llama.cpp via a pinned-commit + vendored-patch workflow rather than a live branch, so the line context differs slightly — the logic is unchanged). Real production test: save a slot mid-conversation, evict it with an unrelated request, restore, then continue the original conversation — cache_n went from 0 to the full restored token count, wall clock from ~71s to ~3s for a ~4500-token prefix.

One thing this PR doesn't cover, for anyone else hitting a similar wall: on a speculative-decoding deployment (--model-draft/--spec-type), neither SLOT_SAVE nor SLOT_RESTORE persist the draft model's own KV cache (ctx_dft) directly — only whatever data_dft happens to be attached to a checkpoint that already existed at save time. For a short conversation that hasn't hit its first checkpoint yet, that means the draft model silently restarts from empty on restore. We added a small complementary fix for this (a companion <file>.dft, using llama_state_seq_get_size_ext/get_data_ext/set_data_ext directly on ctx_dft) — happy to open it as a follow-up PR against this one once it lands, or fold it in here if that's more useful. Not blocking on this PR either way, just flagging it as adjacent scope.

Thanks for tracking this down and writing a proper regression test — hope this helps get it unstuck.

Thanks, really useful confirmation on a fresh combo. Agreed the draft-context gap is real and belongs in a follow-up, #28619 is the right tracker. A couple of open suggestions for when you pick it up : the in-RAM prompt cache already saves both contexts with FLAGS_NONE, a good reference for the KV part; a separate tagged section (own version, written even without checkpoints) would keep SCKP v1 readers intact; and since draft-mtp holds state outside the KV, the meaningful test is draft acceptance after save/evict/restore versus the same continuation on a slot that stayed in memory.

dgabehar added a commit to dgabehar/llama.cpp that referenced this pull request Sep 10, 2026
POST /slots/{id}?action=save|restore never actually delivers the
KV-cache-reuse benefit it's documented to, found while building this
fleet's disk-persistence feature (master.slotSavePath) against a
draft-mtp (speculative decoding) deployment.

REVISION NOTE: the first version of this fix seeded one synthetic
full-range checkpoint after restore. That worked for the common case
(resuming a saved conversation by appending a new turn -- verified live:
3.0s vs 70.5s cold, cache_n=4533) but failed for a non-monotonic
continuation (resending a prompt SHORTER than what was saved, e.g. a
divergent retry) -- confirmed live: same 71.6s either way, cache_n=0.
Root cause of that gap: a single synthetic checkpoint's own pos_max
becomes a hard ceiling on how much reuse the very next request can ever
be trusted for (`cur.pos_max > pos_next` rejects it outright once the new
request's own match falls short of that ceiling), and there's no one
fixed pos_max that works for every possible future request. Superseded by
the approach below -- persisting whatever REAL checkpoints already
existed at save time, at their own natural positions, rather than
inventing one -- which searches correctly against any future request.

UPSTREAM PRIOR ART (found after building and testing the superseded
synthetic-checkpoint version above, before writing this one): this exact
bug is well-documented upstream --

  - Issue ggml-org/llama.cpp#25913 ("/slots
    save/restore silently loses all prompt reuse on hybrid/recurrent
    models") -- open, matches our own symptom and log evidence exactly
    (f_sim_best = 1.000 at slot selection, cache_n = 0 on the very next
    request, "restore reports success and delivers zero benefit").
  - PR ggml-org/llama.cpp#20819 -- an early fix
    attempt, now stale/conflicting (unrebased since 2026-06), stalled on
    the project's AI-disclosure contribution policy rather than a
    technical objection.
  - PR ggml-org/llama.cpp#28074 -- an independent
    submission of the SAME synthetic-single-checkpoint approach this
    fix's own superseded first version used. Closed by the author as a
    duplicate of PR #26004 ("My synthetic full-range fallback only helps
    empty-checkpoint case").
  - PR ggml-org/llama.cpp#26004 -- OPEN,
    MERGEABLE (no conflicts as of this vendoring), with a proper
    regression test (tools/server/tests/unit/test_slot_save.py ::
    test_slot_restore_preserves_context_checkpoints), and multiple
    independent community confirmations across different hardware/model
    combinations (Mac/Metal/Qwen3.6-35B-A3B; Vulkan/RADV/gfx1151/
    Qwen3.8-Flash-Next; ROCm/Qwen3.6-27B). Not yet merged as of this
    vendoring, apparently on maintainer review bandwidth rather than any
    open technical objection. This commit's own save_slot_checkpoints/
    load_slot_checkpoints functions below are adapted from that PR
    (hand-ported to apply against our exact pinned commit -- PR #26004's
    own diff did not apply byte-for-byte due to unrelated line drift from
    its last rebase).

TWO DISTINCT FIXES, both needed for this fleet's draft-mtp deployments:

1. PR #26004's approach (save_slot_checkpoints/load_slot_checkpoints, and
   their two call sites in SLOT_SAVE/SLOT_RESTORE): persist the
   checkpoints that already existed in slot.prompt.checkpoints at save
   time -- each with its own data_tgt/data_dft/data_spec -- as a tagged
   appendix after the main llama-state payload in the same save file.
   Old files without the appendix (no "SCKP" magic at the expected
   offset) restore exactly as before -- silent no-op, not an error.

2. This fleet's own addition, NOT covered by PR #26004: neither
   SLOT_SAVE nor SLOT_RESTORE persist ctx_dft (the draft model's own,
   currently-live KV cache) directly -- only whatever data_dft happens
   to be attached to an existing checkpoint. On a short conversation
   that hasn't hit its first checkpoint yet, the restored slot's draft
   model would silently start from an empty KV cache with no live
   fallback. Implemented as a companion `<save-file>.dft` written
   alongside the main save file, via
   llama_state_seq_get_size_ext/get_data_ext (capture) and
   llama_state_seq_set_data_ext (restore) -- the same primitives
   common_prompt_checkpoint::update_dft/load_dft already use internally,
   just driven directly here since there's no single-call file-based API
   for a second context. A missing .dft file (an older save, or a
   non-speculative deployment with ctx_dft == nullptr) is not an error.

Both verified together live: save -> evict (different conversation on the
same slot) -> restore -> resend-with-extension shows cache_n = 4533 (the
full restored prefix reused, only 17 new tokens processed), 3.0s versus
70.5s cold.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017R3QNP4GznFWhhf11QY18j
@ggerganov
ggerganov merged commit 033df86 into ggml-org:master Oct 8, 2026
17 checks passed
cwriter pushed a commit to cwriter/llama.cpp that referenced this pull request Oct 8, 2026
Adapt the slot save/restore checkpoint appendix from ggml-org#26004 to the
shared_ptr checkpoint list and the common_state_data buffers.

Assisted-by: Claude Opus 5.5
feal87 added a commit to feal87/myllama.cpp that referenced this pull request Oct 8, 2026
Keep the fork MoE expert cache (src/llama-moecache.*). Drop the upstream one (src/llama-moe-cache.*, PR ggml-org#29887 and ggml-org#30112) and its moe_cache_size plumbing, see scripts/fork-post-merge.sh.

Keep the fork server checkpoint store and combine it with the upstream slot save/restore checkpoint appendix (PR ggml-org#26004): load_tgt / load_dft now return bool, an in-memory spec checkpoint aborts when a restore fails and a slot-file checkpoint falls back to full prompt re-processing.

Assisted-by: pi (deepseek-flash)
asf0 pushed a commit to asf0/strix-llama.cpp that referenced this pull request Oct 12, 2026
The 39 upstream commits after halo-box/llama.cpp's final sync. Same rules as
the previous merge: strix's side wins where the two collide, upstream's
non-conflicting changes stay, and fixes are ported into strix's code.

- server: upstream's final ggml-org#26004 (context checkpoints across slot
  save/restore) replaces strix's earlier port of it, keeping strix's on-device
  restore flags; test_slot_save.py follows upstream.
- cuda: strix's top-k (HIP radix), gated delta net and argsort kernels kept
  whole; upstream's CCCL major-version guard fix (ggml-org#29453) applied to strix's
  argsort. MMQ: upstream's out-of-bounds fix and host-side tile choice
  (ggml-org#29953) with strix's RDNA3.5 tile overrides on top; strix's fused MMQ paths
  pad src1 for the largest tile instead of the removed get_J_max. strix's
  128-column rms_norm fast path and two mmvf calls updated to upstream's new
  signatures (ggml-org#28175, warp_size).
- vulkan: strix's flash_attn_cm2.comp and topk_nary_search.comp kept whole
  (upstream's sparse cm2 FA ggml-org#30003 stays out with the rest of sparse FA).
- llama-context: strix's MTP draft vocabulary next to upstream's MoE cache.
- graph: upstream's single recurrent-state gather (ggml-org#29856) is restored and
  combined with strix's in-place gated delta net: in-place capable consumers
  keep the full gather and get their state view next to the consumer whether
  or not the rows are in place, so in-place and gathered ubatches build the
  same graph; this fixes the realloc aborts under GGML_SCHED_DEBUG_REALLOC in
  both upstream's shared-seq test and strix's seq cp graph reuse test.
- ggml-backend: alloc_buffer_n planning no longer flushes on zero-size
  tensors, which left views of a tensor larger than max_size uninitialized
  (caught by strix's test_view_init_after_max_size_split).
- SYNC.md: this fork now syncs with ggml-org/llama.cpp directly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
BurnWW pushed a commit to BurnWW/mx-llama.cpp that referenced this pull request Oct 15, 2026
811 upstream commits (incl. the b11553 rebase and the RCCL probe fallback).

Local-only content kept:
- L3 disk-backed prompt cache (LLAMA_CACHE_DISK_DIR) with the RAM watermark
  guard, disk-only spill and in-flight write wait.
- MTP draft fix: reset deferred_prefill_failed per task, clear a stale draft
  sequence when the batch position moves backward (adapted to the upstream
  process_decode(const common_batch &) signature).

Dropped as superseded upstream:
- asymmetric Q8_0-Q4_0 KV flash attention: upstream now compiles the K/V
  combination matrix from GGML_CUDA_FA_QUANTS; the qwen-tp2/tiel-tp2 configs
  need -DGGML_CUDA_FA_QUANTS=...q8_0-q4_0... at configure time instead.
- context checkpoints in slot save/restore sidecars: upstream ggml-org#26004 writes
  them into the snapshot file itself (with draft data and a fallback to full
  re-processing when a restored checkpoint does not fit).
roverdrubber pushed a commit to roverdrubber/llama.cpp that referenced this pull request Oct 15, 2026
…org#26004)

* server : preserve context checkpoints across slot save/restore

Append the checkpoints after the packed server_tokens payload added in ggml-org#26640
and count them in n_written / n_read, so a restored slot can still roll back to
a checkpoint instead of re-processing the whole prompt.

* server : drop draft checkpoint data that does not match the draft context

Restoring a slot saved with a different draft KV cache type aborted in
load_dft(). Test-load one draft checkpoint on restore and drop the draft
data if it does not fit, instead of crashing. Adds a regression test.

* server : harden the checkpoint appendix of slot save files

Bound each blob size by the bytes left in the file before allocating, open the
file with UTF-8 paths on Windows like the llama state payload, fall back to full
prompt re-processing when a checkpoint restored from a slot file fails to load,
and replace the 1024 count cap by keeping the last n_ctx_checkpoints while reading.

* server : report an incomplete checkpoint appendix as a failed slot save

Return an error to the client when the appendix cannot be written, like a
failed payload write, and make the oversized-blob test declare a size that
cannot be allocated, so an unbounded allocation fails the test.

* server : reject an empty target state in the checkpoint appendix

A saved checkpoint always holds a target state, an empty blob would roll back
without restoring anything. Also log with the slot id, and load the draft test
model from the HF cache instead of a second download.

* common : return bool from checkpoint load_tgt / load_dft

A checkpoint restored from a slot file falls back to full prompt re-processing
when it fails to load, a checkpoint created in memory still aborts.

---------

Fork: the checkpoints were already saved, beside the file in <file>.ckpt
(3991a0d). They are now appended to the file as upstream does; the
.ckpt sidecar is read only for files saved before this, and a save
removes it. The draft state stays in <file>.dft, which upstream does not
save, and its bytes no longer move the offset where the appendix is read.
test_slot_save_sidecars.py covers the old sidecar and its removal.

Co-authored-by: Igor Okulist <[email protected]>
Assisted-by: Claude Opus 5.5
roverdrubber added a commit to roverdrubber/llama.cpp that referenced this pull request Oct 15, 2026
Reading the checkpoint appendix (ggml-org#26004) test-loads one draft checkpoint
and then clears the draft's sequence, since upstream restores no draft
state. The fork read <file>.dft before it, so the restored cells were
cleared again, and a restored chat continued with a draft context that
held only the new tokens.

On the 27B (base, separate MTP head, 7.3K prompt, temperature 0), turn 3
of a chat after a restore, fresh server per arm:

  live                    draft cells 0..8189     0.667 (266/399)  66.6 t/s
  restored, this commit   draft cells 0..8189     0.667 (266/399)  66.9 t/s
  restored without .dft   draft cells 8159..8189  0.568 (251/442)  58.5 t/s

The restored chat now drafts exactly as the live one; before, it did as
the run without a .dft does. A replay that rolls back to a checkpoint was
unaffected, as each checkpoint carries its own draft state. No server
test covers it: it needs a hybrid target with a draft context and a
continuation that rolls back to no checkpoint, and the test models have
neither; the check is qwen-project/bench/mtp-restore-2026-10-15.

Assisted-by: Claude Opus 5.5
roverdrubber added a commit to roverdrubber/llama.cpp that referenced this pull request Oct 15, 2026
The slot file holds the target's cells only, so a restored MTP chat drafted from an empty draft context and lost acceptance. Save the draft's cells in <file>.dft and read them back after the checkpoints, whose loading clears the draft's sequence.

Port of 3991a0d, eb45582 and 50e85f0 from perf, without the .ckpt sidecar (ggml-org#26004 appends the checkpoints to the file).

Assisted-by: Claude Opus 5.5
ryanabx pushed a commit to ryanabx/llama.cpp that referenced this pull request Oct 22, 2026
Adapt the slot save/restore checkpoint appendix from ggml-org#26004 to the
shared_ptr checkpoint list and the common_state_data buffers.

Assisted-by: Claude Opus 5.5
ryanabx pushed a commit to ryanabx/llama.cpp that referenced this pull request Oct 22, 2026
Adapt the slot save/restore checkpoint appendix from ggml-org#26004 to the
shared_ptr checkpoint list and the common_state_data buffers.

Assisted-by: Claude Opus 5.5
Garretsw pushed a commit to Garretsw/llama.cpp that referenced this pull request Oct 26, 2026
Upstream master now persists context checkpoints (and the draft state)
in slot save files itself (ggml-org#26004, ggml-org#30574), and load_tgt/load_dft return
false instead of aborting. Resolve the conflicts in favour of master's
implementation:

- common: take master's bool load_tgt/load_dft and drop the now
  redundant try_load_tgt/try_load_dft
- server: drop the branch's file-scope "CKPC" appendix writer/reader in
  favour of master's save/load_slot_checkpoints + save/load_slot_draft,
  and master's checkpoint restore fallback (failed slot-file checkpoints
  force a full re-process and are invalidated)
- keep reporting n_ckpt_saved / n_ckpt_restored in the slot save/restore
  responses and the slot_checkpoints /props flag

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0186dV229bL7yh4joD2nXXAF
auRose94 pushed a commit to auRose94/llama.cpp that referenced this pull request Oct 28, 2026
…org#26004)

* server : preserve context checkpoints across slot save/restore

Append the checkpoints after the packed server_tokens payload added in ggml-org#26640
and count them in n_written / n_read, so a restored slot can still roll back to
a checkpoint instead of re-processing the whole prompt.

* server : drop draft checkpoint data that does not match the draft context

Restoring a slot saved with a different draft KV cache type aborted in
load_dft(). Test-load one draft checkpoint on restore and drop the draft
data if it does not fit, instead of crashing. Adds a regression test.

Co-authored-by: Igor Okulist <[email protected]>

* server : harden the checkpoint appendix of slot save files

Bound each blob size by the bytes left in the file before allocating, open the
file with UTF-8 paths on Windows like the llama state payload, fall back to full
prompt re-processing when a checkpoint restored from a slot file fails to load,
and replace the 1024 count cap by keeping the last n_ctx_checkpoints while reading.

* server : report an incomplete checkpoint appendix as a failed slot save

Return an error to the client when the appendix cannot be written, like a
failed payload write, and make the oversized-blob test declare a size that
cannot be allocated, so an unbounded allocation fails the test.

* server : reject an empty target state in the checkpoint appendix

A saved checkpoint always holds a target state, an empty blob would roll back
without restoring anything. Also log with the slot id, and load the draft test
model from the HF cache instead of a second download.

* common : return bool from checkpoint load_tgt / load_dft

A checkpoint restored from a slot file falls back to full prompt re-processing
when it fails to load, a checkpoint created in memory still aborts.

---------

Co-authored-by: Igor Okulist <[email protected]>
cwriter pushed a commit to cwriter/llama.cpp that referenced this pull request Nov 3, 2026
Adapt the slot save/restore checkpoint appendix from ggml-org#26004 to the
shared_ptr checkpoint list and the common_state_data buffers.

Assisted-by: Claude Opus 5.5
ServeurpersoCom pushed a commit that referenced this pull request Nov 5, 2026
#30137)

* checkpoints: reduce overhead

Assisted-by: Codex

* rebase

Adapt the slot save/restore checkpoint appendix from #26004 to the
shared_ptr checkpoint list and the common_state_data buffers.

Assisted-by: Claude Opus 5.5

---------

Co-authored-by: cwriter <cwriter@localhost>
digidocs pushed a commit to digidocs/llama.cpp that referenced this pull request Nov 15, 2026
ggml-org#30137)

* checkpoints: reduce overhead

Assisted-by: Codex

* rebase

Adapt the slot save/restore checkpoint appendix from ggml-org#26004 to the
shared_ptr checkpoint list and the common_state_data buffers.

Assisted-by: Claude Opus 5.5

---------

Co-authored-by: cwriter <cwriter@localhost>
lukekim added a commit to spiceai/llama.cpp that referenced this pull request Nov 16, 2026
* gguf-py : validate every tokenizer merge pair, not only the first (#31631)

* gguf-py : validate every tokenizer merge pair, not only the first

The transformers 4.45 pair format was detected by checking merges[0],
then every element was converted unchecked: a non-pair element raised
a bare TypeError, and pairs with the wrong arity or non-string parts
were silently mangled into invalid merges.

Validate each element (2-string list) up front and raise the existing
"Unknown tokenizer merges format" error for anything else.

Assisted-by: Devin

* gguf-py : remove test_vocab.py per review

* sycl : fix docker issue (#31605)

* add oneDNN in build image

* Update .devops/intel.Dockerfile

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

---------

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

* webgpu: return maxBufferSize from get_max_size and avoid whole-buffer bindings in memset/clear (#31348)

* Fix get_max_size and improve the memset shader

* Fix buffer_memset to  handle the buffer size more than max binding size.

* ui: show text and page thumbnails for PDF attachments, stop endless conversion retries (#31468)

* fix(ui): show extracted text in PDF attachment preview

Assisted-by: Claude (Opus 5.5 Medium)

* feat(ui): show page thumbnails for PDF attachments sent as images

Assisted-by: Claude (Opus 5.5 Medium)

* ui: stop retrying PDF preview conversion after it fails

A failed PDF-to-image conversion or text extraction reset its loading
flag, which re-ran the effect and retried forever. Remember the failed
item for each view and only retry when the item changes, so the error
state stays on screen.

Add a PdfConversionError story that feeds a broken PDF.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: keep the text of PDFs sent as images and tidy the PDF preview

Store the extracted text of a PDF sent as images in its content, so the
Text view reads it instead of parsing the PDF again; only messages stored
with the old placeholder extract it. The model still receives the images
only. Guard retries on the error state, as the item remounts per id, skip
an empty base64 payload, and share the status markup between views.

Assisted-by: Claude (Opus 5.5 Medium)

* model, mtmd: drama-3 tts support (#31613)

* model, mtmd: drama-3 tts support

* clean up

* mtmd: drama3 helper stops at the codebook tower limit

---------

Co-authored-by: Pascal <[email protected]>

* ui: open actions on right-click for chats, tabs, messages and models (#31545)

* ui : share directory resolution and the cwd row

Move the lookup of a browser-picked folder to ToolsService.resolveDirectoryPath, let the working directory picker run without its chip, and split the 'Set working directory to' row into its own component, so other views can pick and show a folder the same way.

Assisted by: Claude (Opus 5.5 Medium)

* ui : open an item's actions on right-click

Sidebar conversations and models manager rows open the same actions as
their "more actions" menu on right-click. Both menus render one shared
list of actions, so they cannot drift apart. Phones keep the browser's
long-press; the dropdown's drawer already holds the actions there.
An action can render a flyout submenu in place of its row, through the
kit of the menu it is in, and close the menu after a pick.

Adds the shadcn-svelte context-menu component, mirroring the
dropdown-menu one.

Assisted by: Claude (Opus 5.5 Medium)

* ui : close conversation tabs from a right-click menu

A tab's right-click menu closes it, the other tabs or the tabs to its
right, and stops a response the tab is generating. Closing tabs that
include the active one keeps the tab the menu was opened on.

Assisted by: Claude (Opus 5.5 Medium)

* ui : open a message's actions on right-click

User and assistant messages open the same actions as their action icons
on right-click. Selected text, links, media, code and fields keep the
browser's own menu, so copying them works as before. The fork dialog
opens from the actions context, like the delete one, so both the icon
and the menu can open it.

Assisted by: Claude (Opus 5.5 Medium)

* ui : scope right-click menu shortcuts and selection to their item

Show the conversation shortcuts only on the active row, as they act on
the active conversation, and keep the browser menu only for a selection
inside the message. Name the close-tab shortcut, and drop the unused
chip toggle, menu submenus and shared cwd row.

Assisted-by: Claude (Opus 5.5 Medium)

* opencl: improve decode perf with FA (#31633)

* opencl: use more workgroups for q4_K gate up + GLU

Co-authored-by: Shaofei Qi <[email protected]>

* opencl: handle FA for GQA 2 and 6 with head size 256

Co-authored-by: Shaofei Qi <[email protected]>

* opencl: handle FA for GQA 16 with head size of 128, 512

Co-authored-by: Shaofei Qi <[email protected]>

* opencl: handle FA for GQA 2 with head size 512

Co-authored-by: Shaofei Qi <[email protected]>

---------

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

* server : realtime: send an error event instead of crashing on exceptions (#31632)

* server : realtime: send an error event instead of crashing on exceptions

* server : route websocket handlers through ex_wrapper, remove the realtime test

* server : realtime: keep the previous tools when the chat template rejects new ones

* server : realtime: reject tool schemas the grammar cannot convert, drop ws_ex_wrapper

* server : realtime: clarify the tool schema check comment

* ci: run self hosted cpu jobs on hf or github (#31439)

* llama : fix on-device state copy sizes for quantized KV caches (#30541)

* llama : fix on-device state copy sizes for quantized KV caches

The on-device sequence state copies (LLAMA_STATE_SEQ_FLAGS_ON_DEVICE) computed
their element count as size / ggml_element_size(). For a quantized type such as
q8_0 or q4_0 that is the number of blocks, not elements, so only part of each
range was copied: the restored state was wrong, or the copy crashed.

Compute the count as size / ggml_type_size() * ggml_blck_size() for the save,
the restore and the copy between differently chunked ranges, and assert that
each range covers whole blocks.

* llama : drop the one-line comments

* llama : drop the redundant cast in the state copy size

* Title: CUDA: fuse NVFP4 gate/up matmuls and GLU in MMQ (#31296)

* cuda: fuse NVFP4 gate/up and GLU in MMQ

* cuda: honor the requested src1 precision in fused gate/up MMQ

* cuda: share NVFP4 scale checks, skip unused fused FP4 kernels

* cuda: test NVFP4 fused MMQ at W4A8 without scales and with batches, clean up naming

* cuda: check gate_scale before loading the fused NVFP4 gate scale

* opencl: add DSV4_HC_PRE and DSV4_HC_POST (#31623)

* opencl: add DSV4_HC_PRE and DSV4_HC_POST

Co-authored-by: Shafei Qi <[email protected]>

* opencl: improve dsv4_hc_post

Co-authored-by: Shaofei Qi <[email protected]>

---------

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

* opencl: support non-contig sigmoid (#31687)

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

* opencl: enable f32 and q5_k multi column GEMV by default for Adreno X2 (#31694)

* opencl: use the small-N f32 GEMV by default on X2E

Assisted-by: Claude Opus 5.5
Co-authored-by: Shaofei Qi <[email protected]>

* opencl: use the q5_K multi-column verify GEMV by default on X2E

Assisted-by: Claude Opus 5.5
Co-authored-by: Shaofei Qi <[email protected]>

---------

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

* qwen2 : add nvfp4 scales to build_ffn (#31657)

This commit adds nvfp4 scales to qwen2's build_ffn call which are
currently passed as NULL.

The motivation for this is that a model converted to NVFP4 will
currently crash because the scales are loaded but never applied in
the FFN:
```console
llama-completion: llama.cpp/src/llama-sampler.cpp:1218:
void llama_sampler_dist_apply(llama_sampler*, llama_token_data_array*):
Assertion `found' failed.
```
The attention already applies its scales but ffn is missing them.

* metal: keep fusable node groups inside one command buffer (#31688)

The first command buffer takes the first 10% of the graph nodes and the
rest is split evenly between the extra command buffers. A fusion cannot
span two command buffers, so a boundary that falls inside a fusable
group runs that group unfused, and the output then depends on the node
count of the graph.

Move each boundary to the end of the fusable group it falls into, so
the encoders fuse the same nodes as with a single command buffer.

* tests: fix CI flakes of TOPK_MOE caused by near ties (#31426)

* tests: fix CI flakes of TOPK_MOE caused by near ties

With uniform random logits, two experts sometimes land within one f32
ulp of each other at a routing boundary, mostly with sqrt_softplus
gating whose output range is narrow. A backend whose gating differs by
a few ulps from the CPU then picks the other expert and the test fails.

Draw each row of logits again until the group selection and the final
top-k both have a relative margin of 1e-4, computed on the host in
double precision.

* tests: build the TOPK_MOE logits by inverting the gating function

Draw the selection scores (probs plus bias) of each row as a random
permutation of a grid, move the experts of the best groups up by half a
step, and set the logits to the inverse of the gating function at these
scores. Every expert and group decision is then one grid step apart on
all backends, and the host no longer recomputes the routing.

The softmax probs are built to sum to one so that the softmax keeps the
scores, and the views of the logits are not initialized again after the
logits are set.

* vulkan: Re-enable large coopmat matmul configuration on AMD proprietary driver 26.10.1+ (#31587)

* rpc : align code with common.cpp (#31684)

Signed-off-by: Adrien Gallouët <[email protected]>

* server : drop u8path() and use generic_string() (#31682)

Signed-off-by: Adrien Gallouët <[email protected]>

* common : drop u8path() and use generic_string() (#31681)

Signed-off-by: Adrien Gallouët <[email protected]>

* ci : remove unused model generation (#31412)

* ci : re-enable test-llama-archs on Windows

* cont : remove unused test

* graph: store the MTP conv snapshots of every recurrent model in one set_rows (#31660)

* graph: store the conv state of every rollback arch in one set_rows

The rollback slots of the causal conv history were written with one
copy per slot in qwen4exp, glm5-next, kimi-k3, bailingmoe3, lfm and
mamba2, while delta_net already wrote them with a single set_rows.
build_conv_state_store now does this for all of them: one copy without
rollback, otherwise one set_rows of the overlapping windows into the
min(n, n_rs_seq + 1) slots a rollback can read.

The slot order {n_rs_seq, ..., 0} is computed once per graph and each
conv layer takes a view of its tail. Its size does not depend on the
ubatch, so the reserved graph covers every ubatch shape, and the graph
input that held it is gone.

A model that is not causal never rolls back, so the context clamps
n_rs_seq to 0 for it, like for an arch without rollback support.

* nits: compute the conv slot order in the graph and keep the n_head name of bailingmoe3

* graph: build the conv slot order in each conv layer

The slot order {K-1, ..., 0} of the conv state store was one tensor
shared by every conv layer of the graph, built on the device of the
first one, so each layer on another device copied the view of its
tail. Each conv layer now builds its own order next to its set_rows,
and llm_graph_input_rs no longer holds it.

* webgpu : add MEAN support (#31591)

Assisted-by: Codex

* fit : account for skipped NextN layers when setting n_gpu_layers (#31569)

* fit : account for skipped NextN layers when setting n_gpu_layers

Without MTP, fit counts n_layer + 1 layers while the model loader counts
n_layer_all + 1 for n_gpu_layers, including the NextN layers which hold no
weights. A fit result that offloads all layers then leaves layer 0 on the CPU
("offloaded 65/66 layers" for Qwen3.8-27B on two GPUs).

Add the skipped NextN layers to n_gpu_layers and to the tensor split of the
device that holds the output layer so the loader assigns the layers that
fit measured.

Fixes #31531

* fit : pass hp_ngl_skip by reference like the other hparams

* fit : add hp_ngl_skip to common_get_device_memory_data

* server : reject non-object session updates (#31714)

Prevent malformed realtime session updates from throwing an uncaught
exception and terminating the server

Signed-off-by: Adrien Gallouët <[email protected]>

* metal : use mul_mm for 32 <= K < 64 (#30982)

* metal : use mul_mm for 32 <= K < 64

* metal : add bf16 x bf16 mul mat kernel

---------

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

* conversion : resolve quantized_layers from source tensor names (#31611)

* conversion : resolve quantized_layers from source tensor names

This commit changes how the per layer NVFP4 quant_algo are resolved from
hf_quant_config.json quantized_layers.

The keys in quantized_layers are module paths in the source checkpoint,
and these can be either be modules like 'lm_head' or parent modules
like 'layers.0.ffn.experts'. Currently these keys are passed through
filter_tensors, but they are not tensor names. So a filter_tensors that
keeps an explicit list of tensor names, like Nemotron's with --mtp
would drop them. That means there was no `_nvfp4_layer_algo entry`, and
`_tag_prec_a4` fell back to `_nvfp4_global_algo`.

This commit records the mapping from source tensor name to filtered
tensor name in index_tensors. Then in prepare_tensors each source
tensor is resolved to its closest quantized_layers parent, and
the algo is stored under the filtered tensor name, which is what
_tag_prec_a4 later looks up.

Converting Nemotron 3.5 Lightning NVFP4 with --mtp now produces:
```console
    general.tensor_extra.name = ['output.weight']
    general.tensor_extra.prec_a4 = [False]
```
whereas on master no general.tensor_extra fields are written. For the
non-MTP conversion, the general.tensor_extra fields are identical to
master.

Also manually verified (using pdb) that this works for
DeepSeek-V4.1-Flash-1017-NVFP4.

Refs: https://github.com/ggml-org/llama.cpp/pull/31602#issuecomment-6603337403

* conversion : shorten comment

* conversion : also remove '.bias' suffixes

* ggml : support `truncate=false` for YaRN (#30206)

* ggml : support `truncate=false` for YaRN

YaRN calculates correction intervals to switch frequency interpolation
methods, but the setting to not round the boundaries of these intervals
to integers (`truncate=false`) was not supported.

Models that use `truncate=false` include gpt-oss and some PLaMo-3
models; to support them correctly, the GGML operations and CPU backend
are modified to handle calculations without rounding. The default
behavior is `truncate=true`, and existing calls not explicitly
configured will maintain their previous behavior.

* support CUDA backend

* add tests

* move RoPE helpers to internal header

* format

* llama-server: Use reference-counted checkpoints instead of deep-copies (#30137)

* checkpoints: reduce overhead

Assisted-by: Codex

* rebase

Adapt the slot save/restore checkpoint appendix from #26004 to the
shared_ptr checkpoint list and the common_state_data buffers.

Assisted-by: Claude Opus 5.5

---------

Co-authored-by: cwriter <cwriter@localhost>

* vulkan : check combined K+V f16 scratch size in FA dequant path (#30487)

Fixes #30048

Assisted-by: Claude

* vulkan: FWHT kernels for block widths above 512 (#29772)

* vulkan: add F16 input to the FWHT

The Vulkan FWHT accepts F32 input only. This adds an F16 source variant of the
shader, for both the subgroup and the shared-memory paths, so the kernel reads
an F16 source directly instead of requiring a converted copy.

The F16 shader needs shader-float16, so the pipelines are only created when the
device reports it. A null pipeline makes ggml_vk_can_use_fwht fall back, which
is the same path an unsupported width already takes.

supports_op and the dispatch both already route through ggml_vk_can_use_fwht,
so there is a single place asking whether an op qualifies; nothing to
consolidate here the way the CUDA/Metal ports needed.

test-backend-ops on an M5 Pro (MoltenVK, fp16: 1): MUL_MAT 1128/1128,
including all 24 Hadamard cases (18 existing F32, 6 new F16).

Assisted-by: Codex

* vulkan: FWHT kernels for block widths above 512

The Vulkan FWHT covers block widths 64 to 512; wider blocks fall back to the
dense matmul. Extend the width list to 8192 and pick the shader per width: the
subgroup shader keeps n/subgroup_size values per invocation, so widths above
512 (or a subgroup narrow enough to exceed 64 values per invocation) use the
shared-memory shader with one row per workgroup and a 256-wide block. The rows
per workgroup become a specialization constant so the dispatch matches.

Pipelines for a width are only created when the device's shared-memory and
workgroup-invocation limits allow it; otherwise that width keeps the fallback.

This is the Vulkan counterpart to #29100 (CUDA). Stacked on #29101; the last
commit is the one to review.

Assisted-by: Codex

* CUDA: linearize MoE data layout for MMQ/MMF (#31047)

* CUDA: linearize MoE data layout for MMQ/MMF

* Apply MMQ tile size optimization more generally

* Fix F16 performance regression

* CUDA/HIP: matrix-core (MFMA) lightning indexer for CDNA2 (gfx90a) (#29050)

* CUDA/HIP: matrix-core (MFMA) lightning indexer for CDNA2 (gfx90a)

* Addressing reviewers comments, mma.cuh and physical warp size

* CUDA/HIP: single mma.cuh matrix-core lightning indexer ::CDNA::

* Support RDNA3

* CUDA/HIP: stream heads through the mma lightning indexer kernel

Process 16 heads at a time with double-buffered Q staging instead of keeping
all heads resident in shared memory, and drop the GGML_INDEXER_NO_MFMA env.

* enable for CUDA

* CUDA: Remove wmma lightning-indexer, also run head 32 through mma kernel

* CUDA: Nv mma dosent transpose accumulator

---------

Co-authored-by: Carl Philipp Klemm <[email protected]>
Co-authored-by: Johannes Gäßler <[email protected]>

* metal : fuse DeepSeek-V4/V4.1 and GLM MoE routing (#31615)

* metal : support scale-bias routing norm in the TOPK_MOE fusion

The DeepSeek-V4.1 graph normalizes the routing weights with a scale+bias
(sum + 1e-20) instead of the lower clamp used by the other models. Add
norm_bias/norm_scale_bias fusion chains that accept a SCALE node with a
unit scale factor at the clamp position, pass an additive bias in the
kernel args, and apply it as max(wt_sum, clamp) + bias so both variants
share one kernel. Cover the new chains in test-backend-ops.

Assisted-by: dsh:llama.cpp/ggml-org/GLM-5.3-Flash-GGUF (Mac Studio, M5 Ultra, 256GB)

* metal : fuse sqrt(softplus) MoE routing with a selection bias

Add TOPK_MOE chains anchored at the softplus node (UNARY+SQRT+ADD+
ARGSORT+GET_ROWS plus optional norm/scale) so the DeepSeek-V4/V4.1
routing fuses on Metal. The kernel scores with sqrt(softplus) and ranks
selection-biased keys while the gathered weights and the norm stay
unbiased, matching the reference graph. Dispatch hooks at the softplus
node, cover the norm-bias combination in test-backend-ops and record the
new deepseek4/deepseek41 fusion counters.

Assisted-by: dsh:llama.cpp/ggml-org/GLM-5.3-Flash-GGUF (Mac Studio, M5 Ultra, 256GB)

* metal : fuse sigmoid MoE routing with a selection bias

The sigmoid-gated MoE archs (GLM, DeepSeek-V2/V3.2, ...) rank
sigmoid(logits) + exp_probs_b with an optional weights-norm, but only
the softmax and sqrt(softplus) routing chains were fusable.

- add 6 sigmoid-anchored TOPK_MOE chains: sigmoid + ADD + ARGSORT +
  GET_ROWS with optional SCALE and SUM_ROWS + CLAMP/SCALE + DIV norm
  tail; the selection-bias ADD is required, same as the sqrt(softplus)
  chains
- generalize the gating function constant from a sqrt(softplus) bool
  to an int (0 = softmax, 1 = sqrt(softplus), 2 = sigmoid); sigmoid
  scores are 1 / (1 + exp(-logits)), matching the CPU, Metal unary and
  CUDA kernels
- anchor the unary dispatch hook at sigmoid nodes too
- test-backend-ops: 4 sigmoid routing cases with and without a
  weights scale
- re-record tests/fusion/MTL.csv: the sigmoid archs (glm5-next,
  deepseek2/32, kimi, minimax, ...) now fuse their routing, and
  muse-spark prefill drops one MOE_REDUCE fire because the reordered
  graph allocates the routing weights inside the reduce output range,
  which the dst/input overlap check correctly declines

Assisted-by: dsh:llama.cpp/ggml-org/GLM-5.3-Flash-GGUF (Mac Studio, M5 Ultra, 256GB)

* cont : remove low-signal comments

* ocd : valign ggml_metal_fusions

* gguf-py : external chat templates have precedence over tokenizer_config (#31717)

* vulkan: RDNA3/4 Large-Tile Split-K Optimization (#30280)

* RDNA3/4 Vulkan Large-Tile Split-K Optimization

* Add single-operator performance test cases

* Update the policy to use driver-reported LDS usage

* Add comments

* Use the simpler split_k rule from review

Assisted-by: GitHub Copilot

* tests : drop the split_k test cases

* vulkan : simplify the RDNA3/4 split_k condition

* CUDA: use highest compiled arch in get_mmvq_mmid_max_batch (#31679)

Co-authored-by: DukeNukem-dev <[email protected]>

* vulkan: Implement test-fusion interface (#30769)

* ggml-cuda: sanitize post-bias NaNs in MoE selection (#31005)

Fixes #28370

* vendor : update cpp-httplib to 0.65.0 (#31731)

Signed-off-by: Adrien Gallouët <[email protected]>

* server : simplify windows MCP command resolution (#31728)

* server : simplify windows MCP command resolution

Signed-off-by: Adrien Gallouët <[email protected]>

* common : remove utf8_to_wstring()

Signed-off-by: Adrien Gallouët <[email protected]>

---------

Signed-off-by: Adrien Gallouët <[email protected]>

* llama: refactoring: move model to class member of llm_graph_context (#31733)

* ui: prevent a hidden sidebar from intercepting clicks (#31712)

* ui: prevent a hidden sidebar from intercepting clicks

* ui: also fix desktop sidebar

* model: Add support for the xing4_0  (#31589)

* model: add support for Xing4.0

* Update src/models/xing4_0.cpp

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

* Update src/models/xing4_0.cpp

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

* Update src/models/xing4_0.cpp

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

* Update src/models/xing4_0.cpp

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

* Update src/models/xing4_0.cpp

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

* Update src/models/xing4_0.cpp

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

* fix: rename model file to xing4-0.cpp to match CI expectations

* model: rename xing4_0.cpp to xing4-0.cpp

* lint: fix E128 continuation indent in conversion/xing.py

* tests: add xing4_0 fusion baseline for Metal

* reduce comments

---------

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

* model : add Ripple (ricursiveai) (#31692)

* feat : added ricursiveai ripple support

* fix : mandatiry SWA, scale through helper, comments back

* fix : metal

* model : make ricursive RoPE/NoPE explicit and validate the layer pattern

Write attention.rope_pattern and read it as optional, falling back to the
sliding window pattern so existing GGUFs keep loading. Refuse a
sliding_window_pattern that does not cover every layer, a model with no
sliding layer, and a gate or value residual present in only some layers.
The converter derives layer_types when the config omits it, ignores a stale
hybrid_layer_pattern and drops tensors of features the config disables.

Assisted-by: Claude Opus 5.5

* model : make ricursive swiglu_clamp per-layer

Store swiglu_clamp as a per-layer array, read it with get_key_or_arr so the
scalar in existing GGUFs still applies to every layer, and refuse a negative
or non-finite value. Add a test-llama-archs fixture with mixed per-layer
clamps and no rope_pattern, so the saver roundtrip checks both.

Assisted-by: Claude Opus 5.5

* model : use the ricursive per-tensor scales and RoPE parameters

Pass the attn_gate and output weight scales to build_lora_mm, take
ext_factor and attn_factor from the graph instead of hardcoding them, and
copy rope_freq_scale_train to the SWA layers instead of pinning it to 1.
Cite the reference lines for the value residual and the NoPE layers.

Assisted-by: Claude Opus 5.5

* convert : drop the ricursive chat_template.jinja override

The precedence between tokenizer_config.json and chat_template.jinja is to
be changed in SpecialVocab for all models instead. Until then a new
conversion stores the short tokenizer_config.json template; GGUFs that
already carry the tool-aware template are not affected.

Assisted-by: Claude Opus 5.5

* fix : remove NVFP4 checkpoint quantization block

* match #31733 refactor

---------

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

* models : recursive fix (#31749)

* llama, mtmd: (chatterbox) add use_classifier_free_guidance as gguf metadata (#31698)

* llama, mtmd: add use_cfg as gguf metadata

* use_classifier_free_guidance

* llama: fix kv shifting, add tests, add per-model build_rope (#31683)

* llama: fix kv shifting and add tests

* llama: add graph build_rope (#31693)

* llama: add graph build_rope

* improve

* migrate new models

* update review skill

* fix ci

* add --kv-shift to CI

* ci: fix build-cmake-pkg ccache (#31705)

* tests : drop u8path() (#31755)

[no ci]

* mtmd: enable cmake unity build (#31760)

* hexagon: Implement set_tensor_n and improve repacking/tiling robustness (#31744)

* hex-repack: move repacking/tiling into graph-optimize

* hex-tiling: simplify tiling rules and remove obsolete helpers

* hex-ops: use a hash for de-duplicating tensor descriptors

* hex-bufs: improve tensor hash

* hex-ops: accept empty (zero-elements) ops

* hex-bufs: enable hostbuf by default and reject tensors that do not fit into max_vmem

* hex-bufs: improve error message and update readme

* hex-bufs: make sure to sync flush opbatch in all sync set_tensor paths

* opencl: add q6_k multi column tiled GEMV for speculative verification and refactoring (#31758)

* opencl: use the multi-column q6_K vocab head GEMV for 2..4 tokens on X2E

Co-authored-by: Shangqing Gu <[email protected]>
Assisted-by: Claude Opus 5.5

* opencl: rename GGML_OPENCL_Q6K_MC3 to GGML_OPENCL_Q6_K_MC3

Co-authored-by: Shangqing Gu <[email protected]>
Assisted-by: Claude Opus 5.5

* opencl: rename GGML_OPENCL_Q40/Q41/Q4K_MC3 to GGML_OPENCL_Q4_0/Q4_1/Q4_K_MC3

GGML_OPENCL_Q4K_MC3_DQ and GGML_OPENCL_Q4K_MC3_LDS become GGML_OPENCL_Q4_K_MC3_DQ
and GGML_OPENCL_Q4_K_MC3_LDS.

Co-authored-by: Shangqing Gu <[email protected]>
Assisted-by: Claude Opus 5.5

* opencl: remove unnecessary debug probe

Co-authored-by: Shangqing Gu <[email protected]>
Assisted-by: Claude Opus 5.5

* opencl: clean up

---------

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

* common : restrict HF token to huggingface.co hosts (#31730)

Signed-off-by: Adrien Gallouët <[email protected]>

* CUDA: fix Maxwell build (#31787)

* vendor: update BoringSSL to 0.20261105.0 (#31757)

[no ci]

* ci : bump CUDA 13 release builds to 13.5 (#31788)

* ci : bump CUDA 13 release builds to 13.5

* docker : bump cuda13 images to 13.5.0

* moe-cache : LRFU/MQ-like hybrid cache, ClassLRU (#31233)

* moe-cache : LRFU/MQ-inspired hybrid cache

* make the clock advance by N tokens: use the real token count (ne[1] is always 1, ids have n_expert_used entries per token)

* sel is a RESHAPE node, the orig input is in src[0], so sel->src[0]->ne[1] is the count

* c for the class index, last_use for last use time

* explain the roles of these

* compute the key once

* use the key directly instead of re-reading

* show how the score is computed from the age

* remove the branch and clarify exp2 and log2 relationship

* reword the header comment and elaborate on unused slots and sorting

* not a copy, not just skip

* std::array maybe

* Revert "std::array maybe"

This reverts commit 7649b1f172db4941a854ad115bec0c7e062b65b9.

* half life it is

* add key and iteration helpers

* extract decayed_crf

* bump classes to 8, document the formula, display the cache size in token worth count

* assert the computed number of classes matches the half life

* vulkan: detect ReBAR support, avoid BAR allocations if unavailable (#31658)

* webgpu: add batched tensor API (`get_tensor_n` and `set_tensor_n`) (#31473)

* add set_tensor_n and get_tensor_n

* fix for editor-config checker

* remove the outdated comment

* opencl:  support repeat for f16, i32, i16, bf16 (#31782)

* opencl: add f16 repeat

Assisted-by: Codex

* opencl: support repeat for i32, i16, bf16

Assisted-by: Codex

* opencl: update ops

Assisted-by: Codex

* cmake : generate RC file directly without win-app.rc.in (#31718)

Signed-off-by: Adrien Gallouët <[email protected]>

* tests : override hardware_concurrency in CI (#31797)

The self-hosted CPU runners are containers with 8 CPUs, but
std::thread::hardware_concurrency reports the cores of the host. The
table mode of test-llama-context sizes its pool from that count, so it
runs 4 models x 8 threads on an 8-CPU job and hangs.

Add TEST_ARG_HARDWARE_CONCURRENCY and TEST_ARG_PARALLEL_WORKERS as the
defaults for the auto-selected counts of test-llama-context and of
test-backend-ops, and set them to 8 and 4 for cpu-x64-high-perf.

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)

* tests : qualify isnan and signbit with std:: (#31791)

* tests : qualify isnan and signbit with std::

The unqualified calls rely on the C math.h names also being present in the
global namespace, which is not the case for the NetBSD 11.99.9/x86_64 gcc
14.4.0 build reported in the issue.  Prefix the calls with std:: to select
the standard C++ overloads declared by <cmath>.

ref: https://github.com/ggml-org/ggml/issues/1681

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

* tests : qualify C math calls with std::

Follow-up to the isnan / signbit fix: make the remaining math calls in
test-quantize-fns.cpp consistent with the std:: isfinite / max / numeric_limits
already used in the same file.

The float variants are overloads in C++, not distinct names, so the mapping is
fabsf -> std::fabs, copysignf -> std::copysign, nextafterf -> std::nextafter -
not std::fabsf & friends, which do not exist in libstdc++ and would break the
gcc build.  NAN and INFINITY are macros and are left unqualified.

Only behavioural difference: array_rmse() fed a double accumulator to sqrtf(),
now std::sqrt() keeps the computation in double.  The result is more accurate
and differs from the previous value by at most 1.4e-7 relative, three orders of
magnitude below the tightest tolerance in this test.

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

* cli : fix crash on invalid UTF-8 in prompt or files (#31563)

Assisted-by: Claude

* docker: add explicit /usr/local/nvidia search path (#31806)

* hexagon: conv_2d optimizations and support for conv_3d (#31814)

* hexagon: Generalization of CONV_2D implementation for CONV_3D

- New op HTP_OP_CONV_3D is wired through htp-ops.h, main.c (shares op_conv_2d) and the op remap in htp-kparams.cpp.
- conv_3d runs on the existing HMX tiled (implicit GEMM) conv2d path. KD and KH are folded into one virtual kernel row (KD*KH), and output rows are counted as N*OD*OH.
- htp_kparams_solve_conv3d checks the conv_3d layout and calls the tiled solver htp_kparams_conv2d_tiled, which takes an is3d flag.
- The tiled kernel takes the sizes and strides that differ between conv_2d and conv_3d from a struct htp_conv_geom. Only the input stage unfolds depth.
- 256-entry DMA queue can no longer overflow

Assisted-by: Claude Code

* hexagon: modify checking to eliminate divide-by-zero hazards

* hexagon: conv2d tiled: compute the conv_3d unfold divisors on the host

The KH and OH fastdiv values used to unfold conv_3d kh into (kd, kh) and
oh into (od, oh) were built per op on the device, each with a 64-bit
divide. Pass them in the kernel params instead; they fit in the space the
window variant already reserves, so the struct size does not change.

Assisted-by: Claude Code

* hexagon : preserve fold scheduling in conv2d for small size

hexagon : support arbitrary positive conv2d strides
Support positive horizontal strides for WHCN and CWHN inputs. Preserve
load/shuffle paths for strides 1/2 and use gather for larger strides.

hexagon : improve conv2d tile size selection

Prefer the largest feasible output-channel block and derive spatial
chunk capacity from VTCM usage. Compare capacity and thread-aligned
candidates using per-thread work and chunk overhead.

Co-authored-by: Yiwei Shao <[email protected]>

* hex-conv: fix compiler warning

---------

Co-authored-by: Yiwei Shao <[email protected]>
Co-authored-by: Max Krasnyansky <[email protected]>

* model: add Kimi-K3.1-Pro text model (#31779)

* model: add Kimi-K3.1-Pro text model

K3 with the full-attention MLA layers replaced by DSA: on this checkpoint 24
of the 93 layers carry a lightning indexer (32 heads x 128, top_k 2048, no
rope). The KDA (linear-attention) layers and the rest of the K3 skeleton -
cross-layer residuals, latent MoE, situ, MLA output gate, full-rank KDA gate -
are unchanged, so this reuses the K3 graph and converter and adds the indexer.

Indexer:
  - the selection is an additive mask over the whole cache, not a gather of
    the top-k rows, so it reuses the existing sparse flash attention path;
    off that path the mask stays correct but still costs a kq over the cache
  - the indexer key LayerNorm takes its eps from the model's rms_norm_eps,
    because dsa_config declares no eps of its own

Graph and cache:
  - new arch with four indexer tensors per DSA layer, and a hybrid memory
    that keeps a K-only MLA cache for those layers, recurrent state for the
    KDA layers, and the indexer key cache
  - the graph node budget shares the K3 entry

Conversion:
  - KimiK31Model(KimiK3Model), picked by KimiK31ForConditionalGeneration
  - dsa_config becomes attention.indexer.{head_count,key_length,top_k,types}
    plus the indexer LayerNorm eps; the layer list is 1-indexed like
    linear_attn_config's, and the converter asserts that it covers exactly
    the full-attention layers
  - the routed experts stay MXFP4 and are repacked as in K3, not dequantized
  - the vision tower and mm_projector are skipped: text only for now
  - the arch key follows the checkpoint's own model_type ("kimi_k31") and the
    loader registers KimiK31ForConditionalGeneration; the release name carries
    a -Pro suffix that nothing in the config or the tensor names uses

Quantisation: the indexer's q_b, k and proj are kept out of the quant
overrides, since the top-k selection is sensitive to their precision.

Verified on an 8-layer slice against the HF checkpoint: 38 tensors checked
exactly, the indexer metadata against the config, and the selection against
full attention - identical PPL at top_k beyond the context length, divergent
once top_k is forced below it. Arch test fixture and the full arch suite pass.

* converter: avoid clutter in the k3 base

* narrow comment to match model

* update metal fusion expectations

* restore

* sync with PR 31733 refactoring

* hexagon: fuse post-norm residual add into RMS_NORM_MUL (#31822)

* hexagon: fuse post-norm residual add into RMS_NORM_MUL

* hex-fusion: refactor RMS_NORM fusion and add dedicated RMS_NORM_MUL_ADD opcode

Improves performance by keeping things in HVX registers.
Also simplifies overall fusion logic and logging.

---------

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

* meta : raise the compute view limit for buffers with few tensors (#31447)

* ggml-backend-meta : minimum number of compute views per buffer

Assisted-by: Claude Opus 5.5

* tests : revert the deepseek41 test model to 6 layers

Assisted-by: Claude Opus 5.5

* opencl: add arange (#31829)

Assisted-by: Claude Opus 5.5

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

* llama : add missing link to pthread (#31785)

* llama : add missing link to pthread

Signed-off-by: Adrien Gallouët <[email protected]>

* Link Threads::Threads privately

Signed-off-by: Adrien Gallouët <[email protected]>

---------

Signed-off-by: Adrien Gallouët <[email protected]>

* CUDA: fix shared memory bank conflicts in the lightning indexer (#31803)

* vulkan: Add 'readonly' to decodeBuf declarations. (#31833)

In a future driver version I hope to be able to get some perf gain out of this.

* webgpu :  Implement group norm kernel (#31490)

* Only run webgpu CI on my fork

* Add webgpu only workflow

* Add WebGPU group_norm kernel

* clean up

* resolve merge conflicts

* parameterize data type; clean up cmake changes

* add nullptr check

* clean up webkit experiments

* more cleanup

* more cleanup

* clang format

* Remove unused feature check for WebGPU

* clean up supports_op condition and update documentation

* add perf tests for group_norm

* clean up doc with script and undo change in test-backend-ops

* Do 2d dispatch of workgroups

* Do 2d dispatch of workgroups

* Unstage unrelated changes

* undo docs churn

* add new test case

* undo small change

* undo small change

* server: visit parent slots before child slots (#30779)

* server: visit parent slots before child slots
A parent slot wakes its waiting child slots once it finishes the shared
prompt prefix, while slots are visited in id order. When a child task
lands on a lower slot id than its parent, the child is visited before
the parent wakes it and waits an extra batch to process its suffix.
Non-child slots are now visited before active child slots, so every
child woken by its parent joins the same batch.

* server: check systemone test events through test tags

The systemone tests matched free-form debug messages, including the
formatted f_keep value of the prompt cache. The server now emits
__TEST_TAG_WAIT_PARENT_SLOT__ when a child slot waits for its parent,
__TEST_TAG_PROMPT_CACHE_RESTORE__ on every prompt cache restore and
__TEST_TAG_PROMPT_CACHE_FULL_RESTORE__ when the whole cached prompt is
a prefix of the new one, compared on token counts.

---------

Co-authored-by: Pascal <[email protected]>

* metal : fix GROUP_NORM for ne03 > 1 and non-contiguous inputs (#31852)

The kernel_group_norm_f32 kernel and its host dispatch ignored the
batch dimension (ne03) of the source tensor: only ngrp threadgroups
were dispatched and each normalized the flat range
[tgpig*gs, (tgpig+1)*gs) with gs = ne00*ne01*ceil(ne02/ngrp). For
tensors with ne03 > 1, all but the first ne00*ne01*ne02 elements were
left unwritten (exposed by the new GROUP_NORM test with
ne=[3,1,1,65537], num_groups=1).

Dispatch one threadgroup per (group, i03) pair (ngrp in x, ne03 in z,
same work distribution as the Vulkan backend) and compute per-batch
statistics, matching the CPU reference. Also clamp the group element
count for the last group when ne02 is not divisible by ngrp and use
int64_t indexing.

The kernel now only requires ggml_is_contiguous_rows(op->src[0])
instead of full contiguity: it addresses src0 and dst with their own
strides (nb03 and the dst strides are added to the kernel args - dst
can be a strided view of src0 with ggml_group_norm_inplace) and falls
back from the flat fast path to a strided path that decodes the linear
element index when rows or channels are padded. The flat/strided
selection is done on the host in
ggml_metal_library_get_pipeline_group_norm and compiled into one of
two specialized pipeline variants via a FC_group_norm_flat function
constant, so the dead path is eliminated at pipeline creation.
GROUP_NORM support is also gated on F32 src and dst in supports_op -
the kernel only implements f32 and an f16 input would silently be read
as f32.

Assisted-by: dsh:llama.cpp/ggml-org/GLM-5.3-Flash-GGUF (Mac Studio, M5 Ultra, 256GB)

* sycl: add f16 support for SWIGLU_OAI (#30857)

* llama_moe_cache: run missed experts on CPU, add tuning script (#30966)

* moe-cache : compute part of the misses on the CPU

--moe-cache-cpu-share F computes a share F of the MoE cache misses on the CPU
from the host experts instead of uploading them. The graph builds the expert
FFN twice: on the device from the cache slots, where the misses left to the CPU
read zero slots, and on the CPU from the host experts, where the experts
computed on the device have id -1. The two results are added before the down
bias.

- ggml-cpu: MUL_MAT_ID skips negative ids and writes zero rows
- sched: the copy callback is called for all the inputs of a split, and before
  the host sync when there are no events
- the slot lookup callback reads the inputs of the CPU part together with the
  selected experts, so the CPU part does not wait for the device, and its
  result is copied back asynchronously
- each token uses distinct zero slots, mul_mat_id does not support an expert
  selected twice by a token
- LLAMA_MOE_CACHE_TRACE writes the selected experts of each lookup, for a
  simulator of the cache

* scripts : add moe-cache-tune.py to pick the MoE cache arguments

The script wraps a llama-server command: it starts the server at two cache
sizes and three CPU shares, fits the upload and CPU speeds of the machine, and
replays the routing of the runs through a copy of the cache logic to predict
other sizes and shares. It prints the recommended --moe-cache-mib and
--moe-cache-cpu-share.

docs/moe-cache.md describes the MoE cache arguments and the script.

* add am17an as codeowner for MoE cache

* moe-cache : upload all the misses until the cache is full

With a high --moe-cache-cpu-share, few misses are uploaded, so an empty cache
fills slowly and more misses than needed go to the CPU. The CPU share now
starts once all the slots of a cache group hold an expert. moe-cache-tune.py
replays the same rule.

* add backend sync for async transfer queue

* moe-cache : let the scheduler copy the results of the CPU part

* Fix MSVC compilation

* remove sync change

* llama-graph : extract the CPU share condition into can_cpu_share

* llama-graph : make llm_graph_params::moe_cache const

The graph construction no longer updates the MoE cache directly: the CPU
parts of the layers are accumulated in the graph result and applied to
the cache in llama_context::process_ubatch, after the graph inputs are
set and before the graph is computed.

Assisted-by: dsh:llama.cpp/ggml-org/GLM-5.3-Flash-GGUF (Mac Studio, M5 Ultra, 256GB)

* scripts : replay the ClassLRU policy in moe-cache-tune.py

* moe-cache : pick CPU misses by CRF instead of random (#31853)

* moe-cache : remove the backend logic of the CPU part from the graph

The CPU part reads the host experts, so the scheduler places it on the
CPU without set_tensor_backend. The cache gives no CPU map for batches
that a device would offload. Graphs with a CPU part look up their own
slot map, so the graph does not register the part with the cache.

ggml-backend : the inputs of the next split that are already computed
are copied to host memory before the current split runs, so a CPU split
does not wait for the device split before it. This replaces the stash
of the cache, and the copy callback is again called for host weights
only.

* llama-graph : return the MoE cache slots and CPU ids in a struct

The scheduler prefetch no longer checks that the next split runs on
another backend: the inputs of a split are never on its own backend,
so the input loop already skips that case.

---------

Co-authored-by: Gaurav Garg <[email protected]>
Co-authored-by: Georgi Gerganov <[email protected]>
Co-authored-by: Alexey Kopytko <[email protected]>

* mtmd: support MageVL-Cowork model (#31819)

* mtmd: support MageVL-Cowork model

* mtmd: keep magevl rope_freqs at model level and check its shape

The rope factors are shared by every layer, so they live in clip_model
instead of a pointer copied into each clip_layer. The loader now checks
that v.rope_freqs is F32 with d_head elements and that d_head splits
into the 4:6:6 pairs the graph expects.

---------

Co-authored-by: Pascal <[email protected]>

* mtmd: move log-mel computation to cgraph (#31808)

* mtmd: move log-mel computation to cgraph

* rm stray file

* also include source in mtmd_audio_track

* rm stray file

* rm mtmd_audio_stft_op

* add test

* hexagon: n_hvx and n_threads cleanup (#31857)

* hex-nhvx: apply nhvx updates to the latest master

* hex-nhvx: set N_HVX and N_THREADS based on the arch to avoid overallocation

* hex-build: add support for enabling HTP_DEBUG via build.py

* hex-trace: move tracing state/helpers into new htp-trace.h header

* hex-dcache: cleanup dcache #defines

* hex-hnvx: minimize the diff by reflowing the macros

* hex-ci: fix python type/linter warnings

* hex-nhvx: consitent logging

* sycl: refuse device buffers that would exceed VRAM (#31285)

* sycl: exact rounding in CPY to Q4_1, Q5_1 and Q8_0 (#31465)

* hexagon: support for automatic loading of libhtp without legacy env vars (#31781)

* hexagon: use absolute skel path

* hexagon: support non-ascii dir and long path in skel-abs path

* hex-libdir: add support for FASTRPC_MANAGE_DSP_LIBRARY_PATH and GGML_HEXAGON_LIBHTP_DIR on all platforms

* hex-libdir: keep extra fwd slash in abs path on Android and Linux

* hex-libpath: always start with absolute path then fallback to session ctl then env

* hex-libdir: add CDSP1,2,3 to the fallback, needed for the IQ10

---------

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

* server : downgrade per-request proxy logs to trace (#31859)

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

* common : sanitize invalid UTF-8 in PEG tool call arguments (#31861)

* opencl: improve q8_0 and MoE small-n verification for spec (#31831)

* opencl: add kernel_gemv_noshuffle_q8_0_f32_mc

Assisted-by: Claude Opus 5.5
Co-authored-by: Shaofei Qi <[email protected]>
Co-authored-by: Hongqiang Wang <[email protected]>

* opencl: small-n MoE GEMV for q5_1, q4_k

Assisted-by: Claude Opus 5.5
Co-authored-by: Shaofei Qi <[email protected]>
Co-authored-by: Hongqiang Wang <[email protected]>

* opencl: adreno kernel k floor 256 for x2

Assisted-by: Claude Opus 5.5
Co-authored-by: Shaofei Qi <[email protected]>
Co-authored-by: Hongqiang Wang <[email protected]>

* opencl: small-n MoE GEMV for more quants

Assisted-by: Claude Opus 5.5
Co-authored-by: Shaofei Qi <[email protected]>
Co-authored-by: Hongqiang Wang <[email protected]>

* opencl: rename function

* opencl: disable bin FA for small verify batch

---------

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

* speculative : do not apply the MoE cache to the draft model (#31497)

* llama, mtmd: follow the reference precision of ggml_prec_set_acc calls (#31851)

* llama, mtmd: follow the reference precision of ggml_prec_set_acc calls

Requests that the reference implementation does not keep in F32 move
to GGML_PREC_BF16: the GLM4 family down and output projections, the
MiMoVL vision matmuls and the Qwen3-TTS speaker encoder conv1d. The
DeepSeek V4/V4.1 routers and the MiniMax-M3 indexer stay in F32 with
a link to the reference line that computes them in F32.

* ggml: handle GGML_PREC_BF16 the same way as GGML_PREC_F32 in backends

Backends that reject GGML_PREC_F32 on the src1 of MUL_MAT_ID now also
reject GGML_PREC_BF16 (CUDA, Hexagon, OpenCL, WebGPU, Vulkan), and
backends that accept GGML_PREC_F32 for flash attention now also accept
GGML_PREC_BF16 with the same F32 accumulation (CPU, SpaceMIT, ET).
Vulkan keeps the F32 transfer between devices for both. The CUDA
cuBLAS path already handles GGML_PREC_BF16 and is unchanged.

* tests: cover GGML_PREC_BF16 in the flash attention tests

The flash attention cases run with GGML_PREC_BF16 next to F32 and
DEFAULT, and var_to_str prints bf16 so these cases keep their own name.

* llama: request GGML_PREC_BF16 for the KQ multiplication

* cont : add TODO in clip.cpp

---------

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

* ggml : switch to F32 src1 in the CPU backend (#31854)

* ggml : switch to F32 src1 in the CPU backend

Change the default computation for GGML_TYPE_F16 to use F32 for src1
data in matrix multiplications: vec_dot_type(F16) is now F32 and the dot
product goes through the new ggml_vec_dot_f16_f32 (x = F16 src0, y = F32
src1), so src1 is no longer quantized to F16 and worst-case inputs that
only fit in the F32 FP range are handled correctly.

- conv_2d/conv_3d: store im2col patches (the inner mul_mat src1) as F32
  and pass separate src0/src1 types to the inner mul_mat; the previous
  F16 patches made the inner mul_mat widen src1 into the conv work
  buffer, corrupting the patches and crashing on large inputs
- conv_transpose_1d/2d (F16 kernel): keep src1 in F32 in the work buffer
  and use ggml_vec_dot_f16_f32; update work buffer planning accordingly
- supports_op: restore MUL_MAT support for F16 src1, which is now
  widened to F32
- ggml_vec_dot_f16_f32: add GGML_SIMD support by converting chunks of x
  to F32 and reusing the F32 SIMD dot
- mul_mat/mul_mat_id: add TODOs for a more efficient F16 x F16 path that
  can be used if ggml_prec_get_src(dst, 1) allows converting src1 to F16

MUL_MAT f16 x f32 perf on M5 Ultra (GFLOPS):
- m=2048, n=512, k=16 : 120.9 -> 101.7
- m=2048, n=512, k=64 : 150.5 -> 344.2
- m=4096, k=14336 GEMV:    63 -> 343-415
- m=4096, n=512, k=14336: 65.6 -> 770.2

Assisted-by: dsh:llama.cpp/ggml-org/GLM-5.3-Flash-GGUF (Mac Studio, M5 Ultra, 256GB)

* cont : add some F16 x F32 vectorized paths

* cont : enable the fused F16 x F32 dot on AVX without FMA

The 256-bit fused path of ggml_vec_dot_f16_f32 required AVX2 and FMA,
so CPUs with AVX and F16C only fell back to the chunked conversion and
F16 decode was 4x slower than before. Enable it on __AVX__ && __F16C__
and accumulate with GGML_F32x8_FMA, which does mul + add without FMA.

---------

Co-authored-by: Pascal <[email protected]>

* ci: move runners to Ubuntu 26.04 (#31529)

* ci: update to ubuntu26.04

Signed-off-by: Aaron Teo <[email protected]>

* ci: bring back toolchain workaround

Signed-off-by: Aaron Teo <[email protected]>

* ci: remove workaround completely

Signed-off-by: Aaron Teo <[email protected]>

* ci: more switching to ubuntu 26.04

Signed-off-by: Aaron Teo <[email protected]>

* ci: pin android cmake version

Signed-off-by: Aaron Teo <[email protected]>

* ci: restore ubuntu 24.04 for s390x

Signed-off-by: Aaron Teo <[email protected]>

* ci: fix missing s390x ubuntu 24.04 release link

Signed-off-by: Aaron Teo <[email protected]>

* ci: switch release-publish to ubuntu-latest

Signed-off-by: Aaron Teo <[email protected]>

* devops: revert --break-system-packages

Signed-off-by: Aaron Teo <[email protected]>

* ci: bring back ubuntu 24.04 for arm release

Signed-off-by: Aaron Teo <[email protected]>

* ci: revert ubuntu 26.04 from release.yml

Signed-off-by: Aaron Teo <[email protected]>

* ci: fix broken links

Signed-off-by: Aaron Teo <[email protected]>

* ci: fix openvino job naming

Signed-off-by: Aaron Teo <[email protected]>

* devops: revert vulkan dockerfile to use system python3

Signed-off-by: Aaron Teo <[email protected]>

---------

Signed-off-by: Aaron Teo <[email protected]>

* webgpu : add COUNT_EQUAL support (#31578)

* webgpu : add COUNT_EQUAL support

Assisted-by: Codex

* webgpu : reduce small COUNT_EQUAL inputs in one dispatch

Assisted-by: Codex

* webgpu : simplify COUNT_EQUAL and reuse existing tests

* webgpu : move COUNT_EQUAL pipeline cache declaration

* Update ggml/src/ggml-webgpu/ggml-webgpu.cpp

Co-authored-by: Masashi Yoshimura <[email protected]>

* tests : simplify COUNT_EQUAL coverage

---------

Co-authored-by: Masashi Yoshimura <[email protected]>

* moe-cache : ensure CPU part does not wait for the cached experts (#31888)

* ggml-cuda : add d_state=64 fast path to SSM_SCAN kernel (#31818)

Zamba2 and similar architectures use a state size of 64 in their
recurrent-scan step, which fell outside the GPU kernel's existing
fast paths (96, 128, 256). Every scan step was falling back to CPU,
bottlenecking generation to 6-7 tok/s against the 50-70 tok/s band
other architectures achieve on the same hardware.

Add a 4th template instantiation for d_state=64, following the
existing pattern; no change to the underlying math. Verified against
the existing CPU-reference correctness harness with 3 new test cases
built from Zamba2's real hyperparameters (28/28 passing).

Measured ~35% throughput improvement (11 -> 15.1 tok/s) on Zamba2-7B-
Instruct. Full parity with other architectures not yet reached - a
separate, unrelated fraction of scan calls (~28%) still falls back to
CPU for a cause not yet diagnosed.

Assisted-by: Claude Sonnet 5

Co-authored-by: Sargentmajord <[email protected]>

* ggml : update CUDA/Metal radix Top-K to make tied selections deterministic (#31084)

* ggml : fix for the radix TOP_K thread timing bug

* make the key an ordered 64-bit pair

* a rewrite without shift-skip logic

* fix casts

* warp-contiguous layout

* reduce the scope removing vulkan+metal changes

* turn it off for Metal/ROCm, note about cub::DeviceTopK

* fix the hip build

* skip Vulkan as well

* popc lambda from fattn

* do block_cols math in int64_t

* make it allowlist bc SYCL looks non deterministic too

* ggml : make Metal radix Top-K tied selections deterministic

The radix top-k kernel gathered the selected indices with atomic
counters, so the order of the tied candidates at the threshold (and,
with more ties than remaining slots, the subset itself) depended on
the thread scheduling.

Replace the two atomic compaction loops with a deterministic scheme:
count the elements above and tied with the threshold in contiguous
per-thread chunks, rank them with a simdgroup scan and a serial scan
over the (now unused) radix histogram, and write each kept element
exactly once in column order. The output is now byte-identical
across runs.

This is also faster than the atomic version: the strided atomic
loops become contiguous passes, reducing top-k times by ~20-45% on
M5 Ultra, with tie-heavy shapes within a few percent.

Assisted-by: dsh:llama.cpp/ggml-org/GLM-5.3-Flash-GGUF (Mac Studio, M5 Ultra, 256GB)

* tests : enable deterministic top-k check on Metal, add radix-path tie cases

Metal now produces deterministic tied selections for the radix top-k
path, so the determinism self-check runs for the MTL backend as well.

Add eval cases covering the radix path (ncols > 2048) with more ties
at the threshold than remaining slots, and tie-heavy perf cases to
monitor the cost of the deterministic tie handling.

Assisted-by: dsh:llama.cpp/ggml-org/GLM-5.3-Flash-GGUF (Mac Studio, M5 Ultra, 256GB)

* ggml : use coalesced accesses in the Metal radix Top-K compaction

The deterministic compaction walked contiguous per-thread chunks with
scalar sequential loads, which the memory system of the M2 Ultra can
not overlap well: the radix Top-K times regressed by ~1.5-2.4x on the
large-ncols shapes.

Give each warp a contiguous chunk of the row instead and let the lanes
interleave within it with stride 32, so every access is fully
coalesced. The lanes write their kept elements at lane-major ranks,
which is deterministic, and only a tie overflow falls back to a
per-step cross-lane ranking to keep the lowest tied indices in column
order.

Assisted-by: dsh:llama.cpp/ggml-org/GLM-5.3-Flash-GGUF (Mac Studio, M5 Ultra, 256GB)

* tests : remove the extra top-k tie and perf cases

The radix-path eval and tie-heavy perf cases were added to validate and
benchmark the Metal deterministic tie handling. Keep only the enabling
of the determinism self-check for the MTL backend.

Assisted-by: dsh:llama.cpp/ggml-org/GLM-5.3-Flash-GGUF (Mac Studio, M5 Ultra, 256GB)

* metal: scan the radix bins and warp totals with a simdgroup

The radix top-k selected the threshold bucket with a serial scan of
the 256 bins by thread 0 in each of the 4 passes, and ranked the warps
of the compaction with two serial scans by thread 0. The first
simdgroup now does both: each lane sums 8 bins, an exclusive prefix
sum and a ballot find the lane that reaches the k-th value, and the
warp totals get their exclusive bases from simd_prefix_exclusive_sum.

* tests: enable the deterministic top-k check on ROCm

HIP has no cub::DeviceTopK, so every row goes through the radix or
bitonic path, which break ties in the same way in each run. The check
covers all tie cases on ROCm, including the 1 and 2 row ones that CUDA
skips.

* cuda: remove the redundant radix top-k counter reset

Address review from ORippler. top_k_radix_init already zeroes
greater_count for each chunk of rows and top_k_radix_select keeps it,
so the reset kernel before the gather is one launch with no effect.

---------

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

* llamafile: impl bf16 and q8_0 vxe (#31866)

Signed-off-by: Aaron Teo <[email protected]>

* cpu: enable SpacemiT IME2 MXFP4 dense repack (#31776)

Assisted-by: Codex

Signed-off-by: gitGurugu <[email protected]>

* mtmd: refactoring: remove clip.h, consolidate code into mtmd (#31865)

* ggml-zdnn: fix release binary not detecting backend lib (#31905)

Signed-off-by: Aaron Teo <[email protected]>

* opencl: add f32 MUL_MAT_ID (#31783)

* opencl: add f32 mul_mat_id

* opencl: handle -1 index

* opencl: make loading moe_sort_by_expert general

* tests: bound the test_rope tolerance by the f32 angle resolution (#31874)

The rotation angle of a position p is rounded in f32 to about
p*FLT_EPSILON radians, and the CPU reference and the GPU kernels reach
it through different rounding sequences (cumulative product versus
pow). With positions up to 8192 this puts the NMSE floor between
backends near 8e-8, so the default 1e-7 threshold fails at random on
Metal. Derive the tolerance from n_ctx instead: it stays at 1e-7 for
n_ctx=512 and becomes 9.5e-7 for the YaRN cases at n_ctx=8192.

* sycl: cache device-id (#31126)

* ggml : support YaRN truncation config on openvino, sycl, vulkan, webgpu, rpc (#30802)

* openvino : support YaRN truncation config

* sycl : support YaRN truncation config

* vulkan : support YaRN truncation config

* webgpu : support YaRN truncation config

* rpc : support YaRN truncation config

* RPC: Improve loading times (#29413)

* RPC: improve loading

* cont : bump RPC protocol version

* address review comments

* cont: more review comments

* cont : clean-up

---------

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

* mtmd: Pocket TTS - add generic support for temperature set via API (#31655)

* mtmd, server : add temperature to /tts, default Pocket TTS to 0.3

Assisted-by: Claude Opus 5.5

* feat: add temp parameter in llama-tts

* temp: fix default hardcoded values

* fix: remove too narrow test

* fix: addressing PR comments

* opencl : include climits (#31935)

* metal : make ggml_tri select instead of scaling by the comparison (#30711)

* metal: make ggml_tri select instead of scaling by the comparison

The kernel multiplied by the 0/1 comparison, which turns a +-inf outside the triangle into NaN, while the CPU kernel writes a plain zero there. Select, like the CPU does.

Adds test_tri_special, which puts +-inf into the cells that have to be discarded, for all four triangle types. It fails against the previous kernel and passes with this change.

* Just trim down the repetitive comments.

* metal : prevent out-of-bounds writes to the Metal FA output buffer (#31662)

Co-authored-by: Zhuomin Chen <[email protected]>

* ci : Run gfx1151 ROCm job on Strix Halo Devlab runners (#31567)

* fix(rocm,ci): Update ci workflow to use devlab ci runners for gfx1151

* ci : move gpu-rocm job to Strix Halo devlab runners

Assisted-by: Claude

* ci : ROCm 10 wheels with per-GPU device packages for gpu-rocm; add gfx1201

The runners' system ROCm 7.2.1 cannot compile the current HIP code for
gfx1151 ("Invalid dpp_ctrl value" in mmf-instance-ncols_*.cu). Go back
to the TheRock ROCm 10 wheels with the device-<gfx> extra, so rocBLAS
has the target's kernels, and keep ci/run.sh's results and models under
$RUNNER_TEMP instead of the runners' RAM-backed home. Add a gfx1201
(Radeon AI PRO R9700) row with HIP graphs disabled.

Assisted-by: Claude

---------

Co-authored-by: David Hekimian <[email protected]>

* models : Attach Granite NVFP4 weight scales (#31449)

* models : Attach Granite NVFP4 weight scales

* feat: Pass nvfp4 scales through build_ffn for all granite architectures

Branch: granite-nvfp4-moe-scales
AI-usage: full (Claude + Sonnet 5.5)
Signed-off-by: Gabe Goodhart <[email protected]>

---------

Co-authored-by: Gabe Goodhart <[email protected]>

* ggml-backend: don't upload inputs that are not read  (#31419)

* stop uploading inputs nothing reads

* Address nitpicks

* ui: fold, preview and rearrange the sidebar's sections (#31936)

* ui : fold the sidebar's conversation sections

Pinned and Recent conversations fold under their heading. The whole heading
row is the toggle; its chevron follows the title, shows on hover and stays
while the section is folded. Folded sections are remembered across reloads.

Assisted-by: Claude (Opus 5.5 Medium)

* ui : show a sidebar section's first six chats

Pinned and Recent list their first six chats and end with a Show more
row that opens the whole section; Show less, sticking to the bottom of
the sidebar while the section scrolls under it, closes it back. The
expanded sections last for the session.

Assisted-by: Claude (Opus 5.5 Medium)

* ui : rearrange the sidebar's sections and chats by dragging

Pinned and Recent can be dragged by their title. The real section follows
the pointer, tinted like the sidebar's resize handle and edged with a
faint border, the other sliding aside as it passes; let go, it glides from
there into its new slot. The order is remembered across reloads, and a
section never moved keeps its default place. All sections now scroll
together.

A chat dragged onto Pinned is pinned, onto Recent unpinned. A lifted copy
of the row follows the pointer while the row slides out of its section.
The section under the pointer takes the same tint and border; a section
ignores its own chats. Let go, the row slides in where its section sorts
it, the rows below making room, and the copy glides into it; anywhere
else, it slides back into its own section.

While dragging, the rows and headings passed over take no hover. Dragging
needs a mouse or a pen, so a finger still scrolls the sidebar; the sidebar
scrolls near its edges, and Escape cancels.

Assisted-by: Claude (Opus 5.5 Medium)

* ui : set the sidebar's sections apart from their rows

A section heading now reads above its chats: larger, semibold and in the
full foreground colour. Chat titles drop to a regular weight in a slightly
softened colour, full again when the chat is open or hovered, and "Show
more" drops to a regular weight in the muted colour. Chats inside a
section sit closer together, sections further apart, and the sidebar's
actions get more room above and below.

Assisted-by: Claude (Opus 5.5 Medium)

* mtp: read the target hidden states from a device buffer (#31927)

* tests : keep dummy ffn.act scales away from zero (#31940)

The dummy-model generator fills every tensor from a plain normal pool.
`blk.N.ffn.act.scales` is a divisor in the mpt graph, so with seed
1224489258 it draws |v| ~ 1e-6, and `ffn_act = gelu(...) / scales` reaches
2.7e5. Metal stages both operands of `kernel_mul_mm_f32_f32` as half, so
those activations overflow to inf, the norm downstream turns the inf into
nan and the logits come out nan, while the CPU reference stays in f32 and
stays finite. Both NMSE values then become nan and the check fails.

Give `ffn.act` the same treatment as `rope_factors` and keep its magnitude
away from zero.

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)

* ggml : implement the backward pass for TRI (#30712)

* ggml: implement the backward pass for TRI

GGML_OP_TRI had no case in the backward switch, so a trainable graph containing it aborted with "unsupported ggml op for backward pass: TRI". The op is linear, so its gradient is masked the same way. The incoming gradient is not necessarily contiguous (the backward of a transpose hands over a view) and ggml_tri requires contiguity, so it is made contiguous first.

test_tri gains a post_transpose variant (out = transpose(tri(a))) that aborts as above without this change.

* ggml : simplify the TRI backward pass

Pass the gradient directly to ggml_tri and drop the transpose test. The existing TRI cases cover the backward pass for contiguous F32 gra…
fencerJP pushed a commit to fencerJP/llama-apu that referenced this pull request Nov 21, 2026
ggml-org#30137)

* checkpoints: reduce overhead

Assisted-by: Codex

* rebase

Adapt the slot save/restore checkpoint appendix from ggml-org#26004 to the
shared_ptr checkpoint list and the common_state_data buffers.

Assisted-by: Claude Opus 5.5

---------

Co-authored-by: cwriter <cwriter@localhost>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge ready A maintainer can use this label to indicate that they consider the changes final and ready to merge. server

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Misc. bug: /slots save/restore silently loses all prompt reuse on hybrid/recurrent models — checkpoints are never persisted