From fc31d3afd040cc2527ec7143962f3fc6878ec84d Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 08:05:06 -0600 Subject: [PATCH 1/8] tests: a checkpoint as a parked sequence id, proven against a cold run (0 bytes moved vs a 23.9 MB serialize) Joel 2026-11-16: "Pass raw memory by reference ... never encode decode ever ... Pass textures by id don't rasterize." A server checkpoint today serializes the sequence out of device memory (llama_state_seq_get_data) and parses it back on restore. The fork's memory already offers the by-id form: llama_memory_seq_cp shares attention KV cells by sequence id, and recurrent state is copy-on-write on the device (find_slot moves a sharing sequence to an empty cell with src = the shared one; the step graph gathers it via s_copy), so a checkpoint is a parked sequence id. test-seq-park (-m ): prefill 300 tokens on seq 0, park it (seq_cp 0 -> 1), advance seq 0 through 120 other tokens, restore (seq_rm 0; seq_cp 1 -> 0), decode the next token, and compare its logits with a cold run over the same prefix. Receipt, qwen35-0.8b (hybrid=1), this build, M5 Metal: serialized checkpoint 23,894,492 bytes in 1,783 us; parked checkpoint 0 bytes moved, park 13 us, restore 40 us; restored vs cold logits max |diff| 0.0044, argmax 82 = 82 (the difference is batch shape: the cold run decodes 301 tokens in one batch, the restored one 300 + 1). Builds with 0 warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo (cherry picked from commit 6c9713929a03c88232eb8f04ca0890673169d1c2) --- tests/CMakeLists.txt | 1 + tests/test-seq-park.cpp | 132 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 133 insertions(+) create mode 100644 tests/test-seq-park.cpp diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 413aae6e87db..a60b7cd01258 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -206,6 +206,7 @@ endif () llama_build(test-recurrent-state-rollback.cpp) llama_build_and_test(test-server-view-end.cpp) +llama_build(test-seq-park.cpp) # needs -m : a checkpoint as a parked sequence id (CONTINUUM-ENGINE 4.7.11) # GGML_TENSOR_FLAG_GRAD: a leaf whose gradient the backward computes, never optimized (the walk reads the cached prefix K/V gradient) llama_build_and_test(test-grad-leaf.cpp) diff --git a/tests/test-seq-park.cpp b/tests/test-seq-park.cpp new file mode 100644 index 000000000000..cd0d23ec9741 --- /dev/null +++ b/tests/test-seq-park.cpp @@ -0,0 +1,132 @@ +// what this catches: a checkpoint as a PARKED SEQUENCE (CONTINUUM-ENGINE 4.7.11), by id, never +// serialized. The live sequence is copied to a parked id with llama_memory_seq_cp (attention KV cells +// shared by sequence id, the recurrent state shared and copied on the device only when the live +// sequence advances), the live sequence moves on through different tokens, then is restored from the +// parked id; its next-token logits must equal a cold run's over the same prefix. Also times park and +// restore against today's path (llama_state_seq_get_data serializing the sequence to host bytes). +// +// usage: test-seq-park -m (a hybrid or recurrent model exercises the recurrent path) +#include "arg.h" +#include "common.h" +#include "llama.h" + +#include +#include +#include +#include + +static int64_t now_us() { + return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); +} + +static llama_context * make_ctx(const common_params & params, llama_model * model) { + auto cparams = common_context_params_to_llama(params); + cparams.n_seq_max = 2; // seq 0 live, seq 1 parked + cparams.n_ctx = 1024; + cparams.n_batch = 512; + cparams.n_ubatch = 512; + cparams.kv_unified = true; // one stream: a parked id shares the live sequence's cells + return llama_init_from_model(model, cparams); +} + +static bool decode(llama_context * ctx, const std::vector & toks, llama_pos p0, llama_seq_id seq) { + llama_batch batch = llama_batch_init((int32_t) toks.size(), 0, 1); + for (size_t i = 0; i < toks.size(); ++i) { + common_batch_add(batch, toks[i], p0 + (llama_pos) i, { seq }, i + 1 == toks.size()); + } + const bool ok = llama_decode(ctx, batch) == 0; + llama_batch_free(batch); + return ok; +} + +static std::vector last_logits(llama_context * ctx, int n_vocab) { + const float * l = llama_get_logits_ith(ctx, -1); + return std::vector(l, l + n_vocab); +} + +int main(int argc, char ** argv) { + std::setlocale(LC_NUMERIC, "C"); + common_params params; + if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_COMMON)) { + return 1; + } + common_init(); + llama_backend_init(); + llama_model * model = llama_model_load_from_file(params.model.path.c_str(), common_model_params_to_llama(params)); + if (model == nullptr) { + std::fprintf(stderr, "FAILED: model did not load\n"); + return 1; + } + const int n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(model)); + std::printf("model: recurrent=%d hybrid=%d\n", (int) llama_model_is_recurrent(model), (int) llama_model_is_hybrid(model)); + + constexpr int N = 300, M = 120; // the prefix to keep; tokens the live sequence advances through + std::vector prefix, detour; + for (int i = 0; i < N; ++i) prefix.push_back((llama_token) (1000 + (i * 7919) % 20000)); + for (int i = 0; i < M; ++i) detour.push_back((llama_token) (2000 + (i * 104729) % 20000)); + const llama_token next = 4242; + + // reference: a cold run over prefix + next + std::vector ref; + { + llama_context * ctx = make_ctx(params, model); + std::vector all = prefix; + all.push_back(next); + if (!decode(ctx, all, 0, 0)) { std::fprintf(stderr, "FAILED: reference decode\n"); return 1; } + ref = last_logits(ctx, n_vocab); + llama_free(ctx); + } + + llama_context * ctx = make_ctx(params, model); + llama_memory_t mem = llama_get_memory(ctx); + if (!decode(ctx, prefix, 0, 0)) { std::fprintf(stderr, "FAILED: prefix decode\n"); return 1; } + llama_synchronize(ctx); + + // today's checkpoint: serialize the live sequence to host bytes + const int64_t t_ser0 = now_us(); + std::vector blob(llama_state_seq_get_size(ctx, 0)); + const size_t written = llama_state_seq_get_data(ctx, blob.data(), blob.size(), 0); + const int64_t t_ser = now_us() - t_ser0; + + // the parked checkpoint: a sequence id, no bytes moved + const int64_t t_park0 = now_us(); + llama_memory_seq_cp(mem, 0, 1, -1, -1); + const int64_t t_park = now_us() - t_park0; + + // the live sequence moves on through other tokens (this is where the recurrent state is copied on + // the device, copy-on-write, inside the step's own graph) + if (!decode(ctx, detour, N, 0)) { std::fprintf(stderr, "FAILED: detour decode\n"); return 1; } + llama_synchronize(ctx); + + // restore: drop the live sequence, take the parked one's cells and state by id + const int64_t t_rest0 = now_us(); + if (!llama_memory_seq_rm(mem, 0, -1, -1)) { std::fprintf(stderr, "FAILED: seq_rm\n"); return 1; } + llama_memory_seq_cp(mem, 1, 0, -1, -1); + const int64_t t_rest = now_us() - t_rest0; + + if (!decode(ctx, { next }, N, 0)) { std::fprintf(stderr, "FAILED: restored decode\n"); return 1; } + const std::vector got = last_logits(ctx, n_vocab); + + float max_diff = 0.0f; + int argmax_ref = 0, argmax_got = 0; + for (int i = 0; i < n_vocab; ++i) { + max_diff = std::max(max_diff, std::fabs(ref[i] - got[i])); + if (ref[i] > ref[argmax_ref]) argmax_ref = i; + if (got[i] > got[argmax_got]) argmax_got = i; + } + std::printf("serialized checkpoint: %zu bytes in %lld us (host copy of the sequence)\n", written, (long long) t_ser); + std::printf("parked checkpoint: 0 bytes moved, park %lld us, restore %lld us\n", (long long) t_park, (long long) t_rest); + std::printf("restored vs cold logits: max |diff| = %.6g, argmax %d vs %d\n", max_diff, argmax_got, argmax_ref); + + llama_free(ctx); + llama_model_free(model); + llama_backend_free(); + + // the same backend, the same tokens, the same positions: the restored state must be the cold one + if (argmax_got != argmax_ref || max_diff > 1e-2f) { + std::fprintf(stderr, "FAILED: the restored sequence does not reproduce the cold run\n"); + return 1; + } + std::printf("test-seq-park: ok\n"); + return 0; +} From 6772f8b7ebf429e153c00b03dcabeb0b671cc1c1 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 08:08:26 -0600 Subject: [PATCH 2/8] tests: the server's checkpoint form (partial state only) as a parked recurrent cell, proven The server's checkpoints hold only the PARTIAL state (LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY: recurrent / SWA) and trim attention by position. The parked form of exactly that: seq_cp(live, parked, 0, 0) (an empty attention range copies no KV cells; the recurrent half takes the live cell by id), the live sequence advances, then restore in the server's order: seq_cp(parked, live, 0, 0) for the recurrent cell, then seq_rm(live, N, -1) to trim attention. Receipt, qwen35-0.8b (hybrid), this build, M5 Metal, 300-token prefix: today's partial serialize 20,201,932 bytes in 1,190 us; parked 0 bytes, holding no attention cells (seq_pos_max of the parked id = -1), park 3 us, restore 29 us; restored next-token logits equal a cold run's (argmax 82 = 82, max |diff| 0.0044, batch shape). The full-sequence case still passes (23.9 MB vs 0 bytes, 13/27 us). On unified memory the parked cell occupies the same bytes as the copy, in device memory: the win is no copy, no duplicate host buffer, no compressor; the count is budgeted (n_seq_max at load). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo (cherry picked from commit be79edc18c3adf2c9a683ee451c3775a8776caef) --- tests/test-seq-park.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/tests/test-seq-park.cpp b/tests/test-seq-park.cpp index cd0d23ec9741..b9ea459043be 100644 --- a/tests/test-seq-park.cpp +++ b/tests/test-seq-park.cpp @@ -107,6 +107,39 @@ int main(int argc, char ** argv) { if (!decode(ctx, { next }, N, 0)) { std::fprintf(stderr, "FAILED: restored decode\n"); return 1; } const std::vector got = last_logits(ctx, n_vocab); + // the server's form: a checkpoint holds only the PARTIAL state (recurrent / SWA), attention KV is + // trimmed by position. Park only the recurrent cell (an empty attention range [0, 0) copies no + // KV cells), advance, then restore the recurrent cell by id and trim attention past the prefix. + // start from a clean prefix: the recurrent state cannot be trimmed back past `next` + llama_memory_seq_rm(mem, 1, -1, -1); + llama_memory_seq_rm(mem, 0, -1, -1); + if (!decode(ctx, prefix, 0, 0)) { std::fprintf(stderr, "FAILED: second prefix decode\n"); return 1; } + llama_synchronize(ctx); + const int64_t t_ppark0 = now_us(); + llama_memory_seq_cp(mem, 0, 1, 0, 0); + const int64_t t_ppark = now_us() - t_ppark0; + const llama_pos parked_kv_max = llama_memory_seq_pos_max(mem, 1); + if (!decode(ctx, detour, N, 0)) { std::fprintf(stderr, "FAILED: second detour\n"); return 1; } + llama_synchronize(ctx); + const int64_t t_prest0 = now_us(); + llama_memory_seq_cp(mem, 1, 0, 0, 0); // the recurrent cell, by id + const bool trimmed = llama_memory_seq_rm(mem, 0, N, -1); // attention past the prefix + const int64_t t_prest = now_us() - t_prest0; + if (!trimmed) { std::fprintf(stderr, "FAILED: attention trim after the partial restore\n"); return 1; } + if (!decode(ctx, { next }, N, 0)) { std::fprintf(stderr, "FAILED: partial restored decode\n"); return 1; } + const std::vector got_partial = last_logits(ctx, n_vocab); + float max_diff_partial = 0.0f; + int argmax_partial = 0; + for (int i = 0; i < n_vocab; ++i) { + max_diff_partial = std::max(max_diff_partial, std::fabs(ref[i] - got_partial[i])); + if (got_partial[i] > got_partial[argmax_partial]) argmax_partial = i; + } + // today's partial checkpoint, for the same comparison (the size of the state it would copy) + const int64_t t_pser0 = now_us(); + std::vector pblob(llama_state_seq_get_size_ext(ctx, 0, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY)); + const size_t pwritten = llama_state_seq_get_data_ext(ctx, pblob.data(), pblob.size(), 0, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); + const int64_t t_pser = now_us() - t_pser0; + float max_diff = 0.0f; int argmax_ref = 0, argmax_got = 0; for (int i = 0; i < n_vocab; ++i) { @@ -117,12 +150,19 @@ int main(int argc, char ** argv) { std::printf("serialized checkpoint: %zu bytes in %lld us (host copy of the sequence)\n", written, (long long) t_ser); std::printf("parked checkpoint: 0 bytes moved, park %lld us, restore %lld us\n", (long long) t_park, (long long) t_rest); std::printf("restored vs cold logits: max |diff| = %.6g, argmax %d vs %d\n", max_diff, argmax_got, argmax_ref); + std::printf("partial (server form): serialized %zu bytes in %lld us; parked 0 bytes (attention cells held by the parked id: pos_max %d), park %lld us, restore %lld us\n", + pwritten, (long long) t_pser, (int) parked_kv_max, (long long) t_ppark, (long long) t_prest); + std::printf("partial restored vs cold logits: max |diff| = %.6g, argmax %d vs %d\n", max_diff_partial, argmax_partial, argmax_ref); llama_free(ctx); llama_model_free(model); llama_backend_free(); // the same backend, the same tokens, the same positions: the restored state must be the cold one + if (argmax_partial != argmax_ref || max_diff_partial > 1e-2f) { + std::fprintf(stderr, "FAILED: the partial (recurrent-only) restore does not reproduce the cold run\n"); + return 1; + } if (argmax_got != argmax_ref || max_diff > 1e-2f) { std::fprintf(stderr, "FAILED: the restored sequence does not reproduce the cold run\n"); return 1; From d65dc705ec1844bfef0d0aa8265cb4c5684e6dfb Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 08:11:50 -0600 Subject: [PATCH 3/8] tests: test-seq-park takes TEST_SEQ_PARK_N to measure checkpoint growth with context (target partial state is constant: 20,201,932 bytes at 300, 1,500 and 3,000 tokens on qwen35-0.8b) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo (cherry picked from commit 928194f1efe22c6b153e7985cd8effb8b9f49392) --- tests/test-seq-park.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/test-seq-park.cpp b/tests/test-seq-park.cpp index b9ea459043be..f3cf2bfa79e2 100644 --- a/tests/test-seq-park.cpp +++ b/tests/test-seq-park.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include static int64_t now_us() { @@ -22,8 +23,8 @@ static int64_t now_us() { static llama_context * make_ctx(const common_params & params, llama_model * model) { auto cparams = common_context_params_to_llama(params); cparams.n_seq_max = 2; // seq 0 live, seq 1 parked - cparams.n_ctx = 1024; - cparams.n_batch = 512; + cparams.n_ctx = 8192; + cparams.n_batch = 4096; cparams.n_ubatch = 512; cparams.kv_unified = true; // one stream: a parked id shares the live sequence's cells return llama_init_from_model(model, cparams); @@ -60,7 +61,9 @@ int main(int argc, char ** argv) { const int n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(model)); std::printf("model: recurrent=%d hybrid=%d\n", (int) llama_model_is_recurrent(model), (int) llama_model_is_hybrid(model)); - constexpr int N = 300, M = 120; // the prefix to keep; tokens the live sequence advances through + // the prefix to keep (TEST_SEQ_PARK_N overrides, to measure how a checkpoint grows with context) + const int N = std::getenv("TEST_SEQ_PARK_N") ? std::atoi(std::getenv("TEST_SEQ_PARK_N")) : 300; + constexpr int M = 120; // tokens the live sequence advances through std::vector prefix, detour; for (int i = 0; i < N; ++i) prefix.push_back((llama_token) (1000 + (i * 7919) % 20000)); for (int i = 0; i < M; ++i) detour.push_back((llama_token) (2000 + (i * 104729) % 20000)); From 18fc30091c9f5f87b00fd9b7446000ce1e5f4451 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 09:14:21 -0600 Subject: [PATCH 4/8] llama: device snapshots keyed by a caller snapshot id (llama_state_seq_snapshot_save/load/free), prototype for review CONTINUUM-ENGINE 4.7.11 revised design (proposed for Codex's review; not wired into the server). Parked sequence ids cost ~81 MB each on the 0.8B with MTP (every recurrent cell carries 1 + n_rs_seq rollback rows). The fork's LLAMA_STATE_SEQ_FLAGS_ON_DEVICE already copies a sequence's state tensors into device buffers with backend ops, but keys them by sequence id (mem_storage[seq_id]), so each snapshot replaced the last. llama_state_seq_snapshot_save/load/free key a snapshot by a caller id: the snapshot owns a small host header and its own device buffers; load copies them back; free releases them. A checkpoint becomes a device copy into memory named by handle, with no extra sequence ids and no rollback rows. Receipt, qwen35-0.8b (hybrid), this build, M5 Metal, a context with n_seq_max = 1, PARTIAL_ONLY: 20,201,472 device bytes per snapshot at both 300 and 3,000 tokens (one recurrent row, the same as the serialized partial state; no rollback planes); save 1.3-1.4 ms, restore 0.4-0.8 ms; the restored next-token logits equal a cold run's (argmax 82 = 82, max |diff| 0.0044-0.0045, batch shape). Save allocates a fresh device buffer per snapshot: recycling pool-owned buffers is the next measurement. Device buffers are wired (never compressed or swapped): the pool budgets them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo (cherry picked from commit 7ca9509f0fddacdfa6847c7fa9b790182f32def7) --- include/llama.h | 21 +++++++++++++ src/llama-context.cpp | 65 +++++++++++++++++++++++++++++++++++++++++ src/llama-context.h | 13 +++++++++ tests/test-seq-park.cpp | 42 ++++++++++++++++++++++++++ 4 files changed, 141 insertions(+) diff --git a/include/llama.h b/include/llama.h index 6ff7b047fd40..4f058a452dd2 100644 --- a/include/llama.h +++ b/include/llama.h @@ -1085,6 +1085,27 @@ extern "C" { llama_seq_id dest_seq_id, llama_state_seq_flags flags); + // Continuum fork (CONTINUUM-ENGINE 4.7.11): DEVICE SNAPSHOTS of a sequence's state, keyed by a caller + // snapshot id instead of the sequence id, so a sequence can hold many. Save copies the sequence's + // state tensors into device buffers owned by the snapshot with backend ops (no host bytes; the + // host keeps only a small header); load copies them back; free releases them. With + // LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY a hybrid model snapshots its recurrent row only. + LLAMA_API size_t llama_state_seq_snapshot_save( + struct llama_context * ctx, + llama_seq_id seq_id, + uint64_t snapshot_id, + llama_state_seq_flags flags); + + LLAMA_API bool llama_state_seq_snapshot_load( + struct llama_context * ctx, + llama_seq_id seq_id, + uint64_t snapshot_id, + llama_state_seq_flags flags); + + LLAMA_API void llama_state_seq_snapshot_free( + struct llama_context * ctx, + uint64_t snapshot_id); + // // Decoding // diff --git a/src/llama-context.cpp b/src/llama-context.cpp index c2d348884ce9..88c3507929df 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -3165,6 +3165,56 @@ size_t llama_context::state_seq_set_data(llama_seq_id seq_id, const uint8_t * sr } } +size_t llama_context::snapshot_save(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags) { + flags |= LLAMA_STATE_SEQ_FLAGS_ON_DEVICE; + auto & snap = snapshots[snapshot_id]; + snap.header.resize(state_seq_get_size(seq_id, flags)); + try { + { + llama_io_write_device io(snap.header.data(), snap.header.size(), snap.bufs); + io.write(&io_magic, sizeof(io_magic)); + io.write(&seq_id, sizeof(seq_id)); + state_seq_write_data(io, seq_id, flags); + } // the device copies are made as the writer completes + size_t device_bytes = 0; + for (const auto & [buft, mbuf] : snap.bufs) { + device_bytes += mbuf.total_size; + } + return device_bytes; + } catch (const std::exception & err) { + LLAMA_LOG_ERROR("%s: error saving snapshot: %s\n", __func__, err.what()); + snapshots.erase(snapshot_id); + return 0; + } +} + +bool llama_context::snapshot_load(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags) { + flags |= LLAMA_STATE_SEQ_FLAGS_ON_DEVICE; + auto it = snapshots.find(snapshot_id); + if (it == snapshots.end()) { + return false; + } + try { + llama_io_read_device io(it->second.header.data(), it->second.header.size(), it->second.bufs); + uint32_t magic_read; + io.read(&magic_read, sizeof(magic_read)); + if (io_magic != magic_read) { + throw std::runtime_error("wrong sequence state magic"); + } + llama_seq_id seq_id_read; + io.read(&seq_id_read, sizeof(seq_id_read)); + state_seq_read_data(io, seq_id, flags); + return true; + } catch (const std::exception & err) { + LLAMA_LOG_ERROR("%s: error loading snapshot: %s\n", __func__, err.what()); + return false; + } +} + +void llama_context::snapshot_free(uint64_t snapshot_id) { + snapshots.erase(snapshot_id); +} + bool llama_context::state_load_file(const char * filepath, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) { llama_file file(filepath, "rb"); @@ -4199,3 +4249,18 @@ llama_memory_breakdown llama_get_memory_breakdown(const struct llama_context * c llama_context * llama_get_ctx_other(struct llama_context * ctx) { return ctx->get_cparams().ctx_other; } + + +size_t llama_state_seq_snapshot_save(llama_context * ctx, llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags) { + ctx->synchronize(); + return ctx->snapshot_save(seq_id, snapshot_id, flags); +} + +bool llama_state_seq_snapshot_load(llama_context * ctx, llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags) { + ctx->synchronize(); + return ctx->snapshot_load(seq_id, snapshot_id, flags); +} + +void llama_state_seq_snapshot_free(llama_context * ctx, uint64_t snapshot_id) { + ctx->snapshot_free(snapshot_id); +} diff --git a/src/llama-context.h b/src/llama-context.h index 86bb220f765f..267fa64ee8f9 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -515,6 +515,19 @@ struct llama_context { // keep copies of the per-sequence memory on the device std::map mem_storage; + // Continuum fork: device snapshots keyed by a caller snapshot id (llama_state_seq_snapshot_*) + struct device_snapshot { + std::vector header; // the host-side part: magic, seq id, tensor layout + llama_memory_buffers bufs; // the state itself, in device buffers + }; + std::map snapshots; + +public: + size_t snapshot_save(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags); + bool snapshot_load(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags); + void snapshot_free(uint64_t snapshot_id); +private: + bool has_evaluated_once = false; // env: LLAMA_GRAPH_REUSE_DISABLE diff --git a/tests/test-seq-park.cpp b/tests/test-seq-park.cpp index f3cf2bfa79e2..a6700c4bad8d 100644 --- a/tests/test-seq-park.cpp +++ b/tests/test-seq-park.cpp @@ -158,6 +158,48 @@ int main(int argc, char ** argv) { std::printf("partial restored vs cold logits: max |diff| = %.6g, argmax %d vs %d\n", max_diff_partial, argmax_partial, argmax_ref); llama_free(ctx); + + // ---- the revised design: the target's partial state as a DEVICE SNAPSHOT keyed by snapshot id, on a + // context with ONE sequence (no parked ids, no extra rollback rows) + float max_diff_snap = 0.0f; + int argmax_snap = 0; + { + auto cparams = common_context_params_to_llama(params); + cparams.n_seq_max = 1; + cparams.n_ctx = 8192; + cparams.n_batch = 4096; + cparams.n_ubatch = 512; + llama_context * sctx = llama_init_from_model(model, cparams); + llama_memory_t smem = llama_get_memory(sctx); + if (!decode(sctx, prefix, 0, 0)) { std::fprintf(stderr, "FAILED: snapshot prefix decode\n"); return 1; } + llama_synchronize(sctx); + const int64_t t_s0 = now_us(); + const size_t snap_bytes = llama_state_seq_snapshot_save(sctx, 0, /*snapshot_id=*/42, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); + const int64_t t_save = now_us() - t_s0; + if (snap_bytes == 0) { std::fprintf(stderr, "FAILED: snapshot save\n"); return 1; } + if (!decode(sctx, detour, N, 0)) { std::fprintf(stderr, "FAILED: snapshot detour\n"); return 1; } + llama_synchronize(sctx); + const int64_t t_l0 = now_us(); + if (!llama_state_seq_snapshot_load(sctx, 0, 42, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY)) { std::fprintf(stderr, "FAILED: snapshot load\n"); return 1; } + if (!llama_memory_seq_rm(smem, 0, N, -1)) { std::fprintf(stderr, "FAILED: trim after snapshot load\n"); return 1; } + llama_synchronize(sctx); + const int64_t t_load = now_us() - t_l0; + if (!decode(sctx, { next }, N, 0)) { std::fprintf(stderr, "FAILED: snapshot restored decode\n"); return 1; } + const std::vector got_snap = last_logits(sctx, n_vocab); + for (int i = 0; i < n_vocab; ++i) { + max_diff_snap = std::max(max_diff_snap, std::fabs(ref[i] - got_snap[i])); + if (got_snap[i] > got_snap[argmax_snap]) argmax_snap = i; + } + std::printf("device snapshot (n_seq_max 1): %zu device bytes, save %lld us, restore %lld us; logits max |diff| %.6g, argmax %d vs %d\n", + snap_bytes, (long long) t_save, (long long) t_load, max_diff_snap, argmax_snap, argmax_ref); + llama_state_seq_snapshot_free(sctx, 42); + llama_free(sctx); + } + if (argmax_snap != argmax_ref || max_diff_snap > 1e-2f) { + std::fprintf(stderr, "FAILED: the device snapshot restore does not reproduce the cold run\n"); + return 1; + } + llama_model_free(model); llama_backend_free(); From 25b0993e61f6595e4e8addbab27db134dde74360 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 09:20:32 -0600 Subject: [PATCH 5/8] llama: device snapshots are transactional, validated and typed; device IO commits explicitly (Codex's review of 7ca9509f0) 1. Transactional save: the state is staged into separate snapshot storage, copied, and only then published under the id; a failed save (typed ALLOC_FAILED) leaves the previous snapshot loadable. During a replacement both generations exist; llama_state_seq_snapshot_bytes quotes the device bytes BEFORE anything allocates so the pool reserves exactly that (quote == held, asserted). 2. Provenance and validation before mutation: a snapshot stores its flags and its tensor layout (which tensors, how many bytes each; offsets excluded, a recurrent sequence may change cells). A load first runs a metadata-only write pass over the target and refuses (INCOMPATIBLE) on a flags or layout mismatch BEFORE state_seq_read_data touches cell metadata. The reader no longer aborts on a mismatch (it checks every buffer type, counts, totals and per-tensor sizes before any copy). Typed llama_snapshot_status (OK, ABSENT, INCOMPATIBLE, ALLOC_FAILED, COPY_FAILED); no exception crosses the C API. 3. Device IO commits explicitly: llama_io_write_device / llama_io_read_device gain commit() (typed, never throws or aborts) and discard(); every snapshot path discards on an exception, so nothing is allocated, copied, or half-read in a destructor. Upstream's own ON_DEVICE path is unchanged (its destructors still commit and abort on failure). Save, load and free synchronize first, so no submitted step reads or writes buffers being replaced or freed. Native fault replays (test-seq-park, qwen35-0.8b hybrid, n_seq_max 1, PARTIAL_ONLY, M5, at 300 and 3,000 tokens): a failed replacement (injected allocation failure) keeps the prior snapshot, which then restores the cold-run logits; an incompatible-flags load and an unknown id are refused with the live state byte-identical (serialized witness); save and free with decode work still in flight; 200 save/free cycles of 4 snapshots return the process footprint to base exactly (433.0 -> peak 490.9 -> 433.0 MiB; 474.2 -> 532.1 -> 474.2), the peak being the staged-replacement overlap. Per snapshot: 20,201,472 device bytes (one recurrent row), save 1.4-1.5 ms, restore 0.4-0.8 ms, restored logits equal a cold run (argmax equal, max |diff| 0.0044). 0 build warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo (cherry picked from commit be11e4448cff0d86b8d20b115123b500fcb6c1b8) --- include/llama.h | 45 +++++--- src/llama-context.cpp | 223 ++++++++++++++++++++++++++++++++-------- src/llama-context.h | 13 ++- tests/test-seq-park.cpp | 104 ++++++++++++++----- 4 files changed, 297 insertions(+), 88 deletions(-) diff --git a/include/llama.h b/include/llama.h index 4f058a452dd2..02619e8f4e40 100644 --- a/include/llama.h +++ b/include/llama.h @@ -1086,25 +1086,36 @@ extern "C" { llama_state_seq_flags flags); // Continuum fork (CONTINUUM-ENGINE 4.7.11): DEVICE SNAPSHOTS of a sequence's state, keyed by a caller - // snapshot id instead of the sequence id, so a sequence can hold many. Save copies the sequence's - // state tensors into device buffers owned by the snapshot with backend ops (no host bytes; the - // host keeps only a small header); load copies them back; free releases them. With - // LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY a hybrid model snapshots its recurrent row only. - LLAMA_API size_t llama_state_seq_snapshot_save( - struct llama_context * ctx, - llama_seq_id seq_id, - uint64_t snapshot_id, - llama_state_seq_flags flags); + // snapshot id (the pool's identity), so a sequence can hold many. Save copies the sequence's state + // tensors into device buffers owned by the snapshot (no host bytes; the host keeps a small header); + // load copies them back; free releases them. With LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY a hybrid model + // snapshots its recurrent row only. Every call returns a typed status and never throws or aborts. + enum llama_snapshot_status { + LLAMA_SNAPSHOT_OK = 0, + LLAMA_SNAPSHOT_ABSENT = 1, // no snapshot under this id / nothing to snapshot under these flags + LLAMA_SNAPSHOT_INCOMPATIBLE = 2, // flags or tensor layout differ from the target: nothing was changed + LLAMA_SNAPSHOT_ALLOC_FAILED = 3, // device memory could not be allocated: a previous snapshot is kept + LLAMA_SNAPSHOT_COPY_FAILED = 4, // the copy itself failed + }; - LLAMA_API bool llama_state_seq_snapshot_load( - struct llama_context * ctx, - llama_seq_id seq_id, - uint64_t snapshot_id, - llama_state_seq_flags flags); + // The device bytes a snapshot of `seq_id` would hold, so the pool reserves BEFORE anything allocates. + LLAMA_API enum llama_snapshot_status llama_state_seq_snapshot_bytes( + struct llama_context * ctx, llama_seq_id seq_id, llama_state_seq_flags flags, size_t * device_bytes); - LLAMA_API void llama_state_seq_snapshot_free( - struct llama_context * ctx, - uint64_t snapshot_id); + // Stage, copy, then publish: a failed save leaves any previous snapshot under this id loadable. While + // a replacement is staged both generations exist (the pool charges both). + LLAMA_API enum llama_snapshot_status llama_state_seq_snapshot_save( + struct llama_context * ctx, llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags, size_t * device_bytes); + + // Validated before the live sequence is touched: refused (INCOMPATIBLE) on a flags or layout mismatch. + LLAMA_API enum llama_snapshot_status llama_state_seq_snapshot_load( + struct llama_context * ctx, llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags); + + // Synchronizes first: no submitted step can still read the buffers being freed. + LLAMA_API enum llama_snapshot_status llama_state_seq_snapshot_free(struct llama_context * ctx, uint64_t snapshot_id); + + // Test-only fault injection: the next `n` snapshot device allocations fail. + LLAMA_API void llama_state_seq_snapshot_test_fail_next_allocs(int n); // // Decoding diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 88c3507929df..0868fa4e3dd3 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -2846,7 +2846,40 @@ class llama_io_write_device : public llama_io_write_i { llama_io_write_device(uint8_t * p, size_t len, llama_memory_buffers & mbufs) : ptr(p), buf_size(len), mbufs(mbufs) { } + // upstream ON_DEVICE path: commit on destruction, abort if it cannot (unchanged behavior) ~llama_io_write_device() { + if (!done && commit() != commit_status::ok) { + GGML_ABORT("%s: device state write failed\n", __func__); + } + } + + enum class commit_status { ok, alloc_failed }; + + // Continuum fork: the tensors this write would copy, by identity and size (offsets are not part of + // compatibility: a recurrent sequence may occupy a different cell at load) + std::vector> layout() const { + std::vector> out; + out.reserve(winfos.size()); + for (const auto & w : winfos) { + out.emplace_back(w.tensor, w.size); + } + return out; + } + + size_t payload_bytes() const { + size_t n = 0; + for (const auto & w : winfos) { + n += w.size; + } + return n; + } + + // a dry pass: nothing is allocated or copied + void discard() { done = true; } + + // allocate (or reuse) the device buffers and copy the recorded tensors; never throws + commit_status commit() { + done = true; llama_memory_buffers mbufs_new; for (const auto & winfo : winfos) { @@ -2910,7 +2943,10 @@ class llama_io_write_device : public llama_io_write_i { if (!mbuf_cur.buf || mbuf_cur.total_size != mbuf.total_size) { mbuf_cur = std::move(mbuf); - mbuf_cur.buf.reset(ggml_backend_alloc_ctx_tensors_from_buft(mbuf_cur.ctx.get(), buft)); + mbuf_cur.buf.reset(test_fail_alloc() ? nullptr : ggml_backend_alloc_ctx_tensors_from_buft(mbuf_cur.ctx.get(), buft)); + if (!mbuf_cur.buf) { + return commit_status::alloc_failed; + } LLAMA_LOG_INFO("%s: allocated '%s' buffer %.3f MiB\n", __func__, ggml_backend_buft_name(buft), mbuf.total_size/1024.0/1024.0); } else { @@ -2936,6 +2972,19 @@ class llama_io_write_device : public llama_io_write_i { ggml_backend_tensor_copy(mbuf_cur.org[i], mbuf_cur.cpy[i]); } } + return commit_status::ok; + } + + // test-only fault: the next N device allocations of snapshot writes fail + static std::atomic & fail_allocs() { static std::atomic n{0}; return n; } + static bool test_fail_alloc() { + int n = fail_allocs().load(); + while (n > 0) { + if (fail_allocs().compare_exchange_weak(n, n - 1)) { + return true; + } + } + return false; } void write(const void * src, size_t size) override { @@ -2971,6 +3020,7 @@ class llama_io_write_device : public llama_io_write_i { std::vector winfos; llama_memory_buffers & mbufs; + bool done = false; }; class llama_io_read_device : public llama_io_read_i { @@ -2978,7 +3028,20 @@ class llama_io_read_device : public llama_io_read_i { llama_io_read_device(const uint8_t * p, size_t len, const llama_memory_buffers & mbufs) : ptr(p), buf_size(len), mbufs(mbufs) { } + // upstream ON_DEVICE path: commit on destruction, abort on a mismatch (unchanged behavior) ~llama_io_read_device() { + if (!done && !commit()) { + GGML_ABORT("%s: memory buffer mismatch\n", __func__); + } + } + + // an aborted read: nothing is copied + void discard() { done = true; } + + // copy the stored tensors into the recorded destinations; false on any layout mismatch (checked for + // every buffer type BEFORE any copy), never throws or aborts + bool commit() { + done = true; llama_memory_buffers mbufs_new; for (const auto & rinfo : rinfos) { @@ -3013,18 +3076,30 @@ class llama_io_read_device : public llama_io_read_i { } for (auto & [buft, mbuf] : mbufs_new) { - const auto & mbuf_cur = mbufs.at(buft); - - if (!mbuf_cur.buf || mbuf_cur.n_tensors != mbuf.n_tensors || mbuf_cur.total_size != mbuf.total_size) { - GGML_ABORT("%s: memory buffer mismatch\n", __func__); + const auto it = mbufs.find(buft); + if (it == mbufs.end()) { + return false; } + const auto & mbuf_cur = it->second; + if (!mbuf_cur.buf || mbuf_cur.n_tensors != mbuf.n_tensors || mbuf_cur.total_size != mbuf.total_size || + mbuf_cur.cpy.size() != mbuf.org.size()) { + return false; + } + for (size_t i = 0; i < mbuf.org.size(); ++i) { + if (ggml_nbytes(mbuf_cur.cpy[i]) != ggml_nbytes(mbuf.org[i])) { + return false; + } + } + } + for (auto & [buft, mbuf] : mbufs_new) { + const auto & mbuf_cur = mbufs.at(buft); for (size_t i = 0; i < mbuf_cur.org.size(); ++i) { ggml_backend_tensor_copy(mbuf_cur.cpy[i], mbuf.org[i]); } } - GGML_ASSERT(buf_size == 0); + return buf_size == 0; } void read(void * dst, size_t size) override { @@ -3060,6 +3135,7 @@ class llama_io_read_device : public llama_io_read_i { std::vector rinfos; const llama_memory_buffers & mbufs; + bool done = false; }; size_t llama_context::state_get_size() { @@ -3165,54 +3241,94 @@ size_t llama_context::state_seq_set_data(llama_seq_id seq_id, const uint8_t * sr } } -size_t llama_context::snapshot_save(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags) { +// Continuum fork: device snapshots, transactional and typed (Codex's review of 7ca9509f0). +llama_snapshot_status llama_context::snapshot_bytes(llama_seq_id seq_id, llama_state_seq_flags flags, size_t * device_bytes) { flags |= LLAMA_STATE_SEQ_FLAGS_ON_DEVICE; - auto & snap = snapshots[snapshot_id]; - snap.header.resize(state_seq_get_size(seq_id, flags)); + std::vector header(state_seq_get_size(seq_id, flags)); + llama_memory_buffers none; + llama_io_write_device dry(header.data(), header.size(), none); + dry.discard(); // metadata only: nothing is ever allocated or copied by this pass + dry.write(&io_magic, sizeof(io_magic)); + dry.write(&seq_id, sizeof(seq_id)); + state_seq_write_data(dry, seq_id, flags); + *device_bytes = dry.payload_bytes(); + return *device_bytes > 0 ? LLAMA_SNAPSHOT_OK : LLAMA_SNAPSHOT_ABSENT; +} + +llama_snapshot_status llama_context::snapshot_save(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags, size_t * device_bytes) { + flags |= LLAMA_STATE_SEQ_FLAGS_ON_DEVICE; + // stage into separate storage; the published snapshot (if any) is untouched until this one is complete + device_snapshot staged; + staged.flags = flags; + staged.header.resize(state_seq_get_size(seq_id, flags)); + llama_io_write_device io(staged.header.data(), staged.header.size(), staged.bufs); try { - { - llama_io_write_device io(snap.header.data(), snap.header.size(), snap.bufs); - io.write(&io_magic, sizeof(io_magic)); - io.write(&seq_id, sizeof(seq_id)); - state_seq_write_data(io, seq_id, flags); - } // the device copies are made as the writer completes - size_t device_bytes = 0; - for (const auto & [buft, mbuf] : snap.bufs) { - device_bytes += mbuf.total_size; - } - return device_bytes; - } catch (const std::exception & err) { - LLAMA_LOG_ERROR("%s: error saving snapshot: %s\n", __func__, err.what()); - snapshots.erase(snapshot_id); - return 0; + io.write(&io_magic, sizeof(io_magic)); + io.write(&seq_id, sizeof(seq_id)); + state_seq_write_data(io, seq_id, flags); + } catch (...) { + io.discard(); // a failed write pass allocates and copies nothing + throw; } + staged.layout = io.layout(); + const size_t payload = io.payload_bytes(); + if (payload == 0) { + io.discard(); + return LLAMA_SNAPSHOT_ABSENT; // nothing to snapshot under these flags + } + if (io.commit() != llama_io_write_device::commit_status::ok) { + return LLAMA_SNAPSHOT_ALLOC_FAILED; // the previous snapshot under this id stays loadable + } + snapshots[snapshot_id] = std::move(staged); // publish; a replaced generation is freed here, after the copy + *device_bytes = payload; + return LLAMA_SNAPSHOT_OK; } -bool llama_context::snapshot_load(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags) { +llama_snapshot_status llama_context::snapshot_load(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags) { flags |= LLAMA_STATE_SEQ_FLAGS_ON_DEVICE; auto it = snapshots.find(snapshot_id); if (it == snapshots.end()) { - return false; + return LLAMA_SNAPSHOT_ABSENT; + } + const device_snapshot & snap = it->second; + if (snap.flags != flags) { + return LLAMA_SNAPSHOT_INCOMPATIBLE; } + // validate BEFORE the live sequence is touched: the target's own layout under these flags (a dry, + // metadata-only write pass) must match the snapshot's, tensor by tensor + { + std::vector header(state_seq_get_size(seq_id, flags)); + llama_memory_buffers none; + llama_io_write_device dry(header.data(), header.size(), none); + dry.discard(); // metadata only + dry.write(&io_magic, sizeof(io_magic)); + dry.write(&seq_id, sizeof(seq_id)); + state_seq_write_data(dry, seq_id, flags); + const bool same = dry.layout() == snap.layout; + if (!same) { + return LLAMA_SNAPSHOT_INCOMPATIBLE; + } + } + llama_io_read_device io(snap.header.data(), snap.header.size(), snap.bufs); try { - llama_io_read_device io(it->second.header.data(), it->second.header.size(), it->second.bufs); uint32_t magic_read; io.read(&magic_read, sizeof(magic_read)); - if (io_magic != magic_read) { - throw std::runtime_error("wrong sequence state magic"); - } llama_seq_id seq_id_read; io.read(&seq_id_read, sizeof(seq_id_read)); + if (magic_read != io_magic) { + io.discard(); + return LLAMA_SNAPSHOT_INCOMPATIBLE; + } state_seq_read_data(io, seq_id, flags); - return true; - } catch (const std::exception & err) { - LLAMA_LOG_ERROR("%s: error loading snapshot: %s\n", __func__, err.what()); - return false; + } catch (...) { + io.discard(); // never copy into a half-read state + throw; } + return io.commit() ? LLAMA_SNAPSHOT_OK : LLAMA_SNAPSHOT_COPY_FAILED; } -void llama_context::snapshot_free(uint64_t snapshot_id) { - snapshots.erase(snapshot_id); +llama_snapshot_status llama_context::snapshot_free(uint64_t snapshot_id) { + return snapshots.erase(snapshot_id) > 0 ? LLAMA_SNAPSHOT_OK : LLAMA_SNAPSHOT_ABSENT; } bool llama_context::state_load_file(const char * filepath, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) { @@ -4251,16 +4367,37 @@ llama_context * llama_get_ctx_other(struct llama_context * ctx) { } -size_t llama_state_seq_snapshot_save(llama_context * ctx, llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags) { - ctx->synchronize(); - return ctx->snapshot_save(seq_id, snapshot_id, flags); +template +static llama_snapshot_status llama_snapshot_guard(F && f) { + try { + return f(); + } catch (const std::exception & err) { + LLAMA_LOG_ERROR("%s: %s\n", __func__, err.what()); + return LLAMA_SNAPSHOT_COPY_FAILED; + } +} + +llama_snapshot_status llama_state_seq_snapshot_bytes(llama_context * ctx, llama_seq_id seq_id, llama_state_seq_flags flags, size_t * device_bytes) { + *device_bytes = 0; + return llama_snapshot_guard([&] { return ctx->snapshot_bytes(seq_id, flags, device_bytes); }); } -bool llama_state_seq_snapshot_load(llama_context * ctx, llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags) { +llama_snapshot_status llama_state_seq_snapshot_save(llama_context * ctx, llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags, size_t * device_bytes) { + *device_bytes = 0; + ctx->synchronize(); // the state read is the state after every submitted step + return llama_snapshot_guard([&] { return ctx->snapshot_save(seq_id, snapshot_id, flags, device_bytes); }); +} + +llama_snapshot_status llama_state_seq_snapshot_load(llama_context * ctx, llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags) { ctx->synchronize(); - return ctx->snapshot_load(seq_id, snapshot_id, flags); + return llama_snapshot_guard([&] { return ctx->snapshot_load(seq_id, snapshot_id, flags); }); +} + +llama_snapshot_status llama_state_seq_snapshot_free(llama_context * ctx, uint64_t snapshot_id) { + ctx->synchronize(); // no submitted step may still read buffers about to be freed + return llama_snapshot_guard([&] { return ctx->snapshot_free(snapshot_id); }); } -void llama_state_seq_snapshot_free(llama_context * ctx, uint64_t snapshot_id) { - ctx->snapshot_free(snapshot_id); +void llama_state_seq_snapshot_test_fail_next_allocs(int n) { + llama_io_write_device::fail_allocs().store(n); } diff --git a/src/llama-context.h b/src/llama-context.h index 267fa64ee8f9..7d09698b0da7 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -517,15 +517,18 @@ struct llama_context { // Continuum fork: device snapshots keyed by a caller snapshot id (llama_state_seq_snapshot_*) struct device_snapshot { - std::vector header; // the host-side part: magic, seq id, tensor layout - llama_memory_buffers bufs; // the state itself, in device buffers + std::vector header; // the host-side part: magic, seq id, tensor layout + llama_memory_buffers bufs; // the state itself, in device buffers + llama_state_seq_flags flags = 0; + std::vector> layout; // provenance: which tensors, how many bytes }; std::map snapshots; public: - size_t snapshot_save(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags); - bool snapshot_load(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags); - void snapshot_free(uint64_t snapshot_id); + llama_snapshot_status snapshot_bytes(llama_seq_id seq_id, llama_state_seq_flags flags, size_t * device_bytes); + llama_snapshot_status snapshot_save(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags, size_t * device_bytes); + llama_snapshot_status snapshot_load(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags); + llama_snapshot_status snapshot_free(uint64_t snapshot_id); private: bool has_evaluated_once = false; diff --git a/tests/test-seq-park.cpp b/tests/test-seq-park.cpp index a6700c4bad8d..5c9c0a7ac668 100644 --- a/tests/test-seq-park.cpp +++ b/tests/test-seq-park.cpp @@ -13,6 +13,9 @@ #include #include #include +#if defined(__APPLE__) +#include +#endif #include #include @@ -160,9 +163,8 @@ int main(int argc, char ** argv) { llama_free(ctx); // ---- the revised design: the target's partial state as a DEVICE SNAPSHOT keyed by snapshot id, on a - // context with ONE sequence (no parked ids, no extra rollback rows) - float max_diff_snap = 0.0f; - int argmax_snap = 0; + // context with ONE sequence (no parked ids, no extra rollback rows), plus the fault replays from + // Codex's review of 7ca9509f0 { auto cparams = common_context_params_to_llama(params); cparams.n_seq_max = 1; @@ -171,34 +173,90 @@ int main(int argc, char ** argv) { cparams.n_ubatch = 512; llama_context * sctx = llama_init_from_model(model, cparams); llama_memory_t smem = llama_get_memory(sctx); - if (!decode(sctx, prefix, 0, 0)) { std::fprintf(stderr, "FAILED: snapshot prefix decode\n"); return 1; } - llama_synchronize(sctx); + const auto P = LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY; + auto require = [](bool ok, const char * what) { if (!ok) { std::fprintf(stderr, "FAILED: %s\n", what); std::exit(1); } }; + auto restored_matches_cold = [&](uint64_t id, const char * what) { + require(llama_state_seq_snapshot_load(sctx, 0, id, P) == LLAMA_SNAPSHOT_OK, what); + require(llama_memory_seq_rm(smem, 0, N, -1), "trim attention after the restore"); + require(decode(sctx, { next }, N, 0), "decode after the restore"); + const std::vector got = last_logits(sctx, n_vocab); + float d = 0.0f; int am = 0; + for (int i = 0; i < n_vocab; ++i) { d = std::max(d, std::fabs(ref[i] - got[i])); if (got[i] > got[am]) am = i; } + require(am == argmax_ref && d <= 1e-2f, what); + // back to the clean prefix for the next case: the recurrent state cannot be trimmed past `next`, + // so restore the snapshot again (the mechanism under test) and trim attention + require(llama_state_seq_snapshot_load(sctx, 0, id, P) == LLAMA_SNAPSHOT_OK, "re-restore to the prefix"); + require(llama_memory_seq_rm(smem, 0, N, -1), "trim back to the prefix"); + return d; + }; + auto host_state = [&]() { // test-only witness of the live state: its serialized bytes + std::vector v(llama_state_seq_get_size_ext(sctx, 0, P)); + llama_state_seq_get_data_ext(sctx, v.data(), v.size(), 0, P); + return v; + }; + + require(decode(sctx, prefix, 0, 0), "snapshot prefix decode"); + llama_synchronize(sctx); // time the snapshot, not the prefill still in flight + size_t quoted = 0, bytes = 0; + require(llama_state_seq_snapshot_bytes(sctx, 0, P, "ed) == LLAMA_SNAPSHOT_OK && quoted > 0, "size quote before save"); const int64_t t_s0 = now_us(); - const size_t snap_bytes = llama_state_seq_snapshot_save(sctx, 0, /*snapshot_id=*/42, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); + require(llama_state_seq_snapshot_save(sctx, 0, 42, P, &bytes) == LLAMA_SNAPSHOT_OK, "save"); const int64_t t_save = now_us() - t_s0; - if (snap_bytes == 0) { std::fprintf(stderr, "FAILED: snapshot save\n"); return 1; } - if (!decode(sctx, detour, N, 0)) { std::fprintf(stderr, "FAILED: snapshot detour\n"); return 1; } + require(bytes == quoted, "the quote equals what the save holds (the pool reserves exactly this)"); + + // 1. a failed REPLACEMENT keeps the prior snapshot loadable + require(decode(sctx, detour, N, 0), "detour"); + llama_state_seq_snapshot_test_fail_next_allocs(1); + size_t b2 = 0; + require(llama_state_seq_snapshot_save(sctx, 0, 42, P, &b2) == LLAMA_SNAPSHOT_ALLOC_FAILED, "a failed allocation is reported typed"); + // 2. an incompatible load is refused BEFORE the live sequence changes + const auto before = host_state(); + require(llama_state_seq_snapshot_load(sctx, 0, 42, LLAMA_STATE_SEQ_FLAGS_NONE) == LLAMA_SNAPSHOT_INCOMPATIBLE, "flags mismatch refused"); + require(llama_state_seq_snapshot_load(sctx, 0, 999, P) == LLAMA_SNAPSHOT_ABSENT, "an unknown id is absent"); + require(host_state() == before, "a refused load leaves the live sequence byte-identical"); llama_synchronize(sctx); const int64_t t_l0 = now_us(); - if (!llama_state_seq_snapshot_load(sctx, 0, 42, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY)) { std::fprintf(stderr, "FAILED: snapshot load\n"); return 1; } - if (!llama_memory_seq_rm(smem, 0, N, -1)) { std::fprintf(stderr, "FAILED: trim after snapshot load\n"); return 1; } - llama_synchronize(sctx); - const int64_t t_load = now_us() - t_l0; - if (!decode(sctx, { next }, N, 0)) { std::fprintf(stderr, "FAILED: snapshot restored decode\n"); return 1; } - const std::vector got_snap = last_logits(sctx, n_vocab); - for (int i = 0; i < n_vocab; ++i) { - max_diff_snap = std::max(max_diff_snap, std::fabs(ref[i] - got_snap[i])); - if (got_snap[i] > got_snap[argmax_snap]) argmax_snap = i; + require(llama_state_seq_snapshot_load(sctx, 0, 42, P) == LLAMA_SNAPSHOT_OK, "timed restore"); + const int64_t t_load = now_us() - t_l0; // the restore alone (it synchronizes on entry; nothing is in flight) + const float d1 = restored_matches_cold(42, "the prior snapshot survived the failed replacement"); + + // 3. save / free with backend work still in flight (no explicit synchronize by the caller) + require(decode(sctx, detour, N, 0), "detour 2"); // submitted, not synchronized + size_t b3 = 0; + require(llama_state_seq_snapshot_save(sctx, 0, 70, P, &b3) == LLAMA_SNAPSHOT_OK, "save with work in flight"); + require(decode(sctx, { next }, N + M, 0), "more work in flight"); + require(llama_state_seq_snapshot_free(sctx, 70) == LLAMA_SNAPSHOT_OK, "free with work in flight"); + require(llama_state_seq_snapshot_free(sctx, 70) == LLAMA_SNAPSHOT_ABSENT, "a second free is absent, typed"); + + // 4. allocate / recycle cycles: physical footprint must not grow + auto footprint = []() -> int64_t { +#if defined(__APPLE__) + task_vm_info_data_t info; mach_msg_type_number_t n = TASK_VM_INFO_COUNT; + return task_info(mach_task_self(), TASK_VM_INFO, (task_info_t) &info, &n) == KERN_SUCCESS ? (int64_t) info.phys_footprint : -1; +#else + return -1; +#endif + }; + int64_t peak = 0; + const int64_t base = footprint(); + for (int cycle = 0; cycle < 200; ++cycle) { + size_t b4 = 0; + require(llama_state_seq_snapshot_save(sctx, 0, 100 + (uint64_t) (cycle % 4), P, &b4) == LLAMA_SNAPSHOT_OK, "cycle save"); + if (cycle % 4 == 3) { + for (uint64_t id = 100; id < 104; ++id) llama_state_seq_snapshot_free(sctx, id); + } + peak = std::max(peak, footprint()); } - std::printf("device snapshot (n_seq_max 1): %zu device bytes, save %lld us, restore %lld us; logits max |diff| %.6g, argmax %d vs %d\n", - snap_bytes, (long long) t_save, (long long) t_load, max_diff_snap, argmax_snap, argmax_ref); + const int64_t after = footprint(); + std::printf("device snapshot (n_seq_max 1): %zu device bytes (quoted %zu), save %lld us, restore %lld us, logits max |diff| %.6g\n", + bytes, quoted, (long long) t_save, (long long) t_load, d1); + std::printf("fault replays ok: failed replacement kept the prior, incompatible/absent refused with the live state byte-identical, save/free with work in flight\n"); + std::printf("200 save/free cycles of 4 snapshots: footprint base %.1f MiB, peak %.1f MiB, after %.1f MiB\n", + base / 1048576.0, peak / 1048576.0, after / 1048576.0); + require(after - base < (int64_t) bytes, "no growth across cycles beyond one snapshot of slack"); llama_state_seq_snapshot_free(sctx, 42); llama_free(sctx); } - if (argmax_snap != argmax_ref || max_diff_snap > 1e-2f) { - std::fprintf(stderr, "FAILED: the device snapshot restore does not reproduce the cold run\n"); - return 1; - } llama_model_free(model); llama_backend_free(); From a5e922cfb2da7ef66a4129e98434d26a49877a8d Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 09:27:46 -0600 Subject: [PATCH 6/8] llama: snapshot paths never commit from a destructor; a post-read failure quarantines the target; physical byte quotes (Codex's re-review of be11e4448) 1. The device writer and reader take auto_commit; every snapshot path constructs them with false, so nothing is allocated or copied by a destructor whatever unwinds (be11's save called io.layout(), which allocates, outside the try while the writer would still commit on unwinding). Upstream's own ON_DEVICE path keeps auto_commit and its abort, unchanged. 2. state_seq_read_data mutates cell metadata before the copy commits: any failure after the read begins QUARANTINES the target (seq_rm over its whole range) and returns COPY_FAILED, so a caller sees a cold sequence, never a half-restored one; the snapshot itself stays intact and restores it. An empty target (fresh or quarantined) restores from the header; a non-empty one is still validated by a metadata-only dry pass before anything is touched. 3. Quotes and holdings are PHYSICAL: llama_state_seq_snapshot_bytes = host header + every tensor padded to its buffer type's alignment + ggml metadata contexts; save reports the buffers' actual sizes + metadata + header; the test requires quote == held. Native fault replays (qwen35-0.8b hybrid, n_seq_max 1, PARTIAL_ONLY, M5, at 300 and 3,000 tokens): quote == held == 20,228,428 bytes; failed replacement keeps the prior; incompatible/absent refused with the live state byte-identical; injected post-read commit failure -> COPY_FAILED, target emptied (seq_pos_max -1), intact snapshot restores it; save/free with work in flight; 200 save/free cycles of 4 return the footprint to base exactly (433.1 -> 491.0 -> 433.1 MiB; 472.6 -> 530.5 -> 472.6). Save 1.3-1.4 ms, restore 0.35-0.40 ms; restored logits equal a cold run. 0 build warnings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo (cherry picked from commit 16a02cca69ad70a24c92845d5e09c9a66d7b07d6) --- include/llama.h | 10 ++- src/llama-context.cpp | 136 +++++++++++++++++++++++++++------------- tests/test-seq-park.cpp | 15 ++++- 3 files changed, 114 insertions(+), 47 deletions(-) diff --git a/include/llama.h b/include/llama.h index 02619e8f4e40..751b8ccb0d55 100644 --- a/include/llama.h +++ b/include/llama.h @@ -1098,7 +1098,8 @@ extern "C" { LLAMA_SNAPSHOT_COPY_FAILED = 4, // the copy itself failed }; - // The device bytes a snapshot of `seq_id` would hold, so the pool reserves BEFORE anything allocates. + // The bytes a snapshot of `seq_id` would hold PHYSICALLY (device buffers at their alignment, ggml + // metadata, host header), so the pool reserves BEFORE anything allocates; save reports the same. LLAMA_API enum llama_snapshot_status llama_state_seq_snapshot_bytes( struct llama_context * ctx, llama_seq_id seq_id, llama_state_seq_flags flags, size_t * device_bytes); @@ -1107,15 +1108,18 @@ extern "C" { LLAMA_API enum llama_snapshot_status llama_state_seq_snapshot_save( struct llama_context * ctx, llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags, size_t * device_bytes); - // Validated before the live sequence is touched: refused (INCOMPATIBLE) on a flags or layout mismatch. + // Validated before the live sequence is touched: refused (INCOMPATIBLE) on a flags or layout mismatch. A + // failure after the read began quarantines the target (cleared whole) and returns COPY_FAILED. LLAMA_API enum llama_snapshot_status llama_state_seq_snapshot_load( struct llama_context * ctx, llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags); // Synchronizes first: no submitted step can still read the buffers being freed. LLAMA_API enum llama_snapshot_status llama_state_seq_snapshot_free(struct llama_context * ctx, uint64_t snapshot_id); - // Test-only fault injection: the next `n` snapshot device allocations fail. + // Test-only fault injection: the next `n` snapshot device allocations fail; the next `n` load commits + // fail after the read (the target is then quarantined: cleared whole, COPY_FAILED). LLAMA_API void llama_state_seq_snapshot_test_fail_next_allocs(int n); + LLAMA_API void llama_state_seq_snapshot_test_fail_next_load_commits(int n); // // Decoding diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 0868fa4e3dd3..f0a3cf1b8289 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -2843,10 +2843,12 @@ class llama_io_read_file : public llama_io_read_i { class llama_io_write_device : public llama_io_write_i { public: - llama_io_write_device(uint8_t * p, size_t len, llama_memory_buffers & mbufs) : ptr(p), buf_size(len), mbufs(mbufs) { + // `auto_commit`: upstream's ON_DEVICE path commits on destruction (and aborts if it cannot), unchanged. + // Snapshot paths pass false: nothing is ever allocated or copied by a destructor, whatever unwinds. + llama_io_write_device(uint8_t * p, size_t len, llama_memory_buffers & mbufs, bool auto_commit = true) + : ptr(p), buf_size(len), mbufs(mbufs), done(!auto_commit) { } - // upstream ON_DEVICE path: commit on destruction, abort if it cannot (unchanged behavior) ~llama_io_write_device() { if (!done && commit() != commit_status::ok) { GGML_ABORT("%s: device state write failed\n", __func__); @@ -2877,6 +2879,23 @@ class llama_io_write_device : public llama_io_write_i { // a dry pass: nothing is allocated or copied void discard() { done = true; } + // what a commit would hold PHYSICALLY: every tensor padded to its buffer type's alignment, plus the + // ggml metadata context each buffer type needs (the header is the caller's) + size_t physical_quote() const { + std::map> per; // bytes, tensors + for (const auto & w : winfos) { + auto * buft = ggml_backend_buffer_get_type(w.tensor->buffer); + auto & e = per[buft]; + e.first += GGML_PAD(w.size, ggml_backend_buft_get_alignment(buft)); + e.second += 1; + } + size_t total = 0; + for (const auto & [buft, e] : per) { + total += e.first + GGML_PAD(2*e.second*ggml_tensor_overhead(), GGML_MEM_ALIGN); + } + return total; + } + // allocate (or reuse) the device buffers and copy the recorded tensors; never throws commit_status commit() { done = true; @@ -3025,10 +3044,11 @@ class llama_io_write_device : public llama_io_write_i { class llama_io_read_device : public llama_io_read_i { public: - llama_io_read_device(const uint8_t * p, size_t len, const llama_memory_buffers & mbufs) : ptr(p), buf_size(len), mbufs(mbufs) { + // `auto_commit` as for the writer: snapshot paths never commit from a destructor. + llama_io_read_device(const uint8_t * p, size_t len, const llama_memory_buffers & mbufs, bool auto_commit = true) + : ptr(p), buf_size(len), mbufs(mbufs), done(!auto_commit) { } - // upstream ON_DEVICE path: commit on destruction, abort on a mismatch (unchanged behavior) ~llama_io_read_device() { if (!done && !commit()) { GGML_ABORT("%s: memory buffer mismatch\n", __func__); @@ -3040,8 +3060,16 @@ class llama_io_read_device : public llama_io_read_i { // copy the stored tensors into the recorded destinations; false on any layout mismatch (checked for // every buffer type BEFORE any copy), never throws or aborts + // test-only fault: the next N read commits fail after the metadata was read (before any copy) + static std::atomic & fail_commits() { static std::atomic n{0}; return n; } + bool commit() { done = true; + for (int n = fail_commits().load(); n > 0;) { + if (fail_commits().compare_exchange_weak(n, n - 1)) { + return false; + } + } llama_memory_buffers mbufs_new; for (const auto & rinfo : rinfos) { @@ -3241,46 +3269,58 @@ size_t llama_context::state_seq_set_data(llama_seq_id seq_id, const uint8_t * sr } } -// Continuum fork: device snapshots, transactional and typed (Codex's review of 7ca9509f0). -llama_snapshot_status llama_context::snapshot_bytes(llama_seq_id seq_id, llama_state_seq_flags flags, size_t * device_bytes) { +// Continuum fork: device snapshots, transactional and typed (Codex's reviews of 7ca9509f0 and be11e4448). +// Every device writer/reader here is constructed with auto_commit = false: no destructor ever allocates +// or copies on these paths, whatever unwinds. + +// What a snapshot holds physically: its device buffers, the ggml metadata contexts, and the host header. +static size_t snapshot_held_bytes(const std::vector & header, const llama_memory_buffers & bufs) { + size_t held = header.size(); + for (const auto & [buft, mbuf] : bufs) { + if (mbuf.buf) { + held += ggml_backend_buffer_get_size(mbuf.buf.get()); + } + if (mbuf.ctx) { + held += ggml_get_mem_size(mbuf.ctx.get()); + } + } + return held; +} + +llama_snapshot_status llama_context::snapshot_bytes(llama_seq_id seq_id, llama_state_seq_flags flags, size_t * held_bytes) { flags |= LLAMA_STATE_SEQ_FLAGS_ON_DEVICE; std::vector header(state_seq_get_size(seq_id, flags)); llama_memory_buffers none; - llama_io_write_device dry(header.data(), header.size(), none); - dry.discard(); // metadata only: nothing is ever allocated or copied by this pass + llama_io_write_device dry(header.data(), header.size(), none, /*auto_commit=*/false); dry.write(&io_magic, sizeof(io_magic)); dry.write(&seq_id, sizeof(seq_id)); state_seq_write_data(dry, seq_id, flags); - *device_bytes = dry.payload_bytes(); - return *device_bytes > 0 ? LLAMA_SNAPSHOT_OK : LLAMA_SNAPSHOT_ABSENT; + if (dry.payload_bytes() == 0) { + return LLAMA_SNAPSHOT_ABSENT; + } + *held_bytes = header.size() + dry.physical_quote(); + return LLAMA_SNAPSHOT_OK; } -llama_snapshot_status llama_context::snapshot_save(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags, size_t * device_bytes) { +llama_snapshot_status llama_context::snapshot_save(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags, size_t * held_bytes) { flags |= LLAMA_STATE_SEQ_FLAGS_ON_DEVICE; // stage into separate storage; the published snapshot (if any) is untouched until this one is complete device_snapshot staged; staged.flags = flags; staged.header.resize(state_seq_get_size(seq_id, flags)); - llama_io_write_device io(staged.header.data(), staged.header.size(), staged.bufs); - try { - io.write(&io_magic, sizeof(io_magic)); - io.write(&seq_id, sizeof(seq_id)); - state_seq_write_data(io, seq_id, flags); - } catch (...) { - io.discard(); // a failed write pass allocates and copies nothing - throw; - } + llama_io_write_device io(staged.header.data(), staged.header.size(), staged.bufs, /*auto_commit=*/false); + io.write(&io_magic, sizeof(io_magic)); + io.write(&seq_id, sizeof(seq_id)); + state_seq_write_data(io, seq_id, flags); staged.layout = io.layout(); - const size_t payload = io.payload_bytes(); - if (payload == 0) { - io.discard(); + if (io.payload_bytes() == 0) { return LLAMA_SNAPSHOT_ABSENT; // nothing to snapshot under these flags } if (io.commit() != llama_io_write_device::commit_status::ok) { return LLAMA_SNAPSHOT_ALLOC_FAILED; // the previous snapshot under this id stays loadable } + *held_bytes = snapshot_held_bytes(staged.header, staged.bufs); snapshots[snapshot_id] = std::move(staged); // publish; a replaced generation is freed here, after the copy - *device_bytes = payload; return LLAMA_SNAPSHOT_OK; } @@ -3294,37 +3334,43 @@ llama_snapshot_status llama_context::snapshot_load(llama_seq_id seq_id, uint64_t if (snap.flags != flags) { return LLAMA_SNAPSHOT_INCOMPATIBLE; } - // validate BEFORE the live sequence is touched: the target's own layout under these flags (a dry, - // metadata-only write pass) must match the snapshot's, tensor by tensor - { + // validate BEFORE the live sequence is touched: a non-empty target's own layout under these flags (a + // dry, metadata-only write pass) must match the snapshot's, tensor by tensor. An EMPTY target (fresh, or + // quarantined by an earlier failure) has nothing to protect: its read allocates the cell from the + // header, and the commit verifies every size before any copy (a mismatch quarantines it again). + if (llama_memory_seq_pos_max(get_memory(), seq_id) >= 0) { std::vector header(state_seq_get_size(seq_id, flags)); llama_memory_buffers none; - llama_io_write_device dry(header.data(), header.size(), none); - dry.discard(); // metadata only + llama_io_write_device dry(header.data(), header.size(), none, /*auto_commit=*/false); dry.write(&io_magic, sizeof(io_magic)); dry.write(&seq_id, sizeof(seq_id)); state_seq_write_data(dry, seq_id, flags); - const bool same = dry.layout() == snap.layout; - if (!same) { + if (dry.layout() != snap.layout) { return LLAMA_SNAPSHOT_INCOMPATIBLE; } } - llama_io_read_device io(snap.header.data(), snap.header.size(), snap.bufs); + llama_io_read_device io(snap.header.data(), snap.header.size(), snap.bufs, /*auto_commit=*/false); + uint32_t magic_read; + io.read(&magic_read, sizeof(magic_read)); + llama_seq_id seq_id_read; + io.read(&seq_id_read, sizeof(seq_id_read)); + if (magic_read != io_magic) { + return LLAMA_SNAPSHOT_INCOMPATIBLE; + } + // from here the read mutates the sequence's cell metadata before the data is copied: any failure + // QUARANTINES the target (cleared whole), so a caller sees a cold sequence, never a half-restored one + bool copied = false; try { - uint32_t magic_read; - io.read(&magic_read, sizeof(magic_read)); - llama_seq_id seq_id_read; - io.read(&seq_id_read, sizeof(seq_id_read)); - if (magic_read != io_magic) { - io.discard(); - return LLAMA_SNAPSHOT_INCOMPATIBLE; - } state_seq_read_data(io, seq_id, flags); + copied = io.commit(); } catch (...) { - io.discard(); // never copy into a half-read state - throw; + copied = false; + } + if (!copied) { + llama_memory_seq_rm(get_memory(), seq_id, -1, -1); + return LLAMA_SNAPSHOT_COPY_FAILED; } - return io.commit() ? LLAMA_SNAPSHOT_OK : LLAMA_SNAPSHOT_COPY_FAILED; + return LLAMA_SNAPSHOT_OK; } llama_snapshot_status llama_context::snapshot_free(uint64_t snapshot_id) { @@ -4401,3 +4447,7 @@ llama_snapshot_status llama_state_seq_snapshot_free(llama_context * ctx, uint64_ void llama_state_seq_snapshot_test_fail_next_allocs(int n) { llama_io_write_device::fail_allocs().store(n); } + +void llama_state_seq_snapshot_test_fail_next_load_commits(int n) { + llama_io_read_device::fail_commits().store(n); +} diff --git a/tests/test-seq-park.cpp b/tests/test-seq-park.cpp index 5c9c0a7ac668..e79d79a77713 100644 --- a/tests/test-seq-park.cpp +++ b/tests/test-seq-park.cpp @@ -202,7 +202,7 @@ int main(int argc, char ** argv) { const int64_t t_s0 = now_us(); require(llama_state_seq_snapshot_save(sctx, 0, 42, P, &bytes) == LLAMA_SNAPSHOT_OK, "save"); const int64_t t_save = now_us() - t_s0; - require(bytes == quoted, "the quote equals what the save holds (the pool reserves exactly this)"); + require(bytes == quoted, "the physical quote equals what the save holds (the pool reserves exactly this)"); // 1. a failed REPLACEMENT keeps the prior snapshot loadable require(decode(sctx, detour, N, 0), "detour"); @@ -220,6 +220,19 @@ int main(int argc, char ** argv) { const int64_t t_load = now_us() - t_l0; // the restore alone (it synchronizes on entry; nothing is in flight) const float d1 = restored_matches_cold(42, "the prior snapshot survived the failed replacement"); + // 2b. a failure AFTER the read began (metadata mutated, copy not done) quarantines the target: it is + // cleared whole, never half-restored; the snapshot itself is intact and restores it again + llama_state_seq_snapshot_test_fail_next_load_commits(1); + require(llama_state_seq_snapshot_load(sctx, 0, 42, P) == LLAMA_SNAPSHOT_COPY_FAILED, "a post-read failure is typed"); + require(llama_memory_seq_pos_max(smem, 0) == -1, "the quarantined target is empty, never half-restored"); + require(llama_state_seq_snapshot_load(sctx, 0, 42, P) == LLAMA_SNAPSHOT_OK, "an empty target restores from the intact snapshot"); + // the recurrent row is back; attention for the prefix was cleared with the quarantine, so re-prefill it + // (attention is trimmed/re-built by position, as the server does) and check the next token + require(llama_memory_seq_rm(smem, 0, -1, -1), "clear for the prefix re-build"); + require(decode(sctx, prefix, 0, 0), "re-prefill after quarantine"); + llama_synchronize(sctx); + require(llama_state_seq_snapshot_save(sctx, 0, 42, P, &bytes) == LLAMA_SNAPSHOT_OK, "re-save after quarantine"); + // 3. save / free with backend work still in flight (no explicit synchronize by the caller) require(decode(sctx, detour, N, 0), "detour 2"); // submitted, not synchronized size_t b3 = 0; From 3c31845537f64808e0da71f6f8b6ced97f4d369e Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 09:47:59 -0600 Subject: [PATCH 7/8] llama: a page is saved off the main thread (device snapshot on it, file written by a writer from the snapshot) CONTINUUM-ENGINE 4.7.13, audit row 6, measured: a page save ran on the engine's main loop (llama_state_seq_save_file) and stalled every co-resident stream (a 201 MB page: 114-135 ms per save; slot 1's median inter-token gap 7 ms -> 103-131 ms, p99 to 2 s). llama_state_seq_snapshot_write_file writes a FULL-sequence device snapshot (saved with flags 0) as the standard state file from the snapshot alone (magic | version | n_tokens | tokens | the state stream with each tensor's bytes spliced into the snapshot header at the positions the writer recorded; host-visible buffers written straight from the buffer). It never touches the context's live state, so it runs on a writer thread while the context decodes. Snapshots are shared_ptrs under a mutex, so a writer keeps its snapshot alive if the main thread frees or replaces the id meanwhile. test-seq-park (qwen35-0.8b, M5), the main thread's cost per save, synchronous vs snapshot (+ the write on a writer thread while the context keeps decoding): 24 MB page 17.5 ms vs 1.8 ms (+14.8); 57 MB 11.9-41.7 ms vs 3.9-4.1 ms (+10.4-39.0); 193 MB (14,000 tokens) 71.2 ms vs 13.1 ms (+131). Every snapshot-written page is BYTE-IDENTICAL to llama_state_seq_save_file's and, loaded back, restores the cold-run logits (max |diff| 0.0044-0.0048). The test's decode helper now feeds prompts in n_batch chunks and takes the context size from -c. 0 build warnings. Server wiring (SLOT_SAVE -> snapshot + writer module, temp path + rename) is next. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo (cherry picked from commit 4121063af00c3710d028205e74f5abd7f9020156) --- include/llama.h | 6 ++ src/llama-context.cpp | 125 ++++++++++++++++++++++++++++++++++++---- src/llama-context.h | 8 ++- tests/test-seq-park.cpp | 78 ++++++++++++++++++++++--- 4 files changed, 198 insertions(+), 19 deletions(-) diff --git a/include/llama.h b/include/llama.h index 751b8ccb0d55..61eb497f6916 100644 --- a/include/llama.h +++ b/include/llama.h @@ -1113,6 +1113,12 @@ extern "C" { LLAMA_API enum llama_snapshot_status llama_state_seq_snapshot_load( struct llama_context * ctx, llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags); + // Write a FULL-sequence snapshot (saved with flags 0) as a standard state file (the format + // llama_state_seq_save_file writes and llama_state_seq_load_file reads), from the snapshot alone: + // safe on a writer thread while the context keeps decoding. + LLAMA_API enum llama_snapshot_status llama_state_seq_snapshot_write_file( + struct llama_context * ctx, uint64_t snapshot_id, const char * filepath, const llama_token * tokens, size_t n_tokens); + // Synchronizes first: no submitted step can still read the buffers being freed. LLAMA_API enum llama_snapshot_status llama_state_seq_snapshot_free(struct llama_context * ctx, uint64_t snapshot_id); diff --git a/src/llama-context.cpp b/src/llama-context.cpp index f0a3cf1b8289..d422aa0611e7 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -2846,7 +2846,26 @@ class llama_io_write_device : public llama_io_write_i { // `auto_commit`: upstream's ON_DEVICE path commits on destruction (and aborts if it cannot), unchanged. // Snapshot paths pass false: nothing is ever allocated or copied by a destructor, whatever unwinds. llama_io_write_device(uint8_t * p, size_t len, llama_memory_buffers & mbufs, bool auto_commit = true) - : ptr(p), buf_size(len), mbufs(mbufs), done(!auto_commit) { + : ptr(p), buf_size(len), mbufs(mbufs), done(!auto_commit), base(p) { + } + + // where each tensor's bytes belong in the host-format stream: its offset in the header, and which + // copy tensor (buffer type, index within it, in the order commit() allocates them) holds them + struct splice { + size_t offset; + ggml_backend_buffer_type_t buft; + size_t index; + size_t size; + }; + std::vector splices() const { + std::vector out; + std::map seen; + out.reserve(winfos.size()); + for (const auto & w : winfos) { + auto * buft = ggml_backend_buffer_get_type(w.tensor->buffer); + out.push_back({ (size_t) (w.ptr - base), buft, seen[buft]++, w.size }); + } + return out; } ~llama_io_write_device() { @@ -3040,6 +3059,7 @@ class llama_io_write_device : public llama_io_write_i { llama_memory_buffers & mbufs; bool done = false; + const uint8_t * base; }; class llama_io_read_device : public llama_io_read_i { @@ -3305,14 +3325,18 @@ llama_snapshot_status llama_context::snapshot_bytes(llama_seq_id seq_id, llama_s llama_snapshot_status llama_context::snapshot_save(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags, size_t * held_bytes) { flags |= LLAMA_STATE_SEQ_FLAGS_ON_DEVICE; // stage into separate storage; the published snapshot (if any) is untouched until this one is complete - device_snapshot staged; + auto staged_ptr = std::make_shared(); + device_snapshot & staged = *staged_ptr; staged.flags = flags; staged.header.resize(state_seq_get_size(seq_id, flags)); llama_io_write_device io(staged.header.data(), staged.header.size(), staged.bufs, /*auto_commit=*/false); io.write(&io_magic, sizeof(io_magic)); io.write(&seq_id, sizeof(seq_id)); state_seq_write_data(io, seq_id, flags); - staged.layout = io.layout(); + staged.layout = io.layout(); + for (const auto & sp : io.splices()) { + staged.splices.push_back({ sp.offset, sp.buft, sp.index, sp.size }); + } if (io.payload_bytes() == 0) { return LLAMA_SNAPSHOT_ABSENT; // nothing to snapshot under these flags } @@ -3320,17 +3344,26 @@ llama_snapshot_status llama_context::snapshot_save(llama_seq_id seq_id, uint64_t return LLAMA_SNAPSHOT_ALLOC_FAILED; // the previous snapshot under this id stays loadable } *held_bytes = snapshot_held_bytes(staged.header, staged.bufs); - snapshots[snapshot_id] = std::move(staged); // publish; a replaced generation is freed here, after the copy - return LLAMA_SNAPSHOT_OK; + std::shared_ptr replaced; + { + std::scoped_lock lock(snapshots_mutex); + replaced = std::exchange(snapshots[snapshot_id], std::move(staged_ptr)); // publish + } + return LLAMA_SNAPSHOT_OK; // a replaced generation is freed when its last reader (a file writer) lets go } llama_snapshot_status llama_context::snapshot_load(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags) { flags |= LLAMA_STATE_SEQ_FLAGS_ON_DEVICE; - auto it = snapshots.find(snapshot_id); - if (it == snapshots.end()) { - return LLAMA_SNAPSHOT_ABSENT; + std::shared_ptr held; + { + std::scoped_lock lock(snapshots_mutex); + auto it = snapshots.find(snapshot_id); + if (it == snapshots.end()) { + return LLAMA_SNAPSHOT_ABSENT; + } + held = it->second; } - const device_snapshot & snap = it->second; + const device_snapshot & snap = *held; if (snap.flags != flags) { return LLAMA_SNAPSHOT_INCOMPATIBLE; } @@ -3374,7 +3407,74 @@ llama_snapshot_status llama_context::snapshot_load(llama_seq_id seq_id, uint64_t } llama_snapshot_status llama_context::snapshot_free(uint64_t snapshot_id) { - return snapshots.erase(snapshot_id) > 0 ? LLAMA_SNAPSHOT_OK : LLAMA_SNAPSHOT_ABSENT; + std::shared_ptr gone; + { + std::scoped_lock lock(snapshots_mutex); + auto it = snapshots.find(snapshot_id); + if (it == snapshots.end()) { + return LLAMA_SNAPSHOT_ABSENT; + } + gone = std::move(it->second); + snapshots.erase(it); + } + return LLAMA_SNAPSHOT_OK; // freed now, or when a file writer still reading it lets go +} + +// Write a snapshot of a FULL sequence state (flags 0) as a standard state file, from the snapshot alone: +// it never touches the context's live state, so it runs on a writer thread while the context decodes. +// File = magic | version | n_tokens | tokens | the state stream with each tensor's bytes spliced into the +// snapshot's header at the position the writer recorded (the first 8 header bytes are the get_data +// prefix, io magic + seq id, which the file format does not carry). Host-visible buffers (unified +// memory) are written straight from the buffer; others are read through the backend. +llama_snapshot_status llama_context::snapshot_write_file(uint64_t snapshot_id, const char * filepath, const llama_token * tokens, size_t n_tokens) { + std::shared_ptr held; + { + std::scoped_lock lock(snapshots_mutex); + auto it = snapshots.find(snapshot_id); + if (it == snapshots.end()) { + return LLAMA_SNAPSHOT_ABSENT; + } + held = it->second; + } + const device_snapshot & snap = *held; + if ((snap.flags & ~LLAMA_STATE_SEQ_FLAGS_ON_DEVICE) != 0) { + return LLAMA_SNAPSHOT_INCOMPATIBLE; // a state file carries the whole sequence, not a partial state + } + const size_t prefix = sizeof(uint32_t) + sizeof(llama_seq_id); + if (snap.header.size() < prefix) { + return LLAMA_SNAPSHOT_INCOMPATIBLE; + } + FILE * f = std::fopen(filepath, "wb"); + if (f == nullptr) { + return LLAMA_SNAPSHOT_COPY_FAILED; + } + bool ok = true; + auto put = [&](const void * p, size_t n) { ok = ok && (n == 0 || std::fwrite(p, 1, n, f) == n); }; + const uint32_t magic = LLAMA_STATE_SEQ_MAGIC, version = LLAMA_STATE_SEQ_VERSION, count = (uint32_t) n_tokens; + put(&magic, sizeof(magic)); + put(&version, sizeof(version)); + put(&count, sizeof(count)); + put(tokens, sizeof(llama_token) * n_tokens); + std::vector staging; + size_t pos = prefix; + for (const auto & sp : snap.splices) { + if (sp.offset < pos || sp.offset > snap.header.size()) { ok = false; break; } + put(snap.header.data() + pos, sp.offset - pos); + pos = sp.offset; + const auto mb = snap.bufs.find(sp.buft); + if (mb == snap.bufs.end() || sp.index >= mb->second.cpy.size()) { ok = false; break; } + const ggml_tensor * t = mb->second.cpy[sp.index]; + if (ggml_backend_buffer_is_host(t->buffer)) { + put(t->data, sp.size); // unified / host memory: straight from the buffer + } else { + staging.resize(sp.size); + ggml_backend_tensor_get(t, staging.data(), 0, sp.size); + put(staging.data(), sp.size); + } + } + put(snap.header.data() + pos, snap.header.size() - std::min(pos, snap.header.size())); + ok = (std::fclose(f) == 0) && ok; + return ok ? LLAMA_SNAPSHOT_OK : LLAMA_SNAPSHOT_COPY_FAILED; } bool llama_context::state_load_file(const char * filepath, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) { @@ -4444,6 +4544,11 @@ llama_snapshot_status llama_state_seq_snapshot_free(llama_context * ctx, uint64_ return llama_snapshot_guard([&] { return ctx->snapshot_free(snapshot_id); }); } +llama_snapshot_status llama_state_seq_snapshot_write_file(llama_context * ctx, uint64_t snapshot_id, const char * filepath, const llama_token * tokens, size_t n_tokens) { + // no synchronize: this reads only the immutable snapshot, never the context's live state + return llama_snapshot_guard([&] { return ctx->snapshot_write_file(snapshot_id, filepath, tokens, n_tokens); }); +} + void llama_state_seq_snapshot_test_fail_next_allocs(int n) { llama_io_write_device::fail_allocs().store(n); } diff --git a/src/llama-context.h b/src/llama-context.h index 7d09698b0da7..683c26e4a4f2 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -13,6 +13,7 @@ #include #include +#include #include struct llama_model; @@ -521,14 +522,19 @@ struct llama_context { llama_memory_buffers bufs; // the state itself, in device buffers llama_state_seq_flags flags = 0; std::vector> layout; // provenance: which tensors, how many bytes + struct splice { size_t offset; ggml_backend_buffer_type_t buft; size_t index; size_t size; }; + std::vector splices; // where each tensor's bytes go in the host-format stream }; - std::map snapshots; + // shared: a file writer on another thread keeps a snapshot alive after its id is freed or replaced + std::map> snapshots; + std::mutex snapshots_mutex; public: llama_snapshot_status snapshot_bytes(llama_seq_id seq_id, llama_state_seq_flags flags, size_t * device_bytes); llama_snapshot_status snapshot_save(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags, size_t * device_bytes); llama_snapshot_status snapshot_load(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags); llama_snapshot_status snapshot_free(uint64_t snapshot_id); + llama_snapshot_status snapshot_write_file(uint64_t snapshot_id, const char * filepath, const llama_token * tokens, size_t n_tokens); private: bool has_evaluated_once = false; diff --git a/tests/test-seq-park.cpp b/tests/test-seq-park.cpp index e79d79a77713..6abb9a504f27 100644 --- a/tests/test-seq-park.cpp +++ b/tests/test-seq-park.cpp @@ -17,6 +17,8 @@ #include #endif #include +#include +#include #include static int64_t now_us() { @@ -26,21 +28,28 @@ static int64_t now_us() { static llama_context * make_ctx(const common_params & params, llama_model * model) { auto cparams = common_context_params_to_llama(params); cparams.n_seq_max = 2; // seq 0 live, seq 1 parked - cparams.n_ctx = 8192; cparams.n_batch = 4096; cparams.n_ubatch = 512; cparams.kv_unified = true; // one stream: a parked id shares the live sequence's cells return llama_init_from_model(model, cparams); } +// feeds `toks` in batches of at most the context's n_batch; logits only for the last token static bool decode(llama_context * ctx, const std::vector & toks, llama_pos p0, llama_seq_id seq) { - llama_batch batch = llama_batch_init((int32_t) toks.size(), 0, 1); - for (size_t i = 0; i < toks.size(); ++i) { - common_batch_add(batch, toks[i], p0 + (llama_pos) i, { seq }, i + 1 == toks.size()); + const size_t step = llama_n_batch(ctx); + for (size_t off = 0; off < toks.size(); off += step) { + const size_t n = std::min(step, toks.size() - off); + llama_batch batch = llama_batch_init((int32_t) n, 0, 1); + for (size_t i = 0; i < n; ++i) { + common_batch_add(batch, toks[off + i], p0 + (llama_pos) (off + i), { seq }, off + i + 1 == toks.size()); + } + const bool ok = llama_decode(ctx, batch) == 0; + llama_batch_free(batch); + if (!ok) { + return false; + } } - const bool ok = llama_decode(ctx, batch) == 0; - llama_batch_free(batch); - return ok; + return true; } static std::vector last_logits(llama_context * ctx, int n_vocab) { @@ -168,7 +177,6 @@ int main(int argc, char ** argv) { { auto cparams = common_context_params_to_llama(params); cparams.n_seq_max = 1; - cparams.n_ctx = 8192; cparams.n_batch = 4096; cparams.n_ubatch = 512; llama_context * sctx = llama_init_from_model(model, cparams); @@ -268,6 +276,60 @@ int main(int argc, char ** argv) { base / 1048576.0, peak / 1048576.0, after / 1048576.0); require(after - base < (int64_t) bytes, "no growth across cycles beyond one snapshot of slack"); llama_state_seq_snapshot_free(sctx, 42); + + // 5. a page SAVED OFF THE MAIN THREAD: the main thread takes only a full-state device snapshot; + // a writer thread writes the standard state file from it WHILE the context keeps decoding. + // The file must equal llama_state_seq_save_file's byte for byte and restore a cold-equal state. + { + require(llama_memory_seq_rm(smem, 0, -1, -1), "clear for the page test"); + require(decode(sctx, prefix, 0, 0), "page prefix"); + llama_synchronize(sctx); + const std::string dir = std::getenv("TMPDIR") ? std::getenv("TMPDIR") : "/tmp"; + const std::string sync_path = dir + "/seq-park-sync.page", snap_path = dir + "/seq-park-snap.page"; + const int64_t t_sync0 = now_us(); + require(llama_state_seq_save_file(sctx, sync_path.c_str(), 0, prefix.data(), prefix.size()) > 0, "synchronous save"); + const int64_t t_sync = now_us() - t_sync0; + size_t page_bytes = 0; + const int64_t t_snap0 = now_us(); + require(llama_state_seq_snapshot_save(sctx, 0, 500, LLAMA_STATE_SEQ_FLAGS_NONE, &page_bytes) == LLAMA_SNAPSHOT_OK, "full-state snapshot"); + const int64_t t_snap = now_us() - t_snap0; // what the main thread now pays + llama_snapshot_status written = LLAMA_SNAPSHOT_COPY_FAILED; + int64_t t_write = 0; + std::thread writer([&] { + const int64_t t0 = now_us(); + written = llama_state_seq_snapshot_write_file(sctx, 500, snap_path.c_str(), prefix.data(), prefix.size()); + t_write = now_us() - t0; + }); + require(decode(sctx, detour, N, 0), "the context keeps decoding while the page is written"); + llama_synchronize(sctx); + writer.join(); + require(written == LLAMA_SNAPSHOT_OK, "the writer thread wrote the page"); + require(llama_state_seq_snapshot_free(sctx, 500) == LLAMA_SNAPSHOT_OK, "free the page snapshot"); + auto slurp = [](const std::string & path) { + std::FILE * f = std::fopen(path.c_str(), "rb"); + std::vector v; + if (!f) return v; + std::fseek(f, 0, SEEK_END); v.resize((size_t) std::ftell(f)); std::fseek(f, 0, SEEK_SET); + const size_t got = std::fread(v.data(), 1, v.size(), f); std::fclose(f); v.resize(got); + return v; + }; + const auto a_bytes = slurp(sync_path), b_bytes = slurp(snap_path); + require(!a_bytes.empty() && a_bytes == b_bytes, "the snapshot-written page equals the synchronous page byte for byte"); + // and it restores: load into the cleared sequence, decode the next token, compare with the cold run + require(llama_memory_seq_rm(smem, 0, -1, -1), "clear before loading the page"); + std::vector back(prefix.size()); + size_t n_back = 0; + require(llama_state_seq_load_file(sctx, snap_path.c_str(), 0, back.data(), back.size(), &n_back) > 0 && n_back == prefix.size(), "load the page"); + require(decode(sctx, { next }, N, 0), "decode after loading the page"); + const std::vector got = last_logits(sctx, n_vocab); + int am = 0; float d = 0.0f; + for (int i = 0; i < n_vocab; ++i) { d = std::max(d, std::fabs(ref[i] - got[i])); if (got[i] > got[am]) am = i; } + require(am == argmax_ref && d <= 1e-2f, "the page restores the cold-run logits"); + std::printf("page save: %zu-byte file; synchronous save %lld us on the main thread vs snapshot %lld us on it + %lld us on a writer thread (decoding meanwhile); byte-identical, restores (max |diff| %.6g)\n", + a_bytes.size(), (long long) t_sync, (long long) t_snap, (long long) t_write, d); + std::remove(sync_path.c_str()); + std::remove(snap_path.c_str()); + } llama_free(sctx); } From 8cef1077c914ca1816d3a2d6496737f0a9b5fa5d Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 10:29:55 -0600 Subject: [PATCH 8/8] snapshots: a failed restore's quarantine proves its clear; an uncleared target is TARGET_UNCLEARED, kept in the caller's custody Codex's review of 16a02cca6: the post-read failure path called llama_memory_seq_rm and ignored its result, then returned COPY_FAILED, which promises an empty (cold) target. If the clear failed, a half-restored sequence was reported cold and could be served or reused. Now quarantine() succeeds only when seq_rm reports success AND the sequence holds no position afterwards; otherwise the load returns the new LLAMA_SNAPSHOT_TARGET_UNCLEARED, and the header states the caller keeps custody of the sequence (never serves, parks or returns it) until its own clear succeeds. The header also states the owner-attribution rule: on COPY_FAILED the sequence holds no one's state, so the caller drops any record that it holds a mind's tokens. Test (test-seq-park 2c, qwen35-0.8b): a forced load-commit failure plus a forced clear failure returns TARGET_UNCLEARED; the custodian's clear then succeeds; every existing case still passes. 0 build warnings. Fault hook llama_state_seq_snapshot_test_fail_next_quarantine_clears uses the same CAS countdown as the existing load-commit hook. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo (cherry picked from commit 252f36dd4885c3a50e29a45a1bb52b6e2eeccb18) --- include/llama.h | 13 ++++++++++--- src/llama-context.cpp | 25 +++++++++++++++++++++++-- src/llama-context.h | 1 + tests/test-seq-park.cpp | 7 +++++++ 4 files changed, 41 insertions(+), 5 deletions(-) diff --git a/include/llama.h b/include/llama.h index 61eb497f6916..42c06e4a52b0 100644 --- a/include/llama.h +++ b/include/llama.h @@ -1095,7 +1095,10 @@ extern "C" { LLAMA_SNAPSHOT_ABSENT = 1, // no snapshot under this id / nothing to snapshot under these flags LLAMA_SNAPSHOT_INCOMPATIBLE = 2, // flags or tensor layout differ from the target: nothing was changed LLAMA_SNAPSHOT_ALLOC_FAILED = 3, // device memory could not be allocated: a previous snapshot is kept - LLAMA_SNAPSHOT_COPY_FAILED = 4, // the copy itself failed + LLAMA_SNAPSHOT_COPY_FAILED = 4, // the copy itself failed; a load's target was cleared whole (it holds no one's state) + LLAMA_SNAPSHOT_TARGET_UNCLEARED = 5, // a load failed after the read began AND clearing its target failed: the + // sequence is undefined; the caller keeps custody of it (never serves, + // parks or returns it) until llama_memory_seq_rm(seq, -1, -1) succeeds }; // The bytes a snapshot of `seq_id` would hold PHYSICALLY (device buffers at their alignment, ggml @@ -1109,7 +1112,9 @@ extern "C" { struct llama_context * ctx, llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags, size_t * device_bytes); // Validated before the live sequence is touched: refused (INCOMPATIBLE) on a flags or layout mismatch. A - // failure after the read began quarantines the target (cleared whole) and returns COPY_FAILED. + // failure after the read began quarantines the target (cleared whole) and returns COPY_FAILED: the caller + // must then drop any record that the sequence holds a mind's tokens (it is cold). If the clear itself does + // not leave the sequence empty, TARGET_UNCLEARED: the caller keeps custody of the sequence until it clears. LLAMA_API enum llama_snapshot_status llama_state_seq_snapshot_load( struct llama_context * ctx, llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags); @@ -1123,9 +1128,11 @@ extern "C" { LLAMA_API enum llama_snapshot_status llama_state_seq_snapshot_free(struct llama_context * ctx, uint64_t snapshot_id); // Test-only fault injection: the next `n` snapshot device allocations fail; the next `n` load commits - // fail after the read (the target is then quarantined: cleared whole, COPY_FAILED). + // fail after the read (the target is then quarantined: cleared whole, COPY_FAILED); the next `n` + // quarantine clears fail (TARGET_UNCLEARED). LLAMA_API void llama_state_seq_snapshot_test_fail_next_allocs(int n); LLAMA_API void llama_state_seq_snapshot_test_fail_next_load_commits(int n); + LLAMA_API void llama_state_seq_snapshot_test_fail_next_quarantine_clears(int n); // // Decoding diff --git a/src/llama-context.cpp b/src/llama-context.cpp index d422aa0611e7..f9b4f19b15df 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -3400,12 +3400,29 @@ llama_snapshot_status llama_context::snapshot_load(llama_seq_id seq_id, uint64_t copied = false; } if (!copied) { - llama_memory_seq_rm(get_memory(), seq_id, -1, -1); - return LLAMA_SNAPSHOT_COPY_FAILED; + return quarantine(seq_id) ? LLAMA_SNAPSHOT_COPY_FAILED : LLAMA_SNAPSHOT_TARGET_UNCLEARED; } return LLAMA_SNAPSHOT_OK; } +// Clear a sequence whose restore failed after the read began. Success is proven, not assumed: seq_rm +// reports success AND the sequence holds no position afterwards. Anything else is TARGET_UNCLEARED for the +// caller, who keeps custody of the sequence (a half-restored state must never be served or reused). +static std::atomic & quarantine_clear_failures() { + static std::atomic n{0}; + return n; +} + +bool llama_context::quarantine(llama_seq_id seq_id) { + for (int n = quarantine_clear_failures().load(); n > 0;) { + if (quarantine_clear_failures().compare_exchange_weak(n, n - 1)) { + return false; // test fault injection: the clear "fails", leaving the sequence as the failed read left it + } + } + llama_memory_t mem = get_memory(); + return llama_memory_seq_rm(mem, seq_id, -1, -1) && llama_memory_seq_pos_max(mem, seq_id) < 0; +} + llama_snapshot_status llama_context::snapshot_free(uint64_t snapshot_id) { std::shared_ptr gone; { @@ -4556,3 +4573,7 @@ void llama_state_seq_snapshot_test_fail_next_allocs(int n) { void llama_state_seq_snapshot_test_fail_next_load_commits(int n) { llama_io_read_device::fail_commits().store(n); } + +void llama_state_seq_snapshot_test_fail_next_quarantine_clears(int n) { + quarantine_clear_failures().store(n); +} diff --git a/src/llama-context.h b/src/llama-context.h index 683c26e4a4f2..e7249b2850e0 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -533,6 +533,7 @@ struct llama_context { llama_snapshot_status snapshot_bytes(llama_seq_id seq_id, llama_state_seq_flags flags, size_t * device_bytes); llama_snapshot_status snapshot_save(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags, size_t * device_bytes); llama_snapshot_status snapshot_load(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags); + bool quarantine(llama_seq_id seq_id); // clear a failed restore; true only when the sequence is empty after llama_snapshot_status snapshot_free(uint64_t snapshot_id); llama_snapshot_status snapshot_write_file(uint64_t snapshot_id, const char * filepath, const llama_token * tokens, size_t n_tokens); private: diff --git a/tests/test-seq-park.cpp b/tests/test-seq-park.cpp index 6abb9a504f27..e1c1b5396173 100644 --- a/tests/test-seq-park.cpp +++ b/tests/test-seq-park.cpp @@ -233,6 +233,13 @@ int main(int argc, char ** argv) { llama_state_seq_snapshot_test_fail_next_load_commits(1); require(llama_state_seq_snapshot_load(sctx, 0, 42, P) == LLAMA_SNAPSHOT_COPY_FAILED, "a post-read failure is typed"); require(llama_memory_seq_pos_max(smem, 0) == -1, "the quarantined target is empty, never half-restored"); + // 2c. if the quarantine's own clear fails, the status says the target is UNDEFINED (not cold): the + // caller keeps custody until its clear succeeds (regression for Codex's review of 16a02cca6: the + // clear's result was ignored and COPY_FAILED claimed an empty target) + llama_state_seq_snapshot_test_fail_next_load_commits(1); + llama_state_seq_snapshot_test_fail_next_quarantine_clears(1); + require(llama_state_seq_snapshot_load(sctx, 0, 42, P) == LLAMA_SNAPSHOT_TARGET_UNCLEARED, "a failed clear is reported, never claimed cold"); + require(llama_memory_seq_rm(smem, 0, -1, -1) && llama_memory_seq_pos_max(smem, 0) == -1, "the custodian clears it"); require(llama_state_seq_snapshot_load(sctx, 0, 42, P) == LLAMA_SNAPSHOT_OK, "an empty target restores from the intact snapshot"); // the recurrent row is back; attention for the prefix was cleared with the quarantine, so re-prefill it // (attention is trimmed/re-built by position, as the server does) and check the next token