llama: read a released KV/recurrent state from its host shadow

After llama_context_release_device(ctx, true) the KV cache and the recurrent
state live only in host shadows, and their tensors have no buffer, so
llama_state_seq_get_data cannot read them. The disk prompt cache must save
a cold server's slots at exit, and a shutting-down server must not restore
to the device (it may not hold the GPU token, F7).

llama_context_restore_memory_host() makes the state readable without the
device. restore_device_buffers(to_host = true) wraps each shadow as a
CPU_Mapped buffer (ggml_backend_cpu_buffer_from_ptr) and points the tensors
into it: there is no copy and no allocation. The first version copied into a
CPU buffer instead, which needs the full KV allocation a second time, about
2.7 GB for the 35B at ctx 131072; the node has had an OOM-controller kill
before. The buffer base is rounded down to the 32-byte alignment that
cpu_buffer_from_ptr asserts (a large std::vector is only 16-byte aligned);
those leading bytes are never accessed. With to_host the shadows are kept,
because the buffers point into them.

It sets device_discarded, so restore_device() aborts afterwards. Exit only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
LumpiastyandClaude Opus 5.5 committed 2026-11-22 20:38:32 +01:00
1 parent 724a5d6373
commit aa46b82321
13 files changed
+71 -15

No files matched your search

+8 -2
View File
@@ -2141,7 +2141,7 @@ void llama_kv_cache::release_device_buffers(bool keep_shadow) {
}
}
bool llama_kv_cache::restore_device_buffers() {
bool llama_kv_cache::restore_device_buffers(bool to_host) {
if (!dev_released) {
return true;
}
@@ -2151,6 +2151,10 @@ bool llama_kv_cache::restore_device_buffers() {
continue;
}
ggml_context * ctx = ctxs_bufs.bufs[i].first.get();
if (to_host) {
ctxs_bufs.bufs[i].second.reset(llama_memory_wrap_host(ctx, sh.data));
continue;
}
ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, sh.buft);
if (buf == nullptr) {
LLAMA_LOG_ERROR("%s: failed to reallocate KV cache device buffer (out of VRAM?)\n", __func__);
@@ -2166,7 +2170,9 @@ bool llama_kv_cache::restore_device_buffers() {
ctxs_bufs.bufs[i].second.reset(buf);
}
dev_released = false;
dev_shadows.clear(); // recaptured on next release
if (!to_host) {
dev_shadows.clear(); // recaptured on next release; to_host buffers point into the shadows
}
return true;
}