From 715840bbd71cb447a93264d8d34033f1a83d61ef Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 21:41:10 -0600 Subject: [PATCH 01/28] kv: a persona's KV moves between a stream and host memory as raw rows, her metadata by swap, her sequence bound to any stream (CONTINUUM-ENGINE 4.14 prototype) stream_save/stream_load copy her used rows per layer raw (K, V) and swap her llama_kv_cells out/in (no cell walk, no serialization, no recompute); stream_bind maps her own sequence id to a physical stream (seq_to_stream stays a permutation; her cells are never retagged). Graph reuse now compares each sequence's physical stream (llama_memory_i::seq_stream), since K/V views are built at the stream, not the sequence id. The raw copies require the completion fence (llama_synchronize) first: a decode returns before its KV writes land. test-kv-stream-blocks (Metal, M5): next-token logits byte-identical (max|diff| 0) after moving her stream 0 -> host -> stream 1 with her sequence bound there; mirror direction; with and without the destination used first; first and second token after the move. Without the fence the move read zeros (max|diff| 18.15, top token changed). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- src/llama-context.cpp | 9 +- src/llama-graph.h | 7 + src/llama-kv-cache-iswa.h | 2 + src/llama-kv-cache.cpp | 83 ++++++++++++ src/llama-kv-cache.h | 34 +++++ src/llama-memory-hybrid-iswa.h | 2 + src/llama-memory-hybrid.h | 2 + src/llama-memory.h | 4 + tests/CMakeLists.txt | 4 + tests/test-kv-stream-blocks.cpp | 224 ++++++++++++++++++++++++++++++++ 10 files changed, 370 insertions(+), 1 deletion(-) create mode 100644 tests/test-kv-stream-blocks.cpp diff --git a/src/llama-context.cpp b/src/llama-context.cpp index c2d348884ce9..8884f065bcd0 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -2572,7 +2572,7 @@ llm_graph_params llama_context::graph_params( const llama_ubatch & ubatch, const llama_memory_context_i * mctx, llm_graph_type gtype) const { - return { + llm_graph_params params = { /*.arch =*/ model.arch, /*.hparams =*/ model.hparams, /*.cparams =*/ cparams, @@ -2591,6 +2591,13 @@ llm_graph_params llama_context::graph_params( /*.cb =*/ graph_get_cb(), /*.res =*/ res, }; + if (memory) { + params.streams.reserve(ubatch.n_seqs_unq); + for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) { + params.streams.push_back(memory->seq_stream(ubatch.seq_id_unq[s])); + } + } + return params; } ggml_status llama_context::graph_compute( diff --git a/src/llama-graph.h b/src/llama-graph.h index 323dc722d5e1..49310ab80b90 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -829,6 +829,10 @@ struct llm_graph_params { llm_graph_result * res; + // the physical attention stream of each of the ubatch's unique sequences (seq_id_unq order): the graph's K/V views + // are built at these streams, so a graph is reused only when they match, not merely the sequence ids + std::vector streams = {}; + // return true if the "other" params would result in a graph with the same topology as with the current params // having the same topology allows us to reuse the graph in some cases bool allow_reuse(const llm_graph_params & other) const { @@ -859,6 +863,9 @@ struct llm_graph_params { } } + // the graph's K/V views are built at these physical streams, whatever the split: never reuse across streams + can_reuse_ubatch = can_reuse_ubatch && streams == other.streams; + if (!can_reuse_ubatch) { return false; } diff --git a/src/llama-kv-cache-iswa.h b/src/llama-kv-cache-iswa.h index 546b8325d8ad..256d40dd1f0e 100644 --- a/src/llama-kv-cache-iswa.h +++ b/src/llama-kv-cache-iswa.h @@ -91,6 +91,8 @@ class llama_kv_cache_iswa : public llama_memory_i { // llama_kv_cache * get_base() const; + + uint32_t seq_stream(llama_seq_id seq_id) const override { return kv_base->seq_stream(seq_id); } llama_kv_cache * get_swa () const; private: diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index 76aa5692442e..1adcf1e17ece 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -1231,6 +1231,89 @@ ggml_tensor * llama_kv_cache::get_k_storage(int32_t il) const { return layers[ikv].k; } +llama_kv_stream_move llama_kv_cache::stream_save(uint32_t s, llama_kv_stream_blocks & out) { + if (s >= n_stream || n_stream == 1) { + return llama_kv_stream_move::no_such_stream; + } + if (v_trans) { + return llama_kv_stream_move::transposed_v; + } + auto & cells = v_cells[s]; + const uint32_t n_rows = cells.used_max_p1(); + out.n_rows = n_rows; + out.k.resize(layers.size()); + out.v.resize(layers.size()); + for (size_t i = 0; i < layers.size(); ++i) { + const auto & layer = layers[i]; + const size_t k_bytes = ggml_row_size(layer.k->type, layer.k->ne[0]) * n_rows; + out.k[i].resize(k_bytes); + if (k_bytes > 0) { + ggml_backend_tensor_get(layer.k_stream[s], out.k[i].data(), 0, k_bytes); + } + if (layer.v) { + const size_t v_bytes = ggml_row_size(layer.v->type, layer.v->ne[0]) * n_rows; + out.v[i].resize(v_bytes); + if (v_bytes > 0) { + ggml_backend_tensor_get(layer.v_stream[s], out.v[i].data(), 0, v_bytes); + } + } else { + out.v[i].clear(); + } + } + // her metadata leaves with her by swap; the stream takes an empty one of its own size + if (out.cells.size() != cells.size()) { + out.cells.resize(cells.size()); + } else { + out.cells.reset(); + } + std::swap(out.cells, cells); + v_heads[s] = 0; + return llama_kv_stream_move::done; +} + +llama_kv_stream_move llama_kv_cache::stream_bind(llama_seq_id seq, uint32_t s) { + if (n_stream == 1 || s >= n_stream || seq < 0 || (size_t) seq >= seq_to_stream.size()) { + return llama_kv_stream_move::no_such_stream; + } + const uint32_t old = seq_to_stream[seq]; + for (auto & st : seq_to_stream) { + if (st == s) { + st = old; // the sequence that held `s` takes her old stream + break; + } + } + seq_to_stream[seq] = s; + return llama_kv_stream_move::done; +} + +llama_kv_stream_move llama_kv_cache::stream_load(uint32_t s, llama_kv_stream_blocks & in) { + if (s >= n_stream || n_stream == 1) { + return llama_kv_stream_move::no_such_stream; + } + if (v_trans) { + return llama_kv_stream_move::transposed_v; + } + auto & cells = v_cells[s]; + if (cells.get_used() != 0) { + return llama_kv_stream_move::stream_not_empty; + } + if (in.n_rows > cells.size() || in.cells.size() != cells.size()) { + return llama_kv_stream_move::too_long; + } + for (size_t i = 0; i < layers.size(); ++i) { + const auto & layer = layers[i]; + if (!in.k[i].empty()) { + ggml_backend_tensor_set(layer.k_stream[s], in.k[i].data(), 0, in.k[i].size()); + } + if (layer.v && !in.v[i].empty()) { + ggml_backend_tensor_set(layer.v_stream[s], in.v[i].data(), 0, in.v[i].size()); + } + } + std::swap(in.cells, cells); // her metadata back in; `in` keeps the stream's empty cells for reuse + v_heads[s] = 0; + return llama_kv_stream_move::done; +} + const llama_kv_cells & llama_kv_cache::get_cells(llama_seq_id seq_id) const { GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size()); diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h index cba1f663b2e4..e889c247cc06 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -17,6 +17,26 @@ struct llama_context; // llama_kv_cache // +// Continuum fork (CONTINUUM-ENGINE 4.14): a persona's KV, out of the pool: per KV layer, her K and V rows of one stream +// copied raw (the rows she uses, in the stream's own row layout), and her stream's cell metadata OWNED here (moved by +// swap, never copied or rebuilt). Moving a persona between a stream and host memory is these raw copies plus one swap; +// nothing walks a cell, serializes or recomputes. +struct llama_kv_stream_blocks { + uint32_t n_rows = 0; // rows she uses (the stream's used_max_p1 when saved) + std::vector> k; // per KV layer: n_rows rows of K + std::vector> v; // per KV layer: n_rows rows of V (empty for a layer without V) + llama_kv_cells cells; // her cell metadata; sized to the stream when first used +}; + +// the outcome of moving a persona's KV between a stream and host memory +enum class llama_kv_stream_move { + done, + no_such_stream, // s >= n_stream (or the cache is unified: one stream holds every sequence) + transposed_v, // V is stored transposed (flash attention off): her V rows are not contiguous; not supported + stream_not_empty, // a load requires an empty stream + too_long, // her rows exceed the stream's size +}; + class llama_kv_cache : public llama_memory_i { public: struct stream_copy_info { @@ -175,6 +195,20 @@ class llama_kv_cache : public llama_memory_i { const llama_kv_cells & get_cells(llama_seq_id seq_id) const; + // Continuum fork (CONTINUUM-ENGINE 4.14): stream `s` -> `out` (her rows copied raw, her cells swapped out: the + // stream is left empty), and `in` -> empty stream `s` (rows copied raw, cells swapped in). A per-sequence stream + // exists only with unified KV off. + // FENCE: the caller must have completed the context's queued device work first (llama_synchronize): a decode + // returns before its KV writes land, and these copies touch the same device memory. + llama_kv_stream_move stream_save(uint32_t s, llama_kv_stream_blocks & out); + llama_kv_stream_move stream_load(uint32_t s, llama_kv_stream_blocks & in); + // bind sequence `seq` (a persona's own, stable id) to physical stream `s`: the map stays a permutation (the + // sequence that held `s` takes `seq`'s old stream). Her cells keep their sequence id, so nothing is retagged. + // Between batches only: every lookup reads the map at call time. + llama_kv_stream_move stream_bind(llama_seq_id seq, uint32_t s); + + uint32_t seq_stream(llama_seq_id seq_id) const override { return seq_to_stream[seq_id]; } + // // graph_build API // diff --git a/src/llama-memory-hybrid-iswa.h b/src/llama-memory-hybrid-iswa.h index a6b9d84c1ecb..ff287283a16c 100644 --- a/src/llama-memory-hybrid-iswa.h +++ b/src/llama-memory-hybrid-iswa.h @@ -84,6 +84,8 @@ class llama_memory_hybrid_iswa : public llama_memory_i { // llama_kv_cache_iswa * get_mem_attn() const; + + uint32_t seq_stream(llama_seq_id seq_id) const override { return mem_attn->seq_stream(seq_id); } llama_memory_recurrent * get_mem_recr() const; private: diff --git a/src/llama-memory-hybrid.h b/src/llama-memory-hybrid.h index 8cd1dfc80982..593ff802c1f9 100644 --- a/src/llama-memory-hybrid.h +++ b/src/llama-memory-hybrid.h @@ -86,6 +86,8 @@ class llama_memory_hybrid : public llama_memory_i { // llama_kv_cache * get_mem_attn() const; + + uint32_t seq_stream(llama_seq_id seq_id) const override { return mem_attn->seq_stream(seq_id); } llama_memory_recurrent * get_mem_recr() const; private: diff --git a/src/llama-memory.h b/src/llama-memory.h index ceb327db46f1..588853925216 100644 --- a/src/llama-memory.h +++ b/src/llama-memory.h @@ -147,6 +147,10 @@ struct llama_memory_i { virtual llama_pos seq_pos_min(llama_seq_id seq_id) const = 0; virtual llama_pos seq_pos_max(llama_seq_id seq_id) const = 0; + // the physical attention stream holding this sequence (Continuum fork: a persona's sequence can be bound to any + // stream, so a stream is never assumed from the sequence id). Memories with no stream map hold it by identity. + virtual uint32_t seq_stream(llama_seq_id seq_id) const { return (uint32_t) seq_id; } + virtual std::map memory_breakdown() const = 0; // the occupancy of every cell holder this memory owns (see llama_memory_cells) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 408d42e577dd..548cd7258f49 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -355,6 +355,10 @@ llama_build_and_test(test-dup-quantized.cpp) llama_build_and_test(test-state-restore-streams.cpp LABEL "model" ARGS -m "${MODEL_DEST}") set_tests_properties(test-state-restore-streams PROPERTIES FIXTURES_REQUIRED test-download-model) +# a persona's KV moved between a stream and host memory by raw copies is byte-identical (CONTINUUM-ENGINE 4.14) +llama_build_and_test(test-kv-stream-blocks.cpp LABEL "model" ARGS -m "${MODEL_DEST}") +set_tests_properties(test-kv-stream-blocks PROPERTIES FIXTURES_REQUIRED test-download-model) + # Test state save/load functionality llama_build_and_test(test-save-load-state.cpp LABEL "model" ARGS -m "${MODEL_DEST}") set_tests_properties(test-save-load-state PROPERTIES FIXTURES_REQUIRED test-download-model) diff --git a/tests/test-kv-stream-blocks.cpp b/tests/test-kv-stream-blocks.cpp new file mode 100644 index 000000000000..f7e2410e3fe7 --- /dev/null +++ b/tests/test-kv-stream-blocks.cpp @@ -0,0 +1,224 @@ +// what this catches: moving a persona's KV between a stream and host memory (llama_kv_cache::stream_save / +// stream_load / stream_bind, CONTINUUM-ENGINE 4.14) changing her state: after a raw save out of stream 0, a raw load +// into stream 1 and binding her own sequence id to stream 1 (no metadata retagged), her next token's logits must be +// byte-identical to decoding it in place. Also: the stream is left empty by a save, +// and a load into a stream that holds state is refused. No cell walk, serialization or recompute is involved; if any +// row or metadata were lost or misplaced, the logits would differ. + +#include "arg.h" +#include "common.h" +#include "llama.h" + +#include "../src/llama-kv-cache.h" + +#include +#include +#include +#include +#include +#include + +static void require(bool condition, const char * message) { + if (!condition) { + fprintf(stderr, "FAILED: %s\n", message); + std::exit(1); + } +} + +static llama_kv_cache * g_kv = nullptr; + +// the completion fence: llama_decode queues device work and returns; a raw copy of a stream reads or writes device +// memory, so the context's queued compute must have completed first (the same fence llama_state_* takes) +static bool fenced(llama_context * ctx) { + llama_synchronize(ctx); + return true; +} + +// her stream's cell metadata as the decode left it: used count, extent, and each used cell's (index, pos, has her seq) +static void dump_cells(const char * what, llama_seq_id seq) { + const auto & cells = g_kv->get_cells(seq); + fprintf(stderr, "%s: seq %d used=%u used_max_p1=%u cells:", what, seq, cells.get_used(), cells.used_max_p1()); + for (uint32_t i = 0; i < cells.size(); ++i) { + if (!cells.is_empty(i) && (i < 2 || i + 3 >= cells.used_max_p1())) { + fprintf(stderr, " [%u p%d s%d]", i, cells.pos_get(i), cells.seq_has(i, seq) ? 1 : 0); + } + } + fprintf(stderr, "\n"); +} + +static std::vector next_logits(llama_context * ctx, llama_seq_id seq, llama_token token, llama_pos pos) { + llama_batch b = llama_batch_init(1, 0, 1); + common_batch_add(b, token, pos, { seq }, true); + require(llama_decode(ctx, b) == 0, "decode the next token"); + const int n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(llama_get_model(ctx))); + const float * l = llama_get_logits_ith(ctx, 0); + std::vector out(l, l + n_vocab); + llama_batch_free(b); + return out; +} + +// the largest absolute difference and whether the top token agrees (diagnostic when bytes differ) +static void report(const char * what, const std::vector & a, const std::vector & b) { + float max_diff = 0.0f; + size_t top_a = 0, top_b = 0; + for (size_t i = 0; i < a.size(); ++i) { + max_diff = std::max(max_diff, std::fabs(a[i] - b[i])); + top_a = a[i] > a[top_a] ? i : top_a; + top_b = b[i] > b[top_b] ? i : top_b; + } + const bool same = std::memcmp(a.data(), b.data(), a.size() * sizeof(float)) == 0; + fprintf(stderr, "%s: byte-identical=%d max|diff|=%g top=%zu/%zu\n", what, same ? 1 : 0, max_diff, top_a, top_b); +} + +int main(int argc, char ** argv) { + common_params params; + params.kv_unified = false; // one stream per sequence: a persona's KV is one contiguous slice per layer + params.n_parallel = 2; + params.n_ctx = 512; + params.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_ENABLED; // V rows contiguous (not transposed) + common_init(); + if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_COMMON)) { + return 1; + } + ggml_backend_load_all(); + common_init_result_ptr init = common_init_from_params(params); + llama_context * ctx = init->context(); + require(ctx != nullptr, "context"); + auto * kv = dynamic_cast(llama_get_memory(ctx)); + require(kv != nullptr, "a plain KV cache (the test model is not hybrid)"); + g_kv = kv; + + // her prompt on sequence 0 (stream 0) + const int n_prompt = 40; + llama_batch batch = llama_batch_init(n_prompt, 0, 1); + for (int i = 0; i < n_prompt; ++i) { + common_batch_add(batch, 1 + (i * 7) % 300, i, { 0 }, false); + } + require(llama_decode(ctx, batch) == 0, "decode her prompt"); + llama_batch_free(batch); + + // the reference: her next token decoded in place, then taken back so stream 0 holds exactly her prompt again + const llama_token next = 42; + const std::vector reference = next_logits(ctx, 0, next, n_prompt); + dump_cells("after reference decode", 0); + require(llama_memory_seq_rm(llama_get_memory(ctx), 0, n_prompt, -1), "take the reference token back"); + + // control: the same prompt decoded natively on sequence 1 (stream 1); does stream identity alone change logits? + { + llama_batch b1 = llama_batch_init(n_prompt, 0, 1); + for (int i = 0; i < n_prompt; ++i) { + common_batch_add(b1, 1 + (i * 7) % 300, i, { 1 }, false); + } + require(llama_decode(ctx, b1) == 0, "decode her prompt natively on stream 1"); + llama_batch_free(b1); + const std::vector native1 = next_logits(ctx, 1, next, n_prompt); + report("native on stream 1 vs stream 0", reference, native1); + require(llama_memory_seq_rm(llama_get_memory(ctx), 1, -1, -1), "clear the stream 1 control"); + } + + // determinism: the same token decoded in place again + { + const std::vector again = next_logits(ctx, 0, next, n_prompt); + report("in place twice", reference, again); + require(llama_memory_seq_rm(llama_get_memory(ctx), 0, n_prompt, -1), "take it back again"); + } + // the copies alone: a round trip through host memory into the SAME stream, no bind + { + llama_kv_stream_blocks rt; + require(fenced(ctx) && kv->stream_save(0, rt) == llama_kv_stream_move::done, "round-trip save"); + require(fenced(ctx) && kv->stream_load(0, rt) == llama_kv_stream_move::done, "round-trip load"); + const std::vector same_stream = next_logits(ctx, 0, next, n_prompt); + report("same stream round trip", reference, same_stream); + require(llama_memory_seq_rm(llama_get_memory(ctx), 0, n_prompt, -1), "take it back after the round trip"); + } + + // out: raw rows + her metadata swapped out; stream 0 left empty + llama_kv_stream_blocks blocks; + require(fenced(ctx) && kv->stream_save(0, blocks) == llama_kv_stream_move::done, "save stream 0"); + require(blocks.n_rows == (uint32_t) n_prompt, "she uses exactly her prompt's rows"); + require(llama_memory_seq_pos_max(llama_get_memory(ctx), 0) < 0, "stream 0 is empty after the save"); + + // a load into a stream that holds state is refused, and changes nothing + { + llama_batch b = llama_batch_init(1, 0, 1); + common_batch_add(b, 5, 0, { 1 }, false); + require(llama_decode(ctx, b) == 0, "occupy stream 1"); + llama_batch_free(b); + require(fenced(ctx) && kv->stream_load(1, blocks) == llama_kv_stream_move::stream_not_empty, "never loaded over state"); + require(llama_memory_seq_rm(llama_get_memory(ctx), 1, -1, -1), "clear stream 1"); + } + + // in: raw rows + her metadata swapped into physical stream 1; she keeps her own sequence id 0, bound to stream 1 + require(fenced(ctx) && kv->stream_load(1, blocks) == llama_kv_stream_move::done, "load into stream 1"); + require(kv->stream_bind(0, 1) == llama_kv_stream_move::done, "bind her sequence to stream 1"); + { + // her rows as they now sit in stream 1, read back raw, against the bytes that were saved + llama_kv_stream_blocks back; + require(fenced(ctx) && kv->stream_save(1, back) == llama_kv_stream_move::done, "read stream 1 back"); + bool rows_equal = back.n_rows == blocks.n_rows; + for (size_t i = 0; rows_equal && i < back.k.size(); ++i) { + rows_equal = back.k[i] == blocks.k[i] && back.v[i] == blocks.v[i]; + } + fprintf(stderr, "stream 1 rows after load equal the saved bytes: %d (layers %zu)\n", rows_equal ? 1 : 0, back.k.size()); + require(fenced(ctx) && kv->stream_load(1, back) == llama_kv_stream_move::done, "put them back"); + } + require(llama_memory_seq_pos_max(llama_get_memory(ctx), 0) == n_prompt - 1, "her sequence holds her prompt"); + require(llama_memory_seq_pos_max(llama_get_memory(ctx), 1) < 0, "sequence 1 now maps to the empty stream 0"); + dump_cells("moved, before decode", 0); + const std::vector moved = next_logits(ctx, 0, next, n_prompt); + dump_cells("moved, after decode", 0); + require(moved.size() == reference.size(), "same vocabulary"); + report("moved to stream 1", reference, moved); + const bool moved_exact = std::memcmp(moved.data(), reference.data(), moved.size() * sizeof(float)) == 0; + + // bisection variants, each from a cleared cache with the identity mapping + auto reset = [&]() { + llama_memory_clear(llama_get_memory(ctx), true); + require(kv->stream_bind(0, 0) == llama_kv_stream_move::done, "identity bind 0"); + require(kv->stream_bind(1, 1) == llama_kv_stream_move::done, "identity bind 1"); + }; + auto prompt_on = [&](llama_seq_id seq) { + llama_batch b = llama_batch_init(n_prompt, 0, 1); + for (int i = 0; i < n_prompt; ++i) { + common_batch_add(b, 1 + (i * 7) % 300, i, { seq }, false); + } + require(llama_decode(ctx, b) == 0, "decode the prompt"); + llama_batch_free(b); + }; + { // X1: move to stream 1 + bind, without occupying stream 1 first + reset(); + prompt_on(0); + llama_kv_stream_blocks x; + require(fenced(ctx) && kv->stream_save(0, x) == llama_kv_stream_move::done, "X1 save"); + require(fenced(ctx) && kv->stream_load(1, x) == llama_kv_stream_move::done, "X1 load"); + require(kv->stream_bind(0, 1) == llama_kv_stream_move::done, "X1 bind"); + report("X1 move+bind, no occupy", reference, next_logits(ctx, 0, next, n_prompt)); + } + { // X3: mirror: native on seq 1 / stream 1, moved to stream 0, seq 1 bound to stream 0 + reset(); + prompt_on(1); + llama_kv_stream_blocks x; + require(fenced(ctx) && kv->stream_save(1, x) == llama_kv_stream_move::done, "X3 save"); + require(fenced(ctx) && kv->stream_load(0, x) == llama_kv_stream_move::done, "X3 load"); + require(kv->stream_bind(1, 0) == llama_kv_stream_move::done, "X3 bind"); + report("X3 mirror stream1->stream0", reference, next_logits(ctx, 1, next, n_prompt)); + } + { // X4: in place, two tokens; then moved, two tokens: does the second token differ too? + reset(); + prompt_on(0); + next_logits(ctx, 0, next, n_prompt); + const std::vector in_place_2 = next_logits(ctx, 0, next + 1, n_prompt + 1); + reset(); + prompt_on(0); + llama_kv_stream_blocks x; + require(fenced(ctx) && kv->stream_save(0, x) == llama_kv_stream_move::done, "X4 save"); + require(fenced(ctx) && kv->stream_load(1, x) == llama_kv_stream_move::done, "X4 load"); + require(kv->stream_bind(0, 1) == llama_kv_stream_move::done, "X4 bind"); + report("X4 first token after move", reference, next_logits(ctx, 0, next, n_prompt)); + report("X4 second token after move", in_place_2, next_logits(ctx, 0, next + 1, n_prompt + 1)); + } + require(moved_exact, "her next-token logits are byte-identical after the move"); + + fprintf(stderr, "test-kv-stream-blocks: ok (%u rows moved raw)\n", (unsigned) n_prompt); + return 0; +} From 1770577a2ef334c1027ef782a6ce5e78818b075e Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 21:44:55 -0600 Subject: [PATCH 02/28] memory: a persona's whole hybrid state moves raw (attention stream + recurrent rows), byte-identical (CONTINUUM-ENGINE 4.14) llama_memory_recurrent::seq_save/seq_load copy her row in every snapshot group (live + n_rs_seq rollback groups) raw and carry her cell record (pos, rs_idx); a load takes any free cell and sets her tail there (her sequence id is kept; nothing recomputed). llama_memory_hybrid:: persona_save/persona_load compose it with the attention stream move and bind. test-persona-blocks (Metal, M5, tiny random qwen35moe from test-llama-archs -s 42): her first and second token after the move byte-identical (max|diff| 0). Not exercised here: rollback groups (n_rs_seq = 0 without an MTP draft). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- src/llama-memory-hybrid.cpp | 11 ++++ src/llama-memory-hybrid.h | 12 ++++ src/llama-memory-recurrent.cpp | 86 +++++++++++++++++++++++++++ src/llama-memory-recurrent.h | 24 ++++++++ tests/CMakeLists.txt | 4 ++ tests/test-persona-blocks.cpp | 102 +++++++++++++++++++++++++++++++++ 6 files changed, 239 insertions(+) create mode 100644 tests/test-persona-blocks.cpp diff --git a/src/llama-memory-hybrid.cpp b/src/llama-memory-hybrid.cpp index 6cb6faee3cf9..116691a6df38 100644 --- a/src/llama-memory-hybrid.cpp +++ b/src/llama-memory-hybrid.cpp @@ -211,6 +211,17 @@ void llama_memory_hybrid::state_read(llama_io_read_i & io, llama_seq_id seq_id, mem_recr->state_read(io, seq_id, flags); } +bool llama_memory_hybrid::persona_save(llama_seq_id seq_id, llama_persona_blocks & out) { + return mem_attn->stream_save(mem_attn->seq_stream(seq_id), out.kv) == llama_kv_stream_move::done && + mem_recr->seq_save(seq_id, out.rs) == llama_rs_seq_move::done; +} + +bool llama_memory_hybrid::persona_load(llama_seq_id seq_id, uint32_t s, llama_persona_blocks & in) { + return mem_attn->stream_load(s, in.kv) == llama_kv_stream_move::done && + mem_attn->stream_bind(seq_id, s) == llama_kv_stream_move::done && + mem_recr->seq_load(seq_id, in.rs) == llama_rs_seq_move::done; +} + llama_kv_cache * llama_memory_hybrid::get_mem_attn() const { return mem_attn.get(); } diff --git a/src/llama-memory-hybrid.h b/src/llama-memory-hybrid.h index 593ff802c1f9..88956de0ef97 100644 --- a/src/llama-memory-hybrid.h +++ b/src/llama-memory-hybrid.h @@ -16,6 +16,13 @@ // utilizes instances of llama_memory_recurrent and llama_kv_cache to // support models where each layer may be either attention-based or recurrent +// Continuum fork (CONTINUUM-ENGINE 4.14): a persona out of the hybrid pool: her attention stream's rows and cells, and +// her recurrent rows and record, all raw. +struct llama_persona_blocks { + llama_kv_stream_blocks kv; + llama_rs_seq_blocks rs; +}; + class llama_memory_hybrid : public llama_memory_i { public: llama_memory_hybrid( @@ -87,6 +94,11 @@ class llama_memory_hybrid : public llama_memory_i { llama_kv_cache * get_mem_attn() const; + // her whole state out of her stream and cell (both left empty), and back into empty stream `s` bound to her own + // sequence id. FENCE: the caller completes the context's queued device work first. + bool persona_save(llama_seq_id seq_id, llama_persona_blocks & out); + bool persona_load(llama_seq_id seq_id, uint32_t s, llama_persona_blocks & in); + uint32_t seq_stream(llama_seq_id seq_id) const override { return mem_attn->seq_stream(seq_id); } llama_memory_recurrent * get_mem_recr() const; diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp index 208c9d0d557b..cfee7d99a749 100644 --- a/src/llama-memory-recurrent.cpp +++ b/src/llama-memory-recurrent.cpp @@ -392,6 +392,92 @@ llama_pos llama_memory_recurrent::seq_pos_max(llama_seq_id seq_id) const { return result; } +llama_rs_seq_move llama_memory_recurrent::seq_save(llama_seq_id seq_id, llama_rs_seq_blocks & out) { + if (seq_id < 0 || (uint32_t) seq_id >= size || (uint32_t) seq_id >= n_seq_max) { + return llama_rs_seq_move::invalid_seq; + } + const int32_t tail = cells[seq_id].tail; + out.has_state = tail >= 0; + out.r.assign(r_l.size(), {}); + out.s.assign(s_l.size(), {}); + if (!out.has_state) { + return llama_rs_seq_move::done; + } + auto & cell = cells[tail]; + if (cell.seq_id.size() != 1) { + return llama_rs_seq_move::shared_cell; + } + const uint32_t n_groups = 1 + n_rs_seq; + for (size_t il = 0; il < r_l.size(); ++il) { + for (auto [src, dst] : { std::make_pair(r_l[il], &out.r[il]), std::make_pair(s_l[il], &out.s[il]) }) { + if (src == nullptr) { + continue; + } + const size_t row = ggml_row_size(src->type, src->ne[0]); + dst->resize(row * n_groups); + for (uint32_t g = 0; g < n_groups; ++g) { + ggml_backend_tensor_get(src, dst->data() + g * row, (size_t) (g * size + tail) * src->nb[1], row); + } + } + } + out.pos = cell.pos; + out.rs_idx = rs_idx[seq_id]; + + // her cell leaves with her + cell.seq_id.clear(); + cell.pos = -1; + cell.src = -1; + cell.src0 = -1; + cells[seq_id].tail = -1; + rs_idx[seq_id] = 0; + used -= 1; + head = std::min(head, (uint32_t) tail); + return llama_rs_seq_move::done; +} + +llama_rs_seq_move llama_memory_recurrent::seq_load(llama_seq_id seq_id, const llama_rs_seq_blocks & in) { + if (seq_id < 0 || (uint32_t) seq_id >= size || (uint32_t) seq_id >= n_seq_max) { + return llama_rs_seq_move::invalid_seq; + } + if (cells[seq_id].tail >= 0) { + return llama_rs_seq_move::seq_holds_state; + } + if (!in.has_state) { + return llama_rs_seq_move::done; + } + int32_t cell_id = -1; + for (uint32_t i = 0; i < size; ++i) { + if (cells[i].is_empty() && cells[i].pos < 0) { + cell_id = (int32_t) i; + break; + } + } + if (cell_id < 0) { + return llama_rs_seq_move::no_free_cell; + } + const uint32_t n_groups = 1 + n_rs_seq; + for (size_t il = 0; il < r_l.size(); ++il) { + for (auto [dst, src] : { std::make_pair(r_l[il], &in.r[il]), std::make_pair(s_l[il], &in.s[il]) }) { + if (dst == nullptr || src->empty()) { + continue; + } + const size_t row = ggml_row_size(dst->type, dst->ne[0]); + for (uint32_t g = 0; g < n_groups; ++g) { + ggml_backend_tensor_set(dst, src->data() + g * row, (size_t) (g * size + cell_id) * dst->nb[1], row); + } + } + } + auto & cell = cells[cell_id]; + cell.pos = in.pos; + cell.src = cell_id; + cell.src0 = cell_id; + cell.seq_id.insert(seq_id); + cells[seq_id].tail = cell_id; + rs_idx[seq_id] = in.rs_idx; + used += 1; + return llama_rs_seq_move::done; +} + void llama_memory_recurrent::set_rs_idx(llama_seq_id seq_id, uint32_t idx) { if (seq_id < 0) { std::fill(rs_idx.begin(), rs_idx.end(), 0); diff --git a/src/llama-memory-recurrent.h b/src/llama-memory-recurrent.h index 3cbc682a88de..b9c44604f0b9 100644 --- a/src/llama-memory-recurrent.h +++ b/src/llama-memory-recurrent.h @@ -14,6 +14,25 @@ // TODO: extract the cache state used for graph computation into llama_memory_recurrent_context_i // see the implementation of llama_kv_cache_context_i for an example how to do it +// Continuum fork (CONTINUUM-ENGINE 4.14): a persona's recurrent state, out of the pool: per layer, her row in every +// snapshot group (live group 0, then the n_rs_seq rollback groups) copied raw, plus her cell's small record. Restoring +// it into any free cell is these raw copies and that record; nothing is recomputed. +struct llama_rs_seq_blocks { + bool has_state = false; + llama_pos pos = -1; + uint32_t rs_idx = 0; // her pending rollback index + std::vector> r; // per layer: (1 + n_rs_seq) rows of r, group-major + std::vector> s; // per layer: (1 + n_rs_seq) rows of s, group-major +}; + +enum class llama_rs_seq_move { + done, + invalid_seq, // seq_id out of range + seq_holds_state, // a load requires her sequence to hold no state + shared_cell, // her state cell is shared with another sequence: not hers alone to move + no_free_cell, // no free cell to load into +}; + class llama_memory_recurrent : public llama_memory_i { public: llama_memory_recurrent( @@ -85,6 +104,11 @@ class llama_memory_recurrent : public llama_memory_i { void set_rs_idx(llama_seq_id seq_id, uint32_t idx); + // Continuum fork (CONTINUUM-ENGINE 4.14): her state out (rows copied raw, her cell freed) and in (raw rows into a + // free cell, her record restored). FENCE: the caller completes the context's queued device work first. + llama_rs_seq_move seq_save(llama_seq_id seq_id, llama_rs_seq_blocks & out); + llama_rs_seq_move seq_load(llama_seq_id seq_id, const llama_rs_seq_blocks & in); + // an undo of a draft is pending on this sequence: its next read takes a snapshot group, not the // live state (group 0) a training graph reads and writes (llm_graph_context::rs_keep) bool rollback_pending(llama_seq_id seq_id) const { diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 548cd7258f49..2f6d189cb97c 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -359,6 +359,10 @@ set_tests_properties(test-state-restore-streams PROPERTIES FIXTURES_REQUIRED tes llama_build_and_test(test-kv-stream-blocks.cpp LABEL "model" ARGS -m "${MODEL_DEST}") set_tests_properties(test-kv-stream-blocks PROPERTIES FIXTURES_REQUIRED test-download-model) +# a persona's whole hybrid state (attention stream + recurrent rows) moved raw is byte-identical (CONTINUUM-ENGINE 4.14); +# takes a hybrid model, e.g. one written by `test-llama-archs -a qwen35moe -o DIR` +llama_build(test-persona-blocks.cpp) + # Test state save/load functionality llama_build_and_test(test-save-load-state.cpp LABEL "model" ARGS -m "${MODEL_DEST}") set_tests_properties(test-save-load-state PROPERTIES FIXTURES_REQUIRED test-download-model) diff --git a/tests/test-persona-blocks.cpp b/tests/test-persona-blocks.cpp new file mode 100644 index 000000000000..315745f80966 --- /dev/null +++ b/tests/test-persona-blocks.cpp @@ -0,0 +1,102 @@ +// what this catches: moving a persona's WHOLE state on a hybrid model (attention stream + recurrent rows, +// llama_memory_hybrid::persona_save / persona_load, CONTINUUM-ENGINE 4.14) changing her state: after her state goes +// out of stream 0 and her recurrent cell to host memory and back into stream 1 bound to her own sequence id, her next +// two tokens' logits must be byte-identical to decoding them in place. Nothing is recomputed; a lost or misplaced row +// or record changes the logits. The model argument is a hybrid (e.g. a tiny random qwen35moe from +// `test-llama-archs -a qwen35moe -o DIR`). + +#include "arg.h" +#include "common.h" +#include "llama.h" + +#include "../src/llama-memory-hybrid.h" + +#include +#include +#include +#include +#include +#include + +static void require(bool condition, const char * message) { + if (!condition) { + fprintf(stderr, "FAILED: %s\n", message); + std::exit(1); + } +} + +static std::vector next_logits(llama_context * ctx, llama_seq_id seq, llama_token token, llama_pos pos) { + llama_batch b = llama_batch_init(1, 0, 1); + common_batch_add(b, token, pos, { seq }, true); + require(llama_decode(ctx, b) == 0, "decode the next token"); + const int n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(llama_get_model(ctx))); + const float * l = llama_get_logits_ith(ctx, 0); + std::vector out(l, l + n_vocab); + llama_batch_free(b); + return out; +} + +static bool same(const char * what, const std::vector & a, const std::vector & b) { + float max_diff = 0.0f; + for (size_t i = 0; i < a.size(); ++i) { + max_diff = std::max(max_diff, std::fabs(a[i] - b[i])); + } + const bool identical = a.size() == b.size() && std::memcmp(a.data(), b.data(), a.size() * sizeof(float)) == 0; + fprintf(stderr, "%s: byte-identical=%d max|diff|=%g\n", what, identical ? 1 : 0, max_diff); + return identical; +} + +int main(int argc, char ** argv) { + common_params params; + params.kv_unified = false; // one attention stream per sequence + params.n_parallel = 2; + params.n_ctx = 512; + params.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_ENABLED; // V rows contiguous + common_init(); + if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_COMMON)) { + return 1; + } + ggml_backend_load_all(); + common_init_result_ptr init = common_init_from_params(params); + llama_context * ctx = init->context(); + require(ctx != nullptr, "context"); + auto * mem = dynamic_cast(llama_get_memory(ctx)); + require(mem != nullptr, "a hybrid memory (attention + recurrent)"); + const int n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(llama_get_model(ctx))); + + const int n_prompt = 24; + auto prompt_on = [&](llama_seq_id seq) { + llama_batch b = llama_batch_init(n_prompt, 0, 1); + for (int i = 0; i < n_prompt; ++i) { + common_batch_add(b, 1 + (i * 7) % (n_vocab - 1), i, { seq }, false); + } + require(llama_decode(ctx, b) == 0, "decode her prompt"); + llama_batch_free(b); + }; + const llama_token t1 = 3 % n_vocab; + const llama_token t2 = 5 % n_vocab; + + // the reference: her prompt, then her next two tokens decoded in place + prompt_on(0); + const std::vector ref1 = next_logits(ctx, 0, t1, n_prompt); + const std::vector ref2 = next_logits(ctx, 0, t2, n_prompt + 1); + + // the same prompt again from a clear memory, then her whole state moved out and into stream 1, bound to her id + llama_memory_clear(llama_get_memory(ctx), true); + prompt_on(0); + llama_synchronize(ctx); // the completion fence before raw copies + llama_persona_blocks blocks; + require(mem->persona_save(0, blocks), "her state out"); + require(blocks.rs.has_state, "she has recurrent state"); + require(llama_memory_seq_pos_max(llama_get_memory(ctx), 0) < 0, "nothing of her is left in the pool"); + require(mem->persona_load(0, 1, blocks), "her state into stream 1 and a free recurrent cell"); + require(llama_memory_seq_pos_max(llama_get_memory(ctx), 0) == n_prompt - 1, "her sequence holds her prompt again"); + + const bool ok1 = same("first token after the move", ref1, next_logits(ctx, 0, t1, n_prompt)); + const bool ok2 = same("second token after the move", ref2, next_logits(ctx, 0, t2, n_prompt + 1)); + require(ok1 && ok2, "her logits are byte-identical after her whole state moved"); + + fprintf(stderr, "test-persona-blocks: ok (%zu attention layers, %zu recurrent layers, moved raw)\n", + blocks.kv.k.size(), blocks.rs.r.size()); + return 0; +} From a1c5c8eab6a15ff825d240373062a72dee965be0 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 21:50:01 -0600 Subject: [PATCH 03/28] memory: one two-phase persona move (check reserves, commit cannot fail), fenced by the context (Codex's #147 review) - llama_memory_i gains persona_prepare / persona_check_save / persona_check_load (const: every condition decided, destination reserved) and persona_commit_save / persona_commit_load (raw copies and record writes only). KV cache, recurrent memory and hybrid implement it; the hybrid checks both halves before either commits, so a refusal never splits a persona. - llama_context::persona_save / persona_load are the one entry point and take the completion fence (synchronize) themselves. - No cell walk on a move: her blocks hold an empty, stream-sized cells object prepared once (persona_prepare); a save checks it in O(1) (used set, has_shift flag) and refuses cells_not_prepared, never resets. - Loads validate layer counts and every per-layer byte length (KV rows; recurrent rows x groups) before the first write: layout_mismatch. - Recurrent destination: reserved in check_load by a search over the memory's cells (one per sequence slot: bounded by the slot count, not context length). - One typed outcome, llama_persona_move, in llama-persona-blocks.h. - test-persona-blocks replaces test-kv-stream-blocks; every variant is asserted. Measured (Metal, M5): test-persona-blocks passes on stories15M (ctest) and on a tiny random qwen35moe (test-llama-archs -s 42): move to another stream, mirror, same-stream round trip, and two live personas exchanging streams each byte-identical on two tokens; refusals (unprepared save, load over an occupied stream, layout mismatch) typed and leave every persona unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- src/llama-context.cpp | 31 +++++ src/llama-context.h | 7 + src/llama-kv-cache.cpp | 136 +++++++++++-------- src/llama-kv-cache.h | 40 ++---- src/llama-memory-hybrid.cpp | 30 ++++- src/llama-memory-hybrid.h | 18 +-- src/llama-memory-recurrent.cpp | 98 +++++++++----- src/llama-memory-recurrent.h | 32 ++--- src/llama-memory.cpp | 17 +++ src/llama-memory.h | 23 ++++ src/llama-persona-blocks.h | 58 +++++++++ tests/CMakeLists.txt | 11 +- tests/test-kv-stream-blocks.cpp | 224 -------------------------------- tests/test-persona-blocks.cpp | 206 ++++++++++++++++++++--------- 14 files changed, 481 insertions(+), 450 deletions(-) create mode 100644 src/llama-persona-blocks.h delete mode 100644 tests/test-kv-stream-blocks.cpp diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 8884f065bcd0..52c459bf74b5 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -2567,6 +2567,37 @@ llm_graph_type llama_context::graph_type() const { throw std::runtime_error("Unsupported ctx type"); } +llama_persona_move llama_context::persona_prepare(llama_persona_blocks & blocks) const { + return memory ? memory->persona_prepare(blocks) : llama_persona_move::unsupported; +} + +llama_persona_move llama_context::persona_save(llama_seq_id seq_id, llama_persona_blocks & out) { + if (!memory) { + return llama_persona_move::unsupported; + } + synchronize(); // a decode returns before its writes land; the raw copies read the same device memory + const llama_persona_move checked = memory->persona_check_save(seq_id, out); + if (checked != llama_persona_move::done) { + return checked; + } + memory->persona_commit_save(seq_id, out); + return llama_persona_move::done; +} + +llama_persona_move llama_context::persona_load(llama_seq_id seq_id, uint32_t stream, llama_persona_blocks & in) { + if (!memory) { + return llama_persona_move::unsupported; + } + synchronize(); + llama_persona_slot slot; + const llama_persona_move checked = memory->persona_check_load(seq_id, stream, in, slot); + if (checked != llama_persona_move::done) { + return checked; + } + memory->persona_commit_load(seq_id, slot, in); + return llama_persona_move::done; +} + llm_graph_params llama_context::graph_params( llm_graph_result * res, const llama_ubatch & ubatch, diff --git a/src/llama-context.h b/src/llama-context.h index 86bb220f765f..30e7393c6e81 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -57,6 +57,13 @@ struct llama_context { void sched_reserve(); void synchronize(); + + // Continuum fork (CONTINUUM-ENGINE 4.14): move a persona's state between the memory and host memory. Fences the + // queued device work, checks every condition (reserving the destination), then commits raw copies; a refusal + // changes nothing. + llama_persona_move persona_prepare(llama_persona_blocks & blocks) const; + llama_persona_move persona_save(llama_seq_id seq_id, llama_persona_blocks & out); + llama_persona_move persona_load(llama_seq_id seq_id, uint32_t stream, llama_persona_blocks & in); bool opt_state_write_initial(FILE * optimizer, const char * binding); bool opt_state_write(FILE * optimizer, const char * binding); bool opt_shadow_state_write(const llama_adapter_lora * shadow, FILE * optimizer, const char * binding); diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index 1adcf1e17ece..e84acc922d8c 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -1231,87 +1231,115 @@ ggml_tensor * llama_kv_cache::get_k_storage(int32_t il) const { return layers[ikv].k; } -llama_kv_stream_move llama_kv_cache::stream_save(uint32_t s, llama_kv_stream_blocks & out) { - if (s >= n_stream || n_stream == 1) { - return llama_kv_stream_move::no_such_stream; +// an empty, stream-sized cells object: O(1) (used is a set; has_shift a flag); freed cells hold no sequence position +static bool cells_prepared(const llama_kv_cells & cells, uint32_t size) { + return cells.size() == size && cells.get_used() == 0 && !cells.get_has_shift(); +} + +llama_persona_move llama_kv_cache::persona_prepare(llama_persona_blocks & blocks) const { + if (n_stream == 1) { + return llama_persona_move::no_such_stream; + } + blocks.kv.cells.resize(get_size()); // once per persona, at her creation + blocks.kv.k.resize(layers.size()); + blocks.kv.v.resize(layers.size()); + return llama_persona_move::done; +} + +llama_persona_move llama_kv_cache::persona_check_save(llama_seq_id seq_id, const llama_persona_blocks & out) const { + if (n_stream == 1) { + return llama_persona_move::no_such_stream; + } + if (seq_id < 0 || (size_t) seq_id >= seq_to_stream.size()) { + return llama_persona_move::invalid_seq; } if (v_trans) { - return llama_kv_stream_move::transposed_v; + return llama_persona_move::transposed_v; + } + if (!cells_prepared(out.kv.cells, get_size()) || out.kv.k.size() != layers.size() || out.kv.v.size() != layers.size()) { + return llama_persona_move::cells_not_prepared; } + return llama_persona_move::done; +} + +void llama_kv_cache::persona_commit_save(llama_seq_id seq_id, llama_persona_blocks & out) { + const uint32_t s = seq_to_stream[seq_id]; auto & cells = v_cells[s]; const uint32_t n_rows = cells.used_max_p1(); - out.n_rows = n_rows; - out.k.resize(layers.size()); - out.v.resize(layers.size()); + out.kv.n_rows = n_rows; for (size_t i = 0; i < layers.size(); ++i) { const auto & layer = layers[i]; const size_t k_bytes = ggml_row_size(layer.k->type, layer.k->ne[0]) * n_rows; - out.k[i].resize(k_bytes); + out.kv.k[i].resize(k_bytes); if (k_bytes > 0) { - ggml_backend_tensor_get(layer.k_stream[s], out.k[i].data(), 0, k_bytes); + ggml_backend_tensor_get(layer.k_stream[s], out.kv.k[i].data(), 0, k_bytes); } - if (layer.v) { - const size_t v_bytes = ggml_row_size(layer.v->type, layer.v->ne[0]) * n_rows; - out.v[i].resize(v_bytes); - if (v_bytes > 0) { - ggml_backend_tensor_get(layer.v_stream[s], out.v[i].data(), 0, v_bytes); - } - } else { - out.v[i].clear(); + const size_t v_bytes = layer.v ? ggml_row_size(layer.v->type, layer.v->ne[0]) * n_rows : 0; + out.kv.v[i].resize(v_bytes); + if (v_bytes > 0) { + ggml_backend_tensor_get(layer.v_stream[s], out.kv.v[i].data(), 0, v_bytes); } } - // her metadata leaves with her by swap; the stream takes an empty one of its own size - if (out.cells.size() != cells.size()) { - out.cells.resize(cells.size()); - } else { - out.cells.reset(); - } - std::swap(out.cells, cells); + std::swap(out.kv.cells, cells); // hers out; the stream takes the prepared empty object v_heads[s] = 0; - return llama_kv_stream_move::done; } -llama_kv_stream_move llama_kv_cache::stream_bind(llama_seq_id seq, uint32_t s) { - if (n_stream == 1 || s >= n_stream || seq < 0 || (size_t) seq >= seq_to_stream.size()) { - return llama_kv_stream_move::no_such_stream; +llama_persona_move llama_kv_cache::persona_check_load(llama_seq_id seq_id, uint32_t stream, + const llama_persona_blocks & in, llama_persona_slot & slot) const { + if (n_stream == 1 || stream >= n_stream) { + return llama_persona_move::no_such_stream; } - const uint32_t old = seq_to_stream[seq]; - for (auto & st : seq_to_stream) { - if (st == s) { - st = old; // the sequence that held `s` takes her old stream - break; - } - } - seq_to_stream[seq] = s; - return llama_kv_stream_move::done; -} - -llama_kv_stream_move llama_kv_cache::stream_load(uint32_t s, llama_kv_stream_blocks & in) { - if (s >= n_stream || n_stream == 1) { - return llama_kv_stream_move::no_such_stream; + if (seq_id < 0 || (size_t) seq_id >= seq_to_stream.size()) { + return llama_persona_move::invalid_seq; } if (v_trans) { - return llama_kv_stream_move::transposed_v; + return llama_persona_move::transposed_v; } - auto & cells = v_cells[s]; - if (cells.get_used() != 0) { - return llama_kv_stream_move::stream_not_empty; + if (v_cells[stream].get_used() != 0) { + return llama_persona_move::stream_not_empty; } - if (in.n_rows > cells.size() || in.cells.size() != cells.size()) { - return llama_kv_stream_move::too_long; + if (v_cells[seq_to_stream[seq_id]].seq_pos_max(seq_id) >= 0) { + return llama_persona_move::seq_holds_state; + } + const auto & kv = in.kv; + if (kv.cells.size() != get_size() || kv.n_rows > get_size() || kv.cells.used_max_p1() > kv.n_rows || + kv.k.size() != layers.size() || kv.v.size() != layers.size()) { + return llama_persona_move::layout_mismatch; + } + for (size_t i = 0; i < layers.size(); ++i) { + const auto & layer = layers[i]; + const size_t k_bytes = ggml_row_size(layer.k->type, layer.k->ne[0]) * kv.n_rows; + const size_t v_bytes = layer.v ? ggml_row_size(layer.v->type, layer.v->ne[0]) * kv.n_rows : 0; + if (kv.k[i].size() != k_bytes || kv.v[i].size() != v_bytes) { + return llama_persona_move::layout_mismatch; + } } + slot.stream = stream; + return llama_persona_move::done; +} + +void llama_kv_cache::persona_commit_load(llama_seq_id seq_id, const llama_persona_slot & slot, llama_persona_blocks & in) { + const uint32_t s = slot.stream; for (size_t i = 0; i < layers.size(); ++i) { const auto & layer = layers[i]; - if (!in.k[i].empty()) { - ggml_backend_tensor_set(layer.k_stream[s], in.k[i].data(), 0, in.k[i].size()); + if (!in.kv.k[i].empty()) { + ggml_backend_tensor_set(layer.k_stream[s], in.kv.k[i].data(), 0, in.kv.k[i].size()); } - if (layer.v && !in.v[i].empty()) { - ggml_backend_tensor_set(layer.v_stream[s], in.v[i].data(), 0, in.v[i].size()); + if (!in.kv.v[i].empty()) { + ggml_backend_tensor_set(layer.v_stream[s], in.kv.v[i].data(), 0, in.kv.v[i].size()); } } - std::swap(in.cells, cells); // her metadata back in; `in` keeps the stream's empty cells for reuse + std::swap(in.kv.cells, v_cells[s]); // hers in; her blocks keep the stream's empty object for her next save v_heads[s] = 0; - return llama_kv_stream_move::done; + // bind her own sequence id to stream s; the sequence that held s takes her old stream (both empty of others) + const uint32_t old = seq_to_stream[seq_id]; + for (auto & st : seq_to_stream) { + if (st == s) { + st = old; + break; + } + } + seq_to_stream[seq_id] = s; } const llama_kv_cells & llama_kv_cache::get_cells(llama_seq_id seq_id) const { diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h index e889c247cc06..ae8fec0e1395 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -17,26 +17,6 @@ struct llama_context; // llama_kv_cache // -// Continuum fork (CONTINUUM-ENGINE 4.14): a persona's KV, out of the pool: per KV layer, her K and V rows of one stream -// copied raw (the rows she uses, in the stream's own row layout), and her stream's cell metadata OWNED here (moved by -// swap, never copied or rebuilt). Moving a persona between a stream and host memory is these raw copies plus one swap; -// nothing walks a cell, serializes or recomputes. -struct llama_kv_stream_blocks { - uint32_t n_rows = 0; // rows she uses (the stream's used_max_p1 when saved) - std::vector> k; // per KV layer: n_rows rows of K - std::vector> v; // per KV layer: n_rows rows of V (empty for a layer without V) - llama_kv_cells cells; // her cell metadata; sized to the stream when first used -}; - -// the outcome of moving a persona's KV between a stream and host memory -enum class llama_kv_stream_move { - done, - no_such_stream, // s >= n_stream (or the cache is unified: one stream holds every sequence) - transposed_v, // V is stored transposed (flash attention off): her V rows are not contiguous; not supported - stream_not_empty, // a load requires an empty stream - too_long, // her rows exceed the stream's size -}; - class llama_kv_cache : public llama_memory_i { public: struct stream_copy_info { @@ -195,17 +175,15 @@ class llama_kv_cache : public llama_memory_i { const llama_kv_cells & get_cells(llama_seq_id seq_id) const; - // Continuum fork (CONTINUUM-ENGINE 4.14): stream `s` -> `out` (her rows copied raw, her cells swapped out: the - // stream is left empty), and `in` -> empty stream `s` (rows copied raw, cells swapped in). A per-sequence stream - // exists only with unified KV off. - // FENCE: the caller must have completed the context's queued device work first (llama_synchronize): a decode - // returns before its KV writes land, and these copies touch the same device memory. - llama_kv_stream_move stream_save(uint32_t s, llama_kv_stream_blocks & out); - llama_kv_stream_move stream_load(uint32_t s, llama_kv_stream_blocks & in); - // bind sequence `seq` (a persona's own, stable id) to physical stream `s`: the map stays a permutation (the - // sequence that held `s` takes `seq`'s old stream). Her cells keep their sequence id, so nothing is retagged. - // Between batches only: every lookup reads the map at call time. - llama_kv_stream_move stream_bind(llama_seq_id seq, uint32_t s); + // Continuum fork (CONTINUUM-ENGINE 4.14): her used rows of her stream copied raw per layer, her cells exchanged by + // swap with an already-empty object (never reset or walked), her own sequence id bound to the stream she lands on + // (seq_to_stream stays a permutation; her cells are never retagged). Requires unified KV off and flash attention. + llama_persona_move persona_prepare(llama_persona_blocks & blocks) const override; + llama_persona_move persona_check_save(llama_seq_id seq_id, const llama_persona_blocks & out) const override; + llama_persona_move persona_check_load(llama_seq_id seq_id, uint32_t stream, const llama_persona_blocks & in, + llama_persona_slot & slot) const override; + void persona_commit_save(llama_seq_id seq_id, llama_persona_blocks & out) override; + void persona_commit_load(llama_seq_id seq_id, const llama_persona_slot & slot, llama_persona_blocks & in) override; uint32_t seq_stream(llama_seq_id seq_id) const override { return seq_to_stream[seq_id]; } diff --git a/src/llama-memory-hybrid.cpp b/src/llama-memory-hybrid.cpp index 116691a6df38..2c03c5c156f5 100644 --- a/src/llama-memory-hybrid.cpp +++ b/src/llama-memory-hybrid.cpp @@ -211,15 +211,31 @@ void llama_memory_hybrid::state_read(llama_io_read_i & io, llama_seq_id seq_id, mem_recr->state_read(io, seq_id, flags); } -bool llama_memory_hybrid::persona_save(llama_seq_id seq_id, llama_persona_blocks & out) { - return mem_attn->stream_save(mem_attn->seq_stream(seq_id), out.kv) == llama_kv_stream_move::done && - mem_recr->seq_save(seq_id, out.rs) == llama_rs_seq_move::done; +llama_persona_move llama_memory_hybrid::persona_prepare(llama_persona_blocks & blocks) const { + const llama_persona_move attn = mem_attn->persona_prepare(blocks); + return attn != llama_persona_move::done ? attn : mem_recr->persona_prepare(blocks); } -bool llama_memory_hybrid::persona_load(llama_seq_id seq_id, uint32_t s, llama_persona_blocks & in) { - return mem_attn->stream_load(s, in.kv) == llama_kv_stream_move::done && - mem_attn->stream_bind(seq_id, s) == llama_kv_stream_move::done && - mem_recr->seq_load(seq_id, in.rs) == llama_rs_seq_move::done; +llama_persona_move llama_memory_hybrid::persona_check_save(llama_seq_id seq_id, const llama_persona_blocks & out) const { + const llama_persona_move attn = mem_attn->persona_check_save(seq_id, out); + return attn != llama_persona_move::done ? attn : mem_recr->persona_check_save(seq_id, out); +} + +llama_persona_move llama_memory_hybrid::persona_check_load(llama_seq_id seq_id, uint32_t stream, + const llama_persona_blocks & in, llama_persona_slot & slot) const { + const llama_persona_move attn = mem_attn->persona_check_load(seq_id, stream, in, slot); + return attn != llama_persona_move::done ? attn : mem_recr->persona_check_load(seq_id, stream, in, slot); +} + +void llama_memory_hybrid::persona_commit_save(llama_seq_id seq_id, llama_persona_blocks & out) { + mem_attn->persona_commit_save(seq_id, out); + mem_recr->persona_commit_save(seq_id, out); +} + +void llama_memory_hybrid::persona_commit_load(llama_seq_id seq_id, const llama_persona_slot & slot, + llama_persona_blocks & in) { + mem_attn->persona_commit_load(seq_id, slot, in); + mem_recr->persona_commit_load(seq_id, slot, in); } llama_kv_cache * llama_memory_hybrid::get_mem_attn() const { diff --git a/src/llama-memory-hybrid.h b/src/llama-memory-hybrid.h index 88956de0ef97..41a57bc3813d 100644 --- a/src/llama-memory-hybrid.h +++ b/src/llama-memory-hybrid.h @@ -16,13 +16,6 @@ // utilizes instances of llama_memory_recurrent and llama_kv_cache to // support models where each layer may be either attention-based or recurrent -// Continuum fork (CONTINUUM-ENGINE 4.14): a persona out of the hybrid pool: her attention stream's rows and cells, and -// her recurrent rows and record, all raw. -struct llama_persona_blocks { - llama_kv_stream_blocks kv; - llama_rs_seq_blocks rs; -}; - class llama_memory_hybrid : public llama_memory_i { public: llama_memory_hybrid( @@ -94,10 +87,13 @@ class llama_memory_hybrid : public llama_memory_i { llama_kv_cache * get_mem_attn() const; - // her whole state out of her stream and cell (both left empty), and back into empty stream `s` bound to her own - // sequence id. FENCE: the caller completes the context's queued device work first. - bool persona_save(llama_seq_id seq_id, llama_persona_blocks & out); - bool persona_load(llama_seq_id seq_id, uint32_t s, llama_persona_blocks & in); + // her whole state: both halves are checked (and the destination reserved) before either commits + llama_persona_move persona_prepare(llama_persona_blocks & blocks) const override; + llama_persona_move persona_check_save(llama_seq_id seq_id, const llama_persona_blocks & out) const override; + llama_persona_move persona_check_load(llama_seq_id seq_id, uint32_t stream, const llama_persona_blocks & in, + llama_persona_slot & slot) const override; + void persona_commit_save(llama_seq_id seq_id, llama_persona_blocks & out) override; + void persona_commit_load(llama_seq_id seq_id, const llama_persona_slot & slot, llama_persona_blocks & in) override; uint32_t seq_stream(llama_seq_id seq_id) const override { return mem_attn->seq_stream(seq_id); } llama_memory_recurrent * get_mem_recr() const; diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp index cfee7d99a749..5c7fab04c6e0 100644 --- a/src/llama-memory-recurrent.cpp +++ b/src/llama-memory-recurrent.cpp @@ -392,25 +392,40 @@ llama_pos llama_memory_recurrent::seq_pos_max(llama_seq_id seq_id) const { return result; } -llama_rs_seq_move llama_memory_recurrent::seq_save(llama_seq_id seq_id, llama_rs_seq_blocks & out) { +llama_persona_move llama_memory_recurrent::persona_prepare(llama_persona_blocks & blocks) const { + blocks.rs.r.resize(r_l.size()); + blocks.rs.s.resize(s_l.size()); + return llama_persona_move::done; +} + +llama_persona_move llama_memory_recurrent::persona_check_save(llama_seq_id seq_id, const llama_persona_blocks & out) const { if (seq_id < 0 || (uint32_t) seq_id >= size || (uint32_t) seq_id >= n_seq_max) { - return llama_rs_seq_move::invalid_seq; + return llama_persona_move::invalid_seq; + } + if (out.rs.r.size() != r_l.size() || out.rs.s.size() != s_l.size()) { + return llama_persona_move::cells_not_prepared; } const int32_t tail = cells[seq_id].tail; - out.has_state = tail >= 0; - out.r.assign(r_l.size(), {}); - out.s.assign(s_l.size(), {}); - if (!out.has_state) { - return llama_rs_seq_move::done; + if (tail >= 0 && cells[tail].seq_id.size() != 1) { + return llama_persona_move::shared_cell; } - auto & cell = cells[tail]; - if (cell.seq_id.size() != 1) { - return llama_rs_seq_move::shared_cell; + return llama_persona_move::done; +} + +void llama_memory_recurrent::persona_commit_save(llama_seq_id seq_id, llama_persona_blocks & out) { + auto & rs = out.rs; + const int32_t tail = cells[seq_id].tail; + rs.has_state = tail >= 0; + if (!rs.has_state) { + for (auto & v : rs.r) { v.clear(); } + for (auto & v : rs.s) { v.clear(); } + return; } const uint32_t n_groups = 1 + n_rs_seq; for (size_t il = 0; il < r_l.size(); ++il) { - for (auto [src, dst] : { std::make_pair(r_l[il], &out.r[il]), std::make_pair(s_l[il], &out.s[il]) }) { + for (auto [src, dst] : { std::make_pair(r_l[il], &rs.r[il]), std::make_pair(s_l[il], &rs.s[il]) }) { if (src == nullptr) { + dst->clear(); continue; } const size_t row = ggml_row_size(src->type, src->ne[0]); @@ -420,45 +435,65 @@ llama_rs_seq_move llama_memory_recurrent::seq_save(llama_seq_id seq_id, llama_rs } } } - out.pos = cell.pos; - out.rs_idx = rs_idx[seq_id]; - + auto & cell = cells[tail]; + rs.pos = cell.pos; + rs.rs_idx = rs_idx[seq_id]; // her cell leaves with her cell.seq_id.clear(); - cell.pos = -1; - cell.src = -1; + cell.pos = -1; + cell.src = -1; cell.src0 = -1; cells[seq_id].tail = -1; rs_idx[seq_id] = 0; used -= 1; head = std::min(head, (uint32_t) tail); - return llama_rs_seq_move::done; } -llama_rs_seq_move llama_memory_recurrent::seq_load(llama_seq_id seq_id, const llama_rs_seq_blocks & in) { +llama_persona_move llama_memory_recurrent::persona_check_load(llama_seq_id seq_id, uint32_t stream, + const llama_persona_blocks & in, llama_persona_slot & slot) const { + (void) stream; // recurrent state is found through her sequence's tail, in any cell if (seq_id < 0 || (uint32_t) seq_id >= size || (uint32_t) seq_id >= n_seq_max) { - return llama_rs_seq_move::invalid_seq; + return llama_persona_move::invalid_seq; } if (cells[seq_id].tail >= 0) { - return llama_rs_seq_move::seq_holds_state; + return llama_persona_move::seq_holds_state; } - if (!in.has_state) { - return llama_rs_seq_move::done; + const auto & rs = in.rs; + slot.cell = -1; + if (!rs.has_state) { + return llama_persona_move::done; + } + if (rs.r.size() != r_l.size() || rs.s.size() != s_l.size()) { + return llama_persona_move::layout_mismatch; + } + const uint32_t n_groups = 1 + n_rs_seq; + for (size_t il = 0; il < r_l.size(); ++il) { + const size_t r_bytes = r_l[il] ? ggml_row_size(r_l[il]->type, r_l[il]->ne[0]) * n_groups : 0; + const size_t s_bytes = s_l[il] ? ggml_row_size(s_l[il]->type, s_l[il]->ne[0]) * n_groups : 0; + if (rs.r[il].size() != r_bytes || rs.s[il].size() != s_bytes) { + return llama_persona_move::layout_mismatch; + } } - int32_t cell_id = -1; for (uint32_t i = 0; i < size; ++i) { if (cells[i].is_empty() && cells[i].pos < 0) { - cell_id = (int32_t) i; - break; + slot.cell = (int32_t) i; + return llama_persona_move::done; } } - if (cell_id < 0) { - return llama_rs_seq_move::no_free_cell; + return llama_persona_move::no_free_cell; +} + +void llama_memory_recurrent::persona_commit_load(llama_seq_id seq_id, const llama_persona_slot & slot, + llama_persona_blocks & in) { + const auto & rs = in.rs; + if (!rs.has_state) { + return; } + const int32_t cell_id = slot.cell; const uint32_t n_groups = 1 + n_rs_seq; for (size_t il = 0; il < r_l.size(); ++il) { - for (auto [dst, src] : { std::make_pair(r_l[il], &in.r[il]), std::make_pair(s_l[il], &in.s[il]) }) { - if (dst == nullptr || src->empty()) { + for (auto [dst, src] : { std::make_pair(r_l[il], &rs.r[il]), std::make_pair(s_l[il], &rs.s[il]) }) { + if (dst == nullptr) { continue; } const size_t row = ggml_row_size(dst->type, dst->ne[0]); @@ -468,14 +503,13 @@ llama_rs_seq_move llama_memory_recurrent::seq_load(llama_seq_id seq_id, const ll } } auto & cell = cells[cell_id]; - cell.pos = in.pos; + cell.pos = rs.pos; cell.src = cell_id; cell.src0 = cell_id; cell.seq_id.insert(seq_id); cells[seq_id].tail = cell_id; - rs_idx[seq_id] = in.rs_idx; + rs_idx[seq_id] = rs.rs_idx; used += 1; - return llama_rs_seq_move::done; } void llama_memory_recurrent::set_rs_idx(llama_seq_id seq_id, uint32_t idx) { diff --git a/src/llama-memory-recurrent.h b/src/llama-memory-recurrent.h index b9c44604f0b9..64c278a7072c 100644 --- a/src/llama-memory-recurrent.h +++ b/src/llama-memory-recurrent.h @@ -14,25 +14,6 @@ // TODO: extract the cache state used for graph computation into llama_memory_recurrent_context_i // see the implementation of llama_kv_cache_context_i for an example how to do it -// Continuum fork (CONTINUUM-ENGINE 4.14): a persona's recurrent state, out of the pool: per layer, her row in every -// snapshot group (live group 0, then the n_rs_seq rollback groups) copied raw, plus her cell's small record. Restoring -// it into any free cell is these raw copies and that record; nothing is recomputed. -struct llama_rs_seq_blocks { - bool has_state = false; - llama_pos pos = -1; - uint32_t rs_idx = 0; // her pending rollback index - std::vector> r; // per layer: (1 + n_rs_seq) rows of r, group-major - std::vector> s; // per layer: (1 + n_rs_seq) rows of s, group-major -}; - -enum class llama_rs_seq_move { - done, - invalid_seq, // seq_id out of range - seq_holds_state, // a load requires her sequence to hold no state - shared_cell, // her state cell is shared with another sequence: not hers alone to move - no_free_cell, // no free cell to load into -}; - class llama_memory_recurrent : public llama_memory_i { public: llama_memory_recurrent( @@ -104,10 +85,15 @@ class llama_memory_recurrent : public llama_memory_i { void set_rs_idx(llama_seq_id seq_id, uint32_t idx); - // Continuum fork (CONTINUUM-ENGINE 4.14): her state out (rows copied raw, her cell freed) and in (raw rows into a - // free cell, her record restored). FENCE: the caller completes the context's queued device work first. - llama_rs_seq_move seq_save(llama_seq_id seq_id, llama_rs_seq_blocks & out); - llama_rs_seq_move seq_load(llama_seq_id seq_id, const llama_rs_seq_blocks & in); + // Continuum fork (CONTINUUM-ENGINE 4.14): her row in every snapshot group copied raw, her cell's record carried; + // a load takes the free cell reserved by check_load (a search over this memory's cells, one per sequence slot: + // bounded by the slot count, not by context length). Her sequence id is kept. + llama_persona_move persona_prepare(llama_persona_blocks & blocks) const override; + llama_persona_move persona_check_save(llama_seq_id seq_id, const llama_persona_blocks & out) const override; + llama_persona_move persona_check_load(llama_seq_id seq_id, uint32_t stream, const llama_persona_blocks & in, + llama_persona_slot & slot) const override; + void persona_commit_save(llama_seq_id seq_id, llama_persona_blocks & out) override; + void persona_commit_load(llama_seq_id seq_id, const llama_persona_slot & slot, llama_persona_blocks & in) override; // an undo of a draft is pending on this sequence: its next read takes a snapshot group, not the // live state (group 0) a training graph reads and writes (llm_graph_context::rs_keep) diff --git a/src/llama-memory.cpp b/src/llama-memory.cpp index ca6844c32a76..431639390244 100644 --- a/src/llama-memory.cpp +++ b/src/llama-memory.cpp @@ -57,3 +57,20 @@ bool llama_memory_status_is_fail(llama_memory_status status) { return false; } + +const char * llama_persona_move_name(llama_persona_move m) { + switch (m) { + case llama_persona_move::done: return "done"; + case llama_persona_move::unsupported: return "unsupported"; + case llama_persona_move::no_such_stream: return "no_such_stream"; + case llama_persona_move::transposed_v: return "transposed_v"; + case llama_persona_move::stream_not_empty: return "stream_not_empty"; + case llama_persona_move::cells_not_prepared: return "cells_not_prepared"; + case llama_persona_move::layout_mismatch: return "layout_mismatch"; + case llama_persona_move::invalid_seq: return "invalid_seq"; + case llama_persona_move::seq_holds_state: return "seq_holds_state"; + case llama_persona_move::shared_cell: return "shared_cell"; + case llama_persona_move::no_free_cell: return "no_free_cell"; + } + return "unknown"; +} diff --git a/src/llama-memory.h b/src/llama-memory.h index 588853925216..5585f4b26a0a 100644 --- a/src/llama-memory.h +++ b/src/llama-memory.h @@ -2,6 +2,7 @@ #include "llama.h" #include "llama-graph.h" +#include "llama-persona-blocks.h" #include #include @@ -151,6 +152,28 @@ struct llama_memory_i { // stream, so a stream is never assumed from the sequence id). Memories with no stream map hold it by identity. virtual uint32_t seq_stream(llama_seq_id seq_id) const { return (uint32_t) seq_id; } + // Continuum fork (CONTINUUM-ENGINE 4.14): a persona's state moved raw between this memory and host memory, two + // phases. persona_prepare runs once per persona (sizes her blocks). check_* are const: every condition of the move + // is decided and the destination reserved there; commit_* only copy and write records, and cannot fail. Callers go + // through llama_context::persona_save / persona_load, which fence the queued device work first. + virtual llama_persona_move persona_prepare(llama_persona_blocks & blocks) const { + (void) blocks; + return llama_persona_move::unsupported; + } + virtual llama_persona_move persona_check_save(llama_seq_id seq_id, const llama_persona_blocks & out) const { + (void) seq_id; (void) out; + return llama_persona_move::unsupported; + } + virtual llama_persona_move persona_check_load(llama_seq_id seq_id, uint32_t stream, const llama_persona_blocks & in, + llama_persona_slot & slot) const { + (void) seq_id; (void) stream; (void) in; (void) slot; + return llama_persona_move::unsupported; + } + virtual void persona_commit_save(llama_seq_id seq_id, llama_persona_blocks & out) { (void) seq_id; (void) out; } + virtual void persona_commit_load(llama_seq_id seq_id, const llama_persona_slot & slot, llama_persona_blocks & in) { + (void) seq_id; (void) slot; (void) in; + } + virtual std::map memory_breakdown() const = 0; // the occupancy of every cell holder this memory owns (see llama_memory_cells) diff --git a/src/llama-persona-blocks.h b/src/llama-persona-blocks.h new file mode 100644 index 000000000000..f0eb5c6a623f --- /dev/null +++ b/src/llama-persona-blocks.h @@ -0,0 +1,58 @@ +#pragma once + +// Continuum fork (CONTINUUM-ENGINE 4.14): a persona's execution state, out of the memory pool, as native blocks. +// Moving a persona between the pool and host memory is raw row copies plus her small records; nothing is walked, +// serialized or recomputed. Every move is two-phase: validate (const, reserves the destination, refuses with a typed +// outcome) and commit (copies and record writes only, which cannot fail), so a refusal never leaves her split. + +#include "llama.h" +#include "llama-kv-cells.h" + +#include +#include + +// her attention state: per KV layer, the rows she uses of one stream, and her cell metadata OWNED here (exchanged with +// the stream's by swap; the stream receives an already-empty object, so a move never resets or walks cells) +struct llama_kv_stream_blocks { + uint32_t n_rows = 0; + std::vector> k; // per KV layer: n_rows rows of K + std::vector> v; // per KV layer: n_rows rows of V (empty for a layer without V) + llama_kv_cells cells; // hers while she is out; an empty, stream-sized object while she is in +}; + +// her recurrent state: per layer, her row in every snapshot group (live group 0, then the rollback groups), and her +// cell's record +struct llama_rs_seq_blocks { + bool has_state = false; + llama_pos pos = -1; + uint32_t rs_idx = 0; + std::vector> r; // per layer: (1 + n_rs_seq) rows of r, group-major + std::vector> s; // per layer: (1 + n_rs_seq) rows of s, group-major +}; + +struct llama_persona_blocks { + llama_kv_stream_blocks kv; + llama_rs_seq_blocks rs; +}; + +// where a load puts her: the attention stream, and the recurrent cell reserved by validation +struct llama_persona_slot { + uint32_t stream = 0; + int32_t cell = -1; +}; + +enum class llama_persona_move { + done, + unsupported, // this memory has no persona move + no_such_stream, // stream out of range, or the cache is unified (one stream holds every sequence) + transposed_v, // V is stored transposed (flash attention off): her V rows are not contiguous + stream_not_empty, // a load requires an empty stream + cells_not_prepared, // her blocks do not hold an empty, stream-sized cells object (persona_prepare once) + layout_mismatch, // her blocks do not match this memory's layers, row sizes or groups + invalid_seq, // sequence id out of range + seq_holds_state, // a load requires her sequence to hold no state + shared_cell, // her recurrent cell is shared with another sequence: not hers alone to move + no_free_cell, // no free recurrent cell to load into +}; + +const char * llama_persona_move_name(llama_persona_move m); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 2f6d189cb97c..b998b9fb2484 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -355,13 +355,10 @@ llama_build_and_test(test-dup-quantized.cpp) llama_build_and_test(test-state-restore-streams.cpp LABEL "model" ARGS -m "${MODEL_DEST}") set_tests_properties(test-state-restore-streams PROPERTIES FIXTURES_REQUIRED test-download-model) -# a persona's KV moved between a stream and host memory by raw copies is byte-identical (CONTINUUM-ENGINE 4.14) -llama_build_and_test(test-kv-stream-blocks.cpp LABEL "model" ARGS -m "${MODEL_DEST}") -set_tests_properties(test-kv-stream-blocks PROPERTIES FIXTURES_REQUIRED test-download-model) - -# a persona's whole hybrid state (attention stream + recurrent rows) moved raw is byte-identical (CONTINUUM-ENGINE 4.14); -# takes a hybrid model, e.g. one written by `test-llama-archs -a qwen35moe -o DIR` -llama_build(test-persona-blocks.cpp) +# a persona's state moved raw between the memory and host memory is byte-identical, and a refused move changes nothing +# (CONTINUUM-ENGINE 4.14); also run on a hybrid model written by `test-llama-archs -a qwen35moe -o DIR` +llama_build_and_test(test-persona-blocks.cpp LABEL "model" ARGS -m "${MODEL_DEST}") +set_tests_properties(test-persona-blocks PROPERTIES FIXTURES_REQUIRED test-download-model) # Test state save/load functionality llama_build_and_test(test-save-load-state.cpp LABEL "model" ARGS -m "${MODEL_DEST}") diff --git a/tests/test-kv-stream-blocks.cpp b/tests/test-kv-stream-blocks.cpp deleted file mode 100644 index f7e2410e3fe7..000000000000 --- a/tests/test-kv-stream-blocks.cpp +++ /dev/null @@ -1,224 +0,0 @@ -// what this catches: moving a persona's KV between a stream and host memory (llama_kv_cache::stream_save / -// stream_load / stream_bind, CONTINUUM-ENGINE 4.14) changing her state: after a raw save out of stream 0, a raw load -// into stream 1 and binding her own sequence id to stream 1 (no metadata retagged), her next token's logits must be -// byte-identical to decoding it in place. Also: the stream is left empty by a save, -// and a load into a stream that holds state is refused. No cell walk, serialization or recompute is involved; if any -// row or metadata were lost or misplaced, the logits would differ. - -#include "arg.h" -#include "common.h" -#include "llama.h" - -#include "../src/llama-kv-cache.h" - -#include -#include -#include -#include -#include -#include - -static void require(bool condition, const char * message) { - if (!condition) { - fprintf(stderr, "FAILED: %s\n", message); - std::exit(1); - } -} - -static llama_kv_cache * g_kv = nullptr; - -// the completion fence: llama_decode queues device work and returns; a raw copy of a stream reads or writes device -// memory, so the context's queued compute must have completed first (the same fence llama_state_* takes) -static bool fenced(llama_context * ctx) { - llama_synchronize(ctx); - return true; -} - -// her stream's cell metadata as the decode left it: used count, extent, and each used cell's (index, pos, has her seq) -static void dump_cells(const char * what, llama_seq_id seq) { - const auto & cells = g_kv->get_cells(seq); - fprintf(stderr, "%s: seq %d used=%u used_max_p1=%u cells:", what, seq, cells.get_used(), cells.used_max_p1()); - for (uint32_t i = 0; i < cells.size(); ++i) { - if (!cells.is_empty(i) && (i < 2 || i + 3 >= cells.used_max_p1())) { - fprintf(stderr, " [%u p%d s%d]", i, cells.pos_get(i), cells.seq_has(i, seq) ? 1 : 0); - } - } - fprintf(stderr, "\n"); -} - -static std::vector next_logits(llama_context * ctx, llama_seq_id seq, llama_token token, llama_pos pos) { - llama_batch b = llama_batch_init(1, 0, 1); - common_batch_add(b, token, pos, { seq }, true); - require(llama_decode(ctx, b) == 0, "decode the next token"); - const int n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(llama_get_model(ctx))); - const float * l = llama_get_logits_ith(ctx, 0); - std::vector out(l, l + n_vocab); - llama_batch_free(b); - return out; -} - -// the largest absolute difference and whether the top token agrees (diagnostic when bytes differ) -static void report(const char * what, const std::vector & a, const std::vector & b) { - float max_diff = 0.0f; - size_t top_a = 0, top_b = 0; - for (size_t i = 0; i < a.size(); ++i) { - max_diff = std::max(max_diff, std::fabs(a[i] - b[i])); - top_a = a[i] > a[top_a] ? i : top_a; - top_b = b[i] > b[top_b] ? i : top_b; - } - const bool same = std::memcmp(a.data(), b.data(), a.size() * sizeof(float)) == 0; - fprintf(stderr, "%s: byte-identical=%d max|diff|=%g top=%zu/%zu\n", what, same ? 1 : 0, max_diff, top_a, top_b); -} - -int main(int argc, char ** argv) { - common_params params; - params.kv_unified = false; // one stream per sequence: a persona's KV is one contiguous slice per layer - params.n_parallel = 2; - params.n_ctx = 512; - params.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_ENABLED; // V rows contiguous (not transposed) - common_init(); - if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_COMMON)) { - return 1; - } - ggml_backend_load_all(); - common_init_result_ptr init = common_init_from_params(params); - llama_context * ctx = init->context(); - require(ctx != nullptr, "context"); - auto * kv = dynamic_cast(llama_get_memory(ctx)); - require(kv != nullptr, "a plain KV cache (the test model is not hybrid)"); - g_kv = kv; - - // her prompt on sequence 0 (stream 0) - const int n_prompt = 40; - llama_batch batch = llama_batch_init(n_prompt, 0, 1); - for (int i = 0; i < n_prompt; ++i) { - common_batch_add(batch, 1 + (i * 7) % 300, i, { 0 }, false); - } - require(llama_decode(ctx, batch) == 0, "decode her prompt"); - llama_batch_free(batch); - - // the reference: her next token decoded in place, then taken back so stream 0 holds exactly her prompt again - const llama_token next = 42; - const std::vector reference = next_logits(ctx, 0, next, n_prompt); - dump_cells("after reference decode", 0); - require(llama_memory_seq_rm(llama_get_memory(ctx), 0, n_prompt, -1), "take the reference token back"); - - // control: the same prompt decoded natively on sequence 1 (stream 1); does stream identity alone change logits? - { - llama_batch b1 = llama_batch_init(n_prompt, 0, 1); - for (int i = 0; i < n_prompt; ++i) { - common_batch_add(b1, 1 + (i * 7) % 300, i, { 1 }, false); - } - require(llama_decode(ctx, b1) == 0, "decode her prompt natively on stream 1"); - llama_batch_free(b1); - const std::vector native1 = next_logits(ctx, 1, next, n_prompt); - report("native on stream 1 vs stream 0", reference, native1); - require(llama_memory_seq_rm(llama_get_memory(ctx), 1, -1, -1), "clear the stream 1 control"); - } - - // determinism: the same token decoded in place again - { - const std::vector again = next_logits(ctx, 0, next, n_prompt); - report("in place twice", reference, again); - require(llama_memory_seq_rm(llama_get_memory(ctx), 0, n_prompt, -1), "take it back again"); - } - // the copies alone: a round trip through host memory into the SAME stream, no bind - { - llama_kv_stream_blocks rt; - require(fenced(ctx) && kv->stream_save(0, rt) == llama_kv_stream_move::done, "round-trip save"); - require(fenced(ctx) && kv->stream_load(0, rt) == llama_kv_stream_move::done, "round-trip load"); - const std::vector same_stream = next_logits(ctx, 0, next, n_prompt); - report("same stream round trip", reference, same_stream); - require(llama_memory_seq_rm(llama_get_memory(ctx), 0, n_prompt, -1), "take it back after the round trip"); - } - - // out: raw rows + her metadata swapped out; stream 0 left empty - llama_kv_stream_blocks blocks; - require(fenced(ctx) && kv->stream_save(0, blocks) == llama_kv_stream_move::done, "save stream 0"); - require(blocks.n_rows == (uint32_t) n_prompt, "she uses exactly her prompt's rows"); - require(llama_memory_seq_pos_max(llama_get_memory(ctx), 0) < 0, "stream 0 is empty after the save"); - - // a load into a stream that holds state is refused, and changes nothing - { - llama_batch b = llama_batch_init(1, 0, 1); - common_batch_add(b, 5, 0, { 1 }, false); - require(llama_decode(ctx, b) == 0, "occupy stream 1"); - llama_batch_free(b); - require(fenced(ctx) && kv->stream_load(1, blocks) == llama_kv_stream_move::stream_not_empty, "never loaded over state"); - require(llama_memory_seq_rm(llama_get_memory(ctx), 1, -1, -1), "clear stream 1"); - } - - // in: raw rows + her metadata swapped into physical stream 1; she keeps her own sequence id 0, bound to stream 1 - require(fenced(ctx) && kv->stream_load(1, blocks) == llama_kv_stream_move::done, "load into stream 1"); - require(kv->stream_bind(0, 1) == llama_kv_stream_move::done, "bind her sequence to stream 1"); - { - // her rows as they now sit in stream 1, read back raw, against the bytes that were saved - llama_kv_stream_blocks back; - require(fenced(ctx) && kv->stream_save(1, back) == llama_kv_stream_move::done, "read stream 1 back"); - bool rows_equal = back.n_rows == blocks.n_rows; - for (size_t i = 0; rows_equal && i < back.k.size(); ++i) { - rows_equal = back.k[i] == blocks.k[i] && back.v[i] == blocks.v[i]; - } - fprintf(stderr, "stream 1 rows after load equal the saved bytes: %d (layers %zu)\n", rows_equal ? 1 : 0, back.k.size()); - require(fenced(ctx) && kv->stream_load(1, back) == llama_kv_stream_move::done, "put them back"); - } - require(llama_memory_seq_pos_max(llama_get_memory(ctx), 0) == n_prompt - 1, "her sequence holds her prompt"); - require(llama_memory_seq_pos_max(llama_get_memory(ctx), 1) < 0, "sequence 1 now maps to the empty stream 0"); - dump_cells("moved, before decode", 0); - const std::vector moved = next_logits(ctx, 0, next, n_prompt); - dump_cells("moved, after decode", 0); - require(moved.size() == reference.size(), "same vocabulary"); - report("moved to stream 1", reference, moved); - const bool moved_exact = std::memcmp(moved.data(), reference.data(), moved.size() * sizeof(float)) == 0; - - // bisection variants, each from a cleared cache with the identity mapping - auto reset = [&]() { - llama_memory_clear(llama_get_memory(ctx), true); - require(kv->stream_bind(0, 0) == llama_kv_stream_move::done, "identity bind 0"); - require(kv->stream_bind(1, 1) == llama_kv_stream_move::done, "identity bind 1"); - }; - auto prompt_on = [&](llama_seq_id seq) { - llama_batch b = llama_batch_init(n_prompt, 0, 1); - for (int i = 0; i < n_prompt; ++i) { - common_batch_add(b, 1 + (i * 7) % 300, i, { seq }, false); - } - require(llama_decode(ctx, b) == 0, "decode the prompt"); - llama_batch_free(b); - }; - { // X1: move to stream 1 + bind, without occupying stream 1 first - reset(); - prompt_on(0); - llama_kv_stream_blocks x; - require(fenced(ctx) && kv->stream_save(0, x) == llama_kv_stream_move::done, "X1 save"); - require(fenced(ctx) && kv->stream_load(1, x) == llama_kv_stream_move::done, "X1 load"); - require(kv->stream_bind(0, 1) == llama_kv_stream_move::done, "X1 bind"); - report("X1 move+bind, no occupy", reference, next_logits(ctx, 0, next, n_prompt)); - } - { // X3: mirror: native on seq 1 / stream 1, moved to stream 0, seq 1 bound to stream 0 - reset(); - prompt_on(1); - llama_kv_stream_blocks x; - require(fenced(ctx) && kv->stream_save(1, x) == llama_kv_stream_move::done, "X3 save"); - require(fenced(ctx) && kv->stream_load(0, x) == llama_kv_stream_move::done, "X3 load"); - require(kv->stream_bind(1, 0) == llama_kv_stream_move::done, "X3 bind"); - report("X3 mirror stream1->stream0", reference, next_logits(ctx, 1, next, n_prompt)); - } - { // X4: in place, two tokens; then moved, two tokens: does the second token differ too? - reset(); - prompt_on(0); - next_logits(ctx, 0, next, n_prompt); - const std::vector in_place_2 = next_logits(ctx, 0, next + 1, n_prompt + 1); - reset(); - prompt_on(0); - llama_kv_stream_blocks x; - require(fenced(ctx) && kv->stream_save(0, x) == llama_kv_stream_move::done, "X4 save"); - require(fenced(ctx) && kv->stream_load(1, x) == llama_kv_stream_move::done, "X4 load"); - require(kv->stream_bind(0, 1) == llama_kv_stream_move::done, "X4 bind"); - report("X4 first token after move", reference, next_logits(ctx, 0, next, n_prompt)); - report("X4 second token after move", in_place_2, next_logits(ctx, 0, next + 1, n_prompt + 1)); - } - require(moved_exact, "her next-token logits are byte-identical after the move"); - - fprintf(stderr, "test-kv-stream-blocks: ok (%u rows moved raw)\n", (unsigned) n_prompt); - return 0; -} diff --git a/tests/test-persona-blocks.cpp b/tests/test-persona-blocks.cpp index 315745f80966..86105207141b 100644 --- a/tests/test-persona-blocks.cpp +++ b/tests/test-persona-blocks.cpp @@ -1,15 +1,16 @@ -// what this catches: moving a persona's WHOLE state on a hybrid model (attention stream + recurrent rows, -// llama_memory_hybrid::persona_save / persona_load, CONTINUUM-ENGINE 4.14) changing her state: after her state goes -// out of stream 0 and her recurrent cell to host memory and back into stream 1 bound to her own sequence id, her next -// two tokens' logits must be byte-identical to decoding them in place. Nothing is recomputed; a lost or misplaced row -// or record changes the logits. The model argument is a hybrid (e.g. a tiny random qwen35moe from -// `test-llama-archs -a qwen35moe -o DIR`). +// what this catches: moving a persona's state between the memory and host memory (llama_context::persona_save / +// persona_load, CONTINUUM-ENGINE 4.14) changing her state, or a refused move changing anything. Every move must leave +// her next tokens' logits byte-identical to decoding in place: out of one stream and into another bound to her own +// sequence id, the mirror direction, a same-stream round trip, and two live personas exchanging streams. Refusals +// (stream holding state, blocks not prepared, layout mismatch, sequence holding state) must be typed and change +// nothing. Runs on a plain KV model and on a hybrid (attention + recurrent, e.g. a tiny random qwen35moe from +// `test-llama-archs -a qwen35moe -o DIR`); the same interface covers both. #include "arg.h" #include "common.h" #include "llama.h" -#include "../src/llama-memory-hybrid.h" +#include "../src/llama-context.h" #include #include @@ -25,27 +26,69 @@ static void require(bool condition, const char * message) { } } -static std::vector next_logits(llama_context * ctx, llama_seq_id seq, llama_token token, llama_pos pos) { - llama_batch b = llama_batch_init(1, 0, 1); - common_batch_add(b, token, pos, { seq }, true); - require(llama_decode(ctx, b) == 0, "decode the next token"); - const int n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(llama_get_model(ctx))); - const float * l = llama_get_logits_ith(ctx, 0); - std::vector out(l, l + n_vocab); - llama_batch_free(b); - return out; +static void require_move(llama_persona_move got, llama_persona_move want, const char * what) { + if (got != want) { + fprintf(stderr, "FAILED: %s: got %s, want %s\n", what, llama_persona_move_name(got), llama_persona_move_name(want)); + std::exit(1); + } } -static bool same(const char * what, const std::vector & a, const std::vector & b) { +static void require_identical(const char * what, const std::vector & want, const std::vector & got) { float max_diff = 0.0f; - for (size_t i = 0; i < a.size(); ++i) { - max_diff = std::max(max_diff, std::fabs(a[i] - b[i])); + for (size_t i = 0; i < std::min(want.size(), got.size()); ++i) { + max_diff = std::max(max_diff, std::fabs(want[i] - got[i])); } - const bool identical = a.size() == b.size() && std::memcmp(a.data(), b.data(), a.size() * sizeof(float)) == 0; + const bool identical = want.size() == got.size() && std::memcmp(want.data(), got.data(), want.size() * sizeof(float)) == 0; fprintf(stderr, "%s: byte-identical=%d max|diff|=%g\n", what, identical ? 1 : 0, max_diff); - return identical; + require(identical, what); } +struct fixture { + llama_context * ctx = nullptr; + int n_vocab = 0; + int n_prompt = 24; + + std::vector decode_one(llama_seq_id seq, llama_token token, llama_pos pos) { + llama_batch b = llama_batch_init(1, 0, 1); + common_batch_add(b, token, pos, { seq }, true); + require(llama_decode(ctx, b) == 0, "decode a token"); + const float * l = llama_get_logits_ith(ctx, 0); + std::vector out(l, l + n_vocab); + llama_batch_free(b); + return out; + } + + // her prompt (salt makes two personas' prompts differ) + void prompt(llama_seq_id seq, int salt) { + llama_batch b = llama_batch_init(n_prompt, 0, 1); + for (int i = 0; i < n_prompt; ++i) { + common_batch_add(b, 1 + (i * 7 + salt * 13) % (n_vocab - 1), i, { seq }, false); + } + require(llama_decode(ctx, b) == 0, "decode a prompt"); + llama_batch_free(b); + } + + // her next two tokens decoded in place from a clear memory: the reference + std::vector> reference(llama_seq_id seq, int salt) { + llama_memory_clear(llama_get_memory(ctx), true); + prompt(seq, salt); + std::vector> out; + out.push_back(decode_one(seq, 3 % n_vocab, n_prompt)); + out.push_back(decode_one(seq, 5 % n_vocab, n_prompt + 1)); + return out; + } + + void require_continues(const char * what, llama_seq_id seq, const std::vector> & ref) { + char label[160]; + snprintf(label, sizeof(label), "%s: first token", what); + require_identical(label, ref[0], decode_one(seq, 3 % n_vocab, n_prompt)); + snprintf(label, sizeof(label), "%s: second token", what); + require_identical(label, ref[1], decode_one(seq, 5 % n_vocab, n_prompt + 1)); + } + + llama_pos pos_max(llama_seq_id seq) const { return llama_memory_seq_pos_max(llama_get_memory(ctx), seq); } +}; + int main(int argc, char ** argv) { common_params params; params.kv_unified = false; // one attention stream per sequence @@ -58,45 +101,86 @@ int main(int argc, char ** argv) { } ggml_backend_load_all(); common_init_result_ptr init = common_init_from_params(params); - llama_context * ctx = init->context(); - require(ctx != nullptr, "context"); - auto * mem = dynamic_cast(llama_get_memory(ctx)); - require(mem != nullptr, "a hybrid memory (attention + recurrent)"); - const int n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(llama_get_model(ctx))); - - const int n_prompt = 24; - auto prompt_on = [&](llama_seq_id seq) { - llama_batch b = llama_batch_init(n_prompt, 0, 1); - for (int i = 0; i < n_prompt; ++i) { - common_batch_add(b, 1 + (i * 7) % (n_vocab - 1), i, { seq }, false); - } - require(llama_decode(ctx, b) == 0, "decode her prompt"); - llama_batch_free(b); - }; - const llama_token t1 = 3 % n_vocab; - const llama_token t2 = 5 % n_vocab; - - // the reference: her prompt, then her next two tokens decoded in place - prompt_on(0); - const std::vector ref1 = next_logits(ctx, 0, t1, n_prompt); - const std::vector ref2 = next_logits(ctx, 0, t2, n_prompt + 1); - - // the same prompt again from a clear memory, then her whole state moved out and into stream 1, bound to her id - llama_memory_clear(llama_get_memory(ctx), true); - prompt_on(0); - llama_synchronize(ctx); // the completion fence before raw copies - llama_persona_blocks blocks; - require(mem->persona_save(0, blocks), "her state out"); - require(blocks.rs.has_state, "she has recurrent state"); - require(llama_memory_seq_pos_max(llama_get_memory(ctx), 0) < 0, "nothing of her is left in the pool"); - require(mem->persona_load(0, 1, blocks), "her state into stream 1 and a free recurrent cell"); - require(llama_memory_seq_pos_max(llama_get_memory(ctx), 0) == n_prompt - 1, "her sequence holds her prompt again"); - - const bool ok1 = same("first token after the move", ref1, next_logits(ctx, 0, t1, n_prompt)); - const bool ok2 = same("second token after the move", ref2, next_logits(ctx, 0, t2, n_prompt + 1)); - require(ok1 && ok2, "her logits are byte-identical after her whole state moved"); - - fprintf(stderr, "test-persona-blocks: ok (%zu attention layers, %zu recurrent layers, moved raw)\n", - blocks.kv.k.size(), blocks.rs.r.size()); + fixture f; + f.ctx = init->context(); + require(f.ctx != nullptr, "context"); + f.n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(llama_get_model(f.ctx))); + llama_context & ctx = *f.ctx; + + llama_persona_blocks a, b; + require_move(ctx.persona_prepare(a), llama_persona_move::done, "prepare persona a"); + require_move(ctx.persona_prepare(b), llama_persona_move::done, "prepare persona b"); + + const auto ref_a0 = f.reference(0, 1); // persona a on sequence 0 + const auto ref_b1 = f.reference(1, 2); // persona b on sequence 1 + + // 1. out of stream 0, into stream 1 bound to her own sequence 0 + llama_memory_clear(llama_get_memory(f.ctx), true); + f.prompt(0, 1); + require_move(ctx.persona_save(0, a), llama_persona_move::done, "a out"); + require(f.pos_max(0) < 0, "nothing of a is left in the memory"); + require_move(ctx.persona_load(0, 1, a), llama_persona_move::done, "a into stream 1"); + require(f.pos_max(0) == f.n_prompt - 1, "a's sequence holds her prompt"); + f.require_continues("a moved to stream 1", 0, ref_a0); + + // 2. the mirror: b's sequence 1 out of its stream and into the other + llama_memory_clear(llama_get_memory(f.ctx), true); + f.prompt(1, 2); + const uint32_t b_stream = llama_get_memory(f.ctx)->seq_stream(1); + require_move(ctx.persona_save(1, b), llama_persona_move::done, "b out"); + require_move(ctx.persona_load(1, 1 - b_stream, b), llama_persona_move::done, "b into the other stream"); + f.require_continues("b moved to the other stream", 1, ref_b1); + + // 3. same-stream round trip + llama_memory_clear(llama_get_memory(f.ctx), true); + f.prompt(0, 1); + const uint32_t a_stream = llama_get_memory(f.ctx)->seq_stream(0); + require_move(ctx.persona_save(0, a), llama_persona_move::done, "a out (round trip)"); + require_move(ctx.persona_load(0, a_stream, a), llama_persona_move::done, "a back into her own stream"); + f.require_continues("a same-stream round trip", 0, ref_a0); + + // 4. refusals are typed and change nothing + { + llama_memory_clear(llama_get_memory(f.ctx), true); + f.prompt(0, 1); + f.prompt(1, 2); + llama_persona_blocks unprepared; + require(ctx.persona_save(0, unprepared) != llama_persona_move::done, "an unprepared save is refused"); + require(f.pos_max(0) == f.n_prompt - 1, "a refused save leaves her in place"); + + require_move(ctx.persona_save(0, a), llama_persona_move::done, "a out (refusal setup)"); + const uint32_t occupied = llama_get_memory(f.ctx)->seq_stream(1); + require_move(ctx.persona_load(0, occupied, a), llama_persona_move::stream_not_empty, "load over b's stream"); + require(f.pos_max(1) == f.n_prompt - 1, "b untouched by the refused load"); + + llama_persona_blocks bad = a; // the same persona with one layer's rows missing + bad.kv.k.pop_back(); + require_move(ctx.persona_load(0, 1 - occupied, bad), llama_persona_move::layout_mismatch, "a layout mismatch"); + require(f.pos_max(0) < 0, "a refused load writes nothing"); + + require_move(ctx.persona_load(0, 1 - occupied, a), llama_persona_move::done, "a back after the refusals"); + f.require_continues("a after the refusals", 0, ref_a0); + f.require_continues("b untouched by a's refusals", 1, ref_b1); + } + + // 5. two live personas exchange streams: the map stays a permutation and each keeps her own state + { + llama_memory_clear(llama_get_memory(f.ctx), true); + f.prompt(0, 1); + f.prompt(1, 2); + const uint32_t sa = llama_get_memory(f.ctx)->seq_stream(0); + const uint32_t sb = llama_get_memory(f.ctx)->seq_stream(1); + require(sa != sb, "two personas, two streams"); + require_move(ctx.persona_save(0, a), llama_persona_move::done, "a out (exchange)"); + require_move(ctx.persona_save(1, b), llama_persona_move::done, "b out (exchange)"); + require_move(ctx.persona_load(0, sb, a), llama_persona_move::done, "a into b's stream"); + require_move(ctx.persona_load(1, sa, b), llama_persona_move::done, "b into a's stream"); + require(llama_get_memory(f.ctx)->seq_stream(0) == sb && llama_get_memory(f.ctx)->seq_stream(1) == sa, + "the streams are exchanged"); + f.require_continues("a after the exchange", 0, ref_a0); + f.require_continues("b after the exchange", 1, ref_b1); + } + + fprintf(stderr, "test-persona-blocks: ok (%zu attention layers, %zu recurrent layers)\n", a.kv.k.size(), a.rs.r.size()); return 0; } From 8c186c8e6a4524129807e6b032a72e13ecc0e5a6 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 22:05:30 -0600 Subject: [PATCH 04/28] memory: a persona move cannot fail after it starts; her blocks carry her identity; measured on the 35B (Codex's a1c5c8eab review) - Check phases reserve every byte the commit copies (KV rows at her used length; recurrent rows x groups) and her recurrent cell's sequence-set node (a C++17 node handle), so a commit only copies, swaps and inserts a reserved node: nothing allocates after either half changes. - Her blocks carry her sequence and a layout fingerprint per memory (layers, stream size, row types and widths, snapshot groups). A load refuses wrong_persona (her metadata is tagged with her sequence; never retagged), layout_mismatch, and invalid_rollback (rs_idx > n_rs_seq), before any write. - Measure mode (-n N): recompute (prefill) vs her native state saved and loaded; the in-place reference comes from a second clean run (recurrent state cannot be rolled back). ## Measured (M5, Metal, this tree; serving down 04:02-04:05Z) Qwen3.6-35B-A3B Q4_K_M, KV q4_0, flash attention, ub 2048; her next 2 tokens byte-identical after the move in every run: - 4096 tokens: state 89.5 MB; recompute 4350.6 ms; save 5.26 ms; load 1.40 ms (63.9 GB/s); 3108x - 16384 tokens: state 160.2 MB; recompute 20419.4 ms; save 9.88 ms; load 2.64 ms (60.8 GB/s); 7746x - 32768 tokens: state 254.6 MB; recompute 50833.8 ms; save 14.09 ms; load 4.09 ms (62.3 GB/s); 12429x test-persona-blocks passes on stories15M (ctest) and tiny random qwen35moe, incl. wrong_persona and invalid_rollback refusals that write neither half. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- src/llama-kv-cache.cpp | 53 +++++++++++++++++++++------ src/llama-kv-cache.h | 5 ++- src/llama-memory-hybrid.cpp | 4 +- src/llama-memory-hybrid.h | 4 +- src/llama-memory-recurrent.cpp | 50 +++++++++++++++++++++---- src/llama-memory-recurrent.h | 5 ++- src/llama-memory.cpp | 2 + src/llama-memory.h | 9 +++-- src/llama-persona-blocks.h | 21 ++++++++--- tests/test-persona-blocks.cpp | 67 +++++++++++++++++++++++++++++++--- 10 files changed, 178 insertions(+), 42 deletions(-) diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index e84acc922d8c..cdd0427bdc6a 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -1236,17 +1236,34 @@ static bool cells_prepared(const llama_kv_cells & cells, uint32_t size) { return cells.size() == size && cells.get_used() == 0 && !cells.get_has_shift(); } +// this memory's attention layout: what her rows' sizes and meaning depend on +static uint64_t kv_layout_mix(uint64_t h, uint64_t v) { return (h ^ v) * 0x100000001b3ull; } + +uint64_t llama_kv_cache::persona_layout() const { + uint64_t h = kv_layout_mix(0xcbf29ce484222325ull, layers.size()); + h = kv_layout_mix(h, get_size()); + for (const auto & layer : layers) { + h = kv_layout_mix(h, layer.il); + h = kv_layout_mix(h, layer.k ? (uint64_t) layer.k->type : 0xffu); + h = kv_layout_mix(h, layer.k ? (uint64_t) layer.k->ne[0] : 0); + h = kv_layout_mix(h, layer.v ? (uint64_t) layer.v->type : 0xffu); + h = kv_layout_mix(h, layer.v ? (uint64_t) layer.v->ne[0] : 0); + } + return h; +} + llama_persona_move llama_kv_cache::persona_prepare(llama_persona_blocks & blocks) const { if (n_stream == 1) { return llama_persona_move::no_such_stream; } + blocks.kv_layout = persona_layout(); blocks.kv.cells.resize(get_size()); // once per persona, at her creation blocks.kv.k.resize(layers.size()); blocks.kv.v.resize(layers.size()); return llama_persona_move::done; } -llama_persona_move llama_kv_cache::persona_check_save(llama_seq_id seq_id, const llama_persona_blocks & out) const { +llama_persona_move llama_kv_cache::persona_check_save(llama_seq_id seq_id, llama_persona_blocks & out) const { if (n_stream == 1) { return llama_persona_move::no_such_stream; } @@ -1256,30 +1273,36 @@ llama_persona_move llama_kv_cache::persona_check_save(llama_seq_id seq_id, const if (v_trans) { return llama_persona_move::transposed_v; } + if (out.kv_layout != persona_layout()) { + return llama_persona_move::layout_mismatch; + } if (!cells_prepared(out.kv.cells, get_size()) || out.kv.k.size() != layers.size() || out.kv.v.size() != layers.size()) { return llama_persona_move::cells_not_prepared; } + // reserve: every byte the commit copies, so the commit never allocates + const uint32_t n_rows = v_cells[seq_to_stream[seq_id]].used_max_p1(); + for (size_t i = 0; i < layers.size(); ++i) { + const auto & layer = layers[i]; + out.kv.k[i].resize(ggml_row_size(layer.k->type, layer.k->ne[0]) * n_rows); + out.kv.v[i].resize(layer.v ? ggml_row_size(layer.v->type, layer.v->ne[0]) * n_rows : 0); + } + out.kv.n_rows = n_rows; return llama_persona_move::done; } void llama_kv_cache::persona_commit_save(llama_seq_id seq_id, llama_persona_blocks & out) { const uint32_t s = seq_to_stream[seq_id]; auto & cells = v_cells[s]; - const uint32_t n_rows = cells.used_max_p1(); - out.kv.n_rows = n_rows; for (size_t i = 0; i < layers.size(); ++i) { const auto & layer = layers[i]; - const size_t k_bytes = ggml_row_size(layer.k->type, layer.k->ne[0]) * n_rows; - out.kv.k[i].resize(k_bytes); - if (k_bytes > 0) { - ggml_backend_tensor_get(layer.k_stream[s], out.kv.k[i].data(), 0, k_bytes); + if (!out.kv.k[i].empty()) { + ggml_backend_tensor_get(layer.k_stream[s], out.kv.k[i].data(), 0, out.kv.k[i].size()); } - const size_t v_bytes = layer.v ? ggml_row_size(layer.v->type, layer.v->ne[0]) * n_rows : 0; - out.kv.v[i].resize(v_bytes); - if (v_bytes > 0) { - ggml_backend_tensor_get(layer.v_stream[s], out.kv.v[i].data(), 0, v_bytes); + if (!out.kv.v[i].empty()) { + ggml_backend_tensor_get(layer.v_stream[s], out.kv.v[i].data(), 0, out.kv.v[i].size()); } } + out.seq = seq_id; std::swap(out.kv.cells, cells); // hers out; the stream takes the prepared empty object v_heads[s] = 0; } @@ -1301,6 +1324,12 @@ llama_persona_move llama_kv_cache::persona_check_load(llama_seq_id seq_id, uint3 if (v_cells[seq_to_stream[seq_id]].seq_pos_max(seq_id) >= 0) { return llama_persona_move::seq_holds_state; } + if (in.kv_layout != persona_layout()) { + return llama_persona_move::layout_mismatch; + } + if (in.kv.n_rows > 0 && in.seq != seq_id) { + return llama_persona_move::wrong_persona; + } const auto & kv = in.kv; if (kv.cells.size() != get_size() || kv.n_rows > get_size() || kv.cells.used_max_p1() > kv.n_rows || kv.k.size() != layers.size() || kv.v.size() != layers.size()) { @@ -1318,7 +1347,7 @@ llama_persona_move llama_kv_cache::persona_check_load(llama_seq_id seq_id, uint3 return llama_persona_move::done; } -void llama_kv_cache::persona_commit_load(llama_seq_id seq_id, const llama_persona_slot & slot, llama_persona_blocks & in) { +void llama_kv_cache::persona_commit_load(llama_seq_id seq_id, llama_persona_slot & slot, llama_persona_blocks & in) { const uint32_t s = slot.stream; for (size_t i = 0; i < layers.size(); ++i) { const auto & layer = layers[i]; diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h index ae8fec0e1395..691e26ed73e1 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -179,11 +179,12 @@ class llama_kv_cache : public llama_memory_i { // swap with an already-empty object (never reset or walked), her own sequence id bound to the stream she lands on // (seq_to_stream stays a permutation; her cells are never retagged). Requires unified KV off and flash attention. llama_persona_move persona_prepare(llama_persona_blocks & blocks) const override; - llama_persona_move persona_check_save(llama_seq_id seq_id, const llama_persona_blocks & out) const override; + uint64_t persona_layout() const; + llama_persona_move persona_check_save(llama_seq_id seq_id, llama_persona_blocks & out) const override; llama_persona_move persona_check_load(llama_seq_id seq_id, uint32_t stream, const llama_persona_blocks & in, llama_persona_slot & slot) const override; void persona_commit_save(llama_seq_id seq_id, llama_persona_blocks & out) override; - void persona_commit_load(llama_seq_id seq_id, const llama_persona_slot & slot, llama_persona_blocks & in) override; + void persona_commit_load(llama_seq_id seq_id, llama_persona_slot & slot, llama_persona_blocks & in) override; uint32_t seq_stream(llama_seq_id seq_id) const override { return seq_to_stream[seq_id]; } diff --git a/src/llama-memory-hybrid.cpp b/src/llama-memory-hybrid.cpp index 2c03c5c156f5..db115ba6f3ae 100644 --- a/src/llama-memory-hybrid.cpp +++ b/src/llama-memory-hybrid.cpp @@ -216,7 +216,7 @@ llama_persona_move llama_memory_hybrid::persona_prepare(llama_persona_blocks & b return attn != llama_persona_move::done ? attn : mem_recr->persona_prepare(blocks); } -llama_persona_move llama_memory_hybrid::persona_check_save(llama_seq_id seq_id, const llama_persona_blocks & out) const { +llama_persona_move llama_memory_hybrid::persona_check_save(llama_seq_id seq_id, llama_persona_blocks & out) const { const llama_persona_move attn = mem_attn->persona_check_save(seq_id, out); return attn != llama_persona_move::done ? attn : mem_recr->persona_check_save(seq_id, out); } @@ -232,7 +232,7 @@ void llama_memory_hybrid::persona_commit_save(llama_seq_id seq_id, llama_persona mem_recr->persona_commit_save(seq_id, out); } -void llama_memory_hybrid::persona_commit_load(llama_seq_id seq_id, const llama_persona_slot & slot, +void llama_memory_hybrid::persona_commit_load(llama_seq_id seq_id, llama_persona_slot & slot, llama_persona_blocks & in) { mem_attn->persona_commit_load(seq_id, slot, in); mem_recr->persona_commit_load(seq_id, slot, in); diff --git a/src/llama-memory-hybrid.h b/src/llama-memory-hybrid.h index 41a57bc3813d..e30f48cefc05 100644 --- a/src/llama-memory-hybrid.h +++ b/src/llama-memory-hybrid.h @@ -89,11 +89,11 @@ class llama_memory_hybrid : public llama_memory_i { // her whole state: both halves are checked (and the destination reserved) before either commits llama_persona_move persona_prepare(llama_persona_blocks & blocks) const override; - llama_persona_move persona_check_save(llama_seq_id seq_id, const llama_persona_blocks & out) const override; + llama_persona_move persona_check_save(llama_seq_id seq_id, llama_persona_blocks & out) const override; llama_persona_move persona_check_load(llama_seq_id seq_id, uint32_t stream, const llama_persona_blocks & in, llama_persona_slot & slot) const override; void persona_commit_save(llama_seq_id seq_id, llama_persona_blocks & out) override; - void persona_commit_load(llama_seq_id seq_id, const llama_persona_slot & slot, llama_persona_blocks & in) override; + void persona_commit_load(llama_seq_id seq_id, llama_persona_slot & slot, llama_persona_blocks & in) override; uint32_t seq_stream(llama_seq_id seq_id) const override { return mem_attn->seq_stream(seq_id); } llama_memory_recurrent * get_mem_recr() const; diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp index 5c7fab04c6e0..f4a2806ee5de 100644 --- a/src/llama-memory-recurrent.cpp +++ b/src/llama-memory-recurrent.cpp @@ -392,16 +392,35 @@ llama_pos llama_memory_recurrent::seq_pos_max(llama_seq_id seq_id) const { return result; } +static uint64_t rs_layout_mix(uint64_t h, uint64_t v) { return (h ^ v) * 0x100000001b3ull; } + +uint64_t llama_memory_recurrent::persona_layout() const { + uint64_t h = rs_layout_mix(0xcbf29ce484222325ull, r_l.size()); + h = rs_layout_mix(h, size); + h = rs_layout_mix(h, n_rs_seq); + for (size_t il = 0; il < r_l.size(); ++il) { + for (const ggml_tensor * t : { r_l[il], s_l[il] }) { + h = rs_layout_mix(h, t ? (uint64_t) t->type : 0xffu); + h = rs_layout_mix(h, t ? (uint64_t) t->ne[0] : 0); + } + } + return h; +} + llama_persona_move llama_memory_recurrent::persona_prepare(llama_persona_blocks & blocks) const { + blocks.rs_layout = persona_layout(); blocks.rs.r.resize(r_l.size()); blocks.rs.s.resize(s_l.size()); return llama_persona_move::done; } -llama_persona_move llama_memory_recurrent::persona_check_save(llama_seq_id seq_id, const llama_persona_blocks & out) const { +llama_persona_move llama_memory_recurrent::persona_check_save(llama_seq_id seq_id, llama_persona_blocks & out) const { if (seq_id < 0 || (uint32_t) seq_id >= size || (uint32_t) seq_id >= n_seq_max) { return llama_persona_move::invalid_seq; } + if (out.rs_layout != persona_layout()) { + return llama_persona_move::layout_mismatch; + } if (out.rs.r.size() != r_l.size() || out.rs.s.size() != s_l.size()) { return llama_persona_move::cells_not_prepared; } @@ -409,6 +428,12 @@ llama_persona_move llama_memory_recurrent::persona_check_save(llama_seq_id seq_i if (tail >= 0 && cells[tail].seq_id.size() != 1) { return llama_persona_move::shared_cell; } + // reserve: every byte the commit copies, so the commit never allocates + const uint32_t n_groups = 1 + n_rs_seq; + for (size_t il = 0; il < r_l.size(); ++il) { + out.rs.r[il].resize((tail >= 0 && r_l[il]) ? ggml_row_size(r_l[il]->type, r_l[il]->ne[0]) * n_groups : 0); + out.rs.s[il].resize((tail >= 0 && s_l[il]) ? ggml_row_size(s_l[il]->type, s_l[il]->ne[0]) * n_groups : 0); + } return llama_persona_move::done; } @@ -416,20 +441,17 @@ void llama_memory_recurrent::persona_commit_save(llama_seq_id seq_id, llama_pers auto & rs = out.rs; const int32_t tail = cells[seq_id].tail; rs.has_state = tail >= 0; + out.seq = seq_id; if (!rs.has_state) { - for (auto & v : rs.r) { v.clear(); } - for (auto & v : rs.s) { v.clear(); } return; } const uint32_t n_groups = 1 + n_rs_seq; for (size_t il = 0; il < r_l.size(); ++il) { for (auto [src, dst] : { std::make_pair(r_l[il], &rs.r[il]), std::make_pair(s_l[il], &rs.s[il]) }) { - if (src == nullptr) { - dst->clear(); + if (src == nullptr || dst->empty()) { continue; } const size_t row = ggml_row_size(src->type, src->ne[0]); - dst->resize(row * n_groups); for (uint32_t g = 0; g < n_groups; ++g) { ggml_backend_tensor_get(src, dst->data() + g * row, (size_t) (g * size + tail) * src->nb[1], row); } @@ -460,9 +482,18 @@ llama_persona_move llama_memory_recurrent::persona_check_load(llama_seq_id seq_i } const auto & rs = in.rs; slot.cell = -1; + if (in.rs_layout != persona_layout()) { + return llama_persona_move::layout_mismatch; + } if (!rs.has_state) { return llama_persona_move::done; } + if (in.seq != seq_id) { + return llama_persona_move::wrong_persona; + } + if (rs.rs_idx > n_rs_seq) { + return llama_persona_move::invalid_rollback; + } if (rs.r.size() != r_l.size() || rs.s.size() != s_l.size()) { return llama_persona_move::layout_mismatch; } @@ -477,13 +508,16 @@ llama_persona_move llama_memory_recurrent::persona_check_load(llama_seq_id seq_i for (uint32_t i = 0; i < size; ++i) { if (cells[i].is_empty() && cells[i].pos < 0) { slot.cell = (int32_t) i; + // reserve her cell's sequence-set node now, so the commit inserts it without allocating + std::set node_source { seq_id }; + slot.node = node_source.extract(node_source.begin()); return llama_persona_move::done; } } return llama_persona_move::no_free_cell; } -void llama_memory_recurrent::persona_commit_load(llama_seq_id seq_id, const llama_persona_slot & slot, +void llama_memory_recurrent::persona_commit_load(llama_seq_id seq_id, llama_persona_slot & slot, llama_persona_blocks & in) { const auto & rs = in.rs; if (!rs.has_state) { @@ -506,7 +540,7 @@ void llama_memory_recurrent::persona_commit_load(llama_seq_id seq_id, const llam cell.pos = rs.pos; cell.src = cell_id; cell.src0 = cell_id; - cell.seq_id.insert(seq_id); + cell.seq_id.insert(std::move(slot.node)); // the node reserved by check: no allocation cells[seq_id].tail = cell_id; rs_idx[seq_id] = rs.rs_idx; used += 1; diff --git a/src/llama-memory-recurrent.h b/src/llama-memory-recurrent.h index 64c278a7072c..6dfdc4ce9675 100644 --- a/src/llama-memory-recurrent.h +++ b/src/llama-memory-recurrent.h @@ -89,11 +89,12 @@ class llama_memory_recurrent : public llama_memory_i { // a load takes the free cell reserved by check_load (a search over this memory's cells, one per sequence slot: // bounded by the slot count, not by context length). Her sequence id is kept. llama_persona_move persona_prepare(llama_persona_blocks & blocks) const override; - llama_persona_move persona_check_save(llama_seq_id seq_id, const llama_persona_blocks & out) const override; + uint64_t persona_layout() const; + llama_persona_move persona_check_save(llama_seq_id seq_id, llama_persona_blocks & out) const override; llama_persona_move persona_check_load(llama_seq_id seq_id, uint32_t stream, const llama_persona_blocks & in, llama_persona_slot & slot) const override; void persona_commit_save(llama_seq_id seq_id, llama_persona_blocks & out) override; - void persona_commit_load(llama_seq_id seq_id, const llama_persona_slot & slot, llama_persona_blocks & in) override; + void persona_commit_load(llama_seq_id seq_id, llama_persona_slot & slot, llama_persona_blocks & in) override; // an undo of a draft is pending on this sequence: its next read takes a snapshot group, not the // live state (group 0) a training graph reads and writes (llm_graph_context::rs_keep) diff --git a/src/llama-memory.cpp b/src/llama-memory.cpp index 431639390244..5f84200704dc 100644 --- a/src/llama-memory.cpp +++ b/src/llama-memory.cpp @@ -71,6 +71,8 @@ const char * llama_persona_move_name(llama_persona_move m) { case llama_persona_move::seq_holds_state: return "seq_holds_state"; case llama_persona_move::shared_cell: return "shared_cell"; case llama_persona_move::no_free_cell: return "no_free_cell"; + case llama_persona_move::wrong_persona: return "wrong_persona"; + case llama_persona_move::invalid_rollback: return "invalid_rollback"; } return "unknown"; } diff --git a/src/llama-memory.h b/src/llama-memory.h index 5585f4b26a0a..4a49526d3ab8 100644 --- a/src/llama-memory.h +++ b/src/llama-memory.h @@ -153,14 +153,15 @@ struct llama_memory_i { virtual uint32_t seq_stream(llama_seq_id seq_id) const { return (uint32_t) seq_id; } // Continuum fork (CONTINUUM-ENGINE 4.14): a persona's state moved raw between this memory and host memory, two - // phases. persona_prepare runs once per persona (sizes her blocks). check_* are const: every condition of the move - // is decided and the destination reserved there; commit_* only copy and write records, and cannot fail. Callers go + // phases. persona_prepare runs once per persona (sizes her blocks, records the layout). check_* decide every + // condition without touching the memory, and reserve the destination and every byte and node the commit needs; + // commit_* only copy, swap and insert reserved nodes: nothing allocates, so a commit cannot fail. Callers go // through llama_context::persona_save / persona_load, which fence the queued device work first. virtual llama_persona_move persona_prepare(llama_persona_blocks & blocks) const { (void) blocks; return llama_persona_move::unsupported; } - virtual llama_persona_move persona_check_save(llama_seq_id seq_id, const llama_persona_blocks & out) const { + virtual llama_persona_move persona_check_save(llama_seq_id seq_id, llama_persona_blocks & out) const { (void) seq_id; (void) out; return llama_persona_move::unsupported; } @@ -170,7 +171,7 @@ struct llama_memory_i { return llama_persona_move::unsupported; } virtual void persona_commit_save(llama_seq_id seq_id, llama_persona_blocks & out) { (void) seq_id; (void) out; } - virtual void persona_commit_load(llama_seq_id seq_id, const llama_persona_slot & slot, llama_persona_blocks & in) { + virtual void persona_commit_load(llama_seq_id seq_id, llama_persona_slot & slot, llama_persona_blocks & in) { (void) seq_id; (void) slot; (void) in; } diff --git a/src/llama-persona-blocks.h b/src/llama-persona-blocks.h index f0eb5c6a623f..c278c59ebacc 100644 --- a/src/llama-persona-blocks.h +++ b/src/llama-persona-blocks.h @@ -2,13 +2,15 @@ // Continuum fork (CONTINUUM-ENGINE 4.14): a persona's execution state, out of the memory pool, as native blocks. // Moving a persona between the pool and host memory is raw row copies plus her small records; nothing is walked, -// serialized or recomputed. Every move is two-phase: validate (const, reserves the destination, refuses with a typed -// outcome) and commit (copies and record writes only, which cannot fail), so a refusal never leaves her split. +// serialized or recomputed. Every move is two-phase: check (decides every condition, reserves the destination and every +// byte and node the commit needs; refuses with a typed outcome) and commit (copies, swaps and reserved-node inserts: +// nothing allocates, so it cannot fail), so a refusal never leaves her split. #include "llama.h" #include "llama-kv-cells.h" #include +#include #include // her attention state: per KV layer, the rows she uses of one stream, and her cell metadata OWNED here (exchanged with @@ -30,15 +32,22 @@ struct llama_rs_seq_blocks { std::vector> s; // per layer: (1 + n_rs_seq) rows of s, group-major }; +// her identity travels with her blocks: the sequence her metadata is tagged with, and the layout of the memory they +// were prepared for (a fingerprint of layer count, stream size, row types and sizes, snapshot groups) struct llama_persona_blocks { + llama_seq_id seq = -1; + uint64_t kv_layout = 0; + uint64_t rs_layout = 0; llama_kv_stream_blocks kv; llama_rs_seq_blocks rs; }; -// where a load puts her: the attention stream, and the recurrent cell reserved by validation +// where a load puts her, reserved by the check phase: the attention stream, the recurrent cell, and the cell's +// sequence-set node (built in the check phase so the commit inserts it without allocating) struct llama_persona_slot { - uint32_t stream = 0; - int32_t cell = -1; + uint32_t stream = 0; + int32_t cell = -1; + std::set::node_type node; }; enum class llama_persona_move { @@ -53,6 +62,8 @@ enum class llama_persona_move { seq_holds_state, // a load requires her sequence to hold no state shared_cell, // her recurrent cell is shared with another sequence: not hers alone to move no_free_cell, // no free recurrent cell to load into + wrong_persona, // her blocks belong to another sequence (her metadata is tagged with it; never retagged) + invalid_rollback, // her rollback index exceeds this memory's snapshot groups }; const char * llama_persona_move_name(llama_persona_move m); diff --git a/tests/test-persona-blocks.cpp b/tests/test-persona-blocks.cpp index 86105207141b..22deda7e5487 100644 --- a/tests/test-persona-blocks.cpp +++ b/tests/test-persona-blocks.cpp @@ -5,6 +5,10 @@ // (stream holding state, blocks not prepared, layout mismatch, sequence holding state) must be typed and change // nothing. Runs on a plain KV model and on a hybrid (attention + recurrent, e.g. a tiny random qwen35moe from // `test-llama-archs -a qwen35moe -o DIR`); the same interface covers both. +// +// Measure mode (-n N, a prompt of N tokens): only the timed move runs. It reports what recomputing her costs (the +// prefill of her N tokens) against the fenced save and load of her native state (bytes, ms, GB/s), and still requires +// her next tokens to be byte-identical after the move. #include "arg.h" #include "common.h" @@ -58,13 +62,17 @@ struct fixture { return out; } - // her prompt (salt makes two personas' prompts differ) + // her prompt (salt makes two personas' prompts differ), decoded in batches of n_batch + int n_batch = 2048; void prompt(llama_seq_id seq, int salt) { - llama_batch b = llama_batch_init(n_prompt, 0, 1); - for (int i = 0; i < n_prompt; ++i) { - common_batch_add(b, 1 + (i * 7 + salt * 13) % (n_vocab - 1), i, { seq }, false); + llama_batch b = llama_batch_init(n_batch, 0, 1); + for (int i0 = 0; i0 < n_prompt; i0 += n_batch) { + common_batch_clear(b); + for (int i = i0; i < std::min(n_prompt, i0 + n_batch); ++i) { + common_batch_add(b, 1 + (i * 7 + salt * 13) % (n_vocab - 1), i, { seq }, false); + } + require(llama_decode(ctx, b) == 0, "decode a prompt"); } - require(llama_decode(ctx, b) == 0, "decode a prompt"); llama_batch_free(b); } @@ -107,10 +115,50 @@ int main(int argc, char ** argv) { f.n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(llama_get_model(f.ctx))); llama_context & ctx = *f.ctx; + f.n_batch = (int) llama_n_batch(f.ctx); + llama_persona_blocks a, b; require_move(ctx.persona_prepare(a), llama_persona_move::done, "prepare persona a"); require_move(ctx.persona_prepare(b), llama_persona_move::done, "prepare persona b"); + if (params.n_predict > 0) { + // measure mode: what recomputing her costs (prefill) vs her native state moved out and back. Recurrent state + // cannot be rolled back, so the in-place reference comes from a second, clean run. + f.n_prompt = params.n_predict; + llama_memory_clear(llama_get_memory(f.ctx), true); + const int64_t t0 = ggml_time_us(); + f.prompt(0, 1); + llama_synchronize(f.ctx); + const int64_t t_prefill = ggml_time_us() - t0; + + const int64_t t1 = ggml_time_us(); + require_move(ctx.persona_save(0, a), llama_persona_move::done, "her state out"); + const int64_t t_save = ggml_time_us() - t1; + size_t bytes = 0; + for (const auto & v : a.kv.k) { bytes += v.size(); } + for (const auto & v : a.kv.v) { bytes += v.size(); } + for (const auto & v : a.rs.r) { bytes += v.size(); } + for (const auto & v : a.rs.s) { bytes += v.size(); } + const uint32_t other = 1 - llama_get_memory(f.ctx)->seq_stream(0); + const int64_t t2 = ggml_time_us(); + require_move(ctx.persona_load(0, other, a), llama_persona_move::done, "her state into the other stream"); + const int64_t t_load = ggml_time_us() - t2; + std::vector> moved; + moved.push_back(f.decode_one(0, 3 % f.n_vocab, f.n_prompt)); + moved.push_back(f.decode_one(0, 5 % f.n_vocab, f.n_prompt + 1)); + + llama_memory_clear(llama_get_memory(f.ctx), true); + f.prompt(0, 1); + f.require_continues("her next tokens after the timed move", 0, moved); + + const double gb = bytes / 1e9; + fprintf(stderr, "measure: n_prompt=%d state=%.1f MB | recompute (prefill) %.1f ms (%.0f tok/s) | " + "save %.2f ms (%.2f GB/s) | load %.2f ms (%.2f GB/s) | load is %.0fx faster than recompute\n", + f.n_prompt, bytes / 1e6, t_prefill / 1e3, f.n_prompt / (t_prefill / 1e6), + t_save / 1e3, gb / (t_save / 1e6), t_load / 1e3, gb / (t_load / 1e6), (double) t_prefill / t_load); + return 0; + } + const auto ref_a0 = f.reference(0, 1); // persona a on sequence 0 const auto ref_b1 = f.reference(1, 2); // persona b on sequence 1 @@ -119,6 +167,9 @@ int main(int argc, char ** argv) { f.prompt(0, 1); require_move(ctx.persona_save(0, a), llama_persona_move::done, "a out"); require(f.pos_max(0) < 0, "nothing of a is left in the memory"); + require(a.seq == 0, "her blocks carry her sequence"); + require_move(ctx.persona_load(1, 1, a), llama_persona_move::wrong_persona, "a refused as sequence 1 (never retagged)"); + require(f.pos_max(1) < 0, "the refused load wrote nothing"); require_move(ctx.persona_load(0, 1, a), llama_persona_move::done, "a into stream 1"); require(f.pos_max(0) == f.n_prompt - 1, "a's sequence holds her prompt"); f.require_continues("a moved to stream 1", 0, ref_a0); @@ -157,6 +208,12 @@ int main(int argc, char ** argv) { bad.kv.k.pop_back(); require_move(ctx.persona_load(0, 1 - occupied, bad), llama_persona_move::layout_mismatch, "a layout mismatch"); require(f.pos_max(0) < 0, "a refused load writes nothing"); + if (a.rs.has_state) { // hybrid: a rollback index past the snapshot groups is refused before any write + llama_persona_blocks far = a; + far.rs.rs_idx = 1u << 20; + require_move(ctx.persona_load(0, 1 - occupied, far), llama_persona_move::invalid_rollback, "a rollback out of bounds"); + require(f.pos_max(0) < 0, "a refused hybrid load writes neither half"); + } require_move(ctx.persona_load(0, 1 - occupied, a), llama_persona_move::done, "a back after the refusals"); f.require_continues("a after the refusals", 0, ref_a0); From 70ab7f70b0e8de25603891ad9d5b820bf14a5509 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 22:10:31 -0600 Subject: [PATCH 05/28] memory: layout identity computed once; allocation-fault and rollback-group proofs (Codex's 8c186c8e6 review) - persona_layout() returns an id computed once at construction (KV cache, recurrent memory): the allocation layout is immutable, so no per-check rehash of every layer. - test-persona-blocks: - allocation faults: both commits run with every allocation in the process failing (global operator new armed) and complete; a reserve phase failing on allocation leaves her in the memory and continuing byte-identical. - rollback groups (--test-rs-seq N: serving's draft-mtp configuration, n_rs_seq = N): her state moved while a rollback is pending (two drafted tokens, one taken back) continues exactly. ## Measured (M5 Metal, this tree, serving down 04:09:12-04:09:19Z) test-persona-blocks passes on stories15M (ctest), tiny random qwen35moe, and tiny qwen35moe with --test-rs-seq 4 (n_rs_seq=4, her rs_idx=1 carried; continuation max|diff| 0). Test binary sha256 939384c5cab7fd124852454f25e872b449fe1df69a6cdc4c9cb00b70b258040b. Not yet: model/genome owner identity in her blocks (needed before any persistent-tier reuse). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- src/llama-kv-cache.cpp | 4 +- src/llama-kv-cache.h | 6 ++- src/llama-memory-recurrent.cpp | 4 +- src/llama-memory-recurrent.h | 6 ++- tests/test-persona-blocks.cpp | 97 +++++++++++++++++++++++++++++++++- 5 files changed, 112 insertions(+), 5 deletions(-) diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index cdd0427bdc6a..5f45c25a8166 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -363,6 +363,8 @@ llama_kv_cache::llama_kv_cache( const char * LLAMA_KV_CACHE_DEBUG = getenv("LLAMA_KV_CACHE_DEBUG"); debug = LLAMA_KV_CACHE_DEBUG ? atoi(LLAMA_KV_CACHE_DEBUG) : 0; + + persona_layout_id = compute_persona_layout(); // the allocation layout is immutable from here } void llama_kv_cache::clear(bool data) { @@ -1239,7 +1241,7 @@ static bool cells_prepared(const llama_kv_cells & cells, uint32_t size) { // this memory's attention layout: what her rows' sizes and meaning depend on static uint64_t kv_layout_mix(uint64_t h, uint64_t v) { return (h ^ v) * 0x100000001b3ull; } -uint64_t llama_kv_cache::persona_layout() const { +uint64_t llama_kv_cache::compute_persona_layout() const { uint64_t h = kv_layout_mix(0xcbf29ce484222325ull, layers.size()); h = kv_layout_mix(h, get_size()); for (const auto & layer : layers) { diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h index 691e26ed73e1..3a0272f2f5da 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -179,7 +179,7 @@ class llama_kv_cache : public llama_memory_i { // swap with an already-empty object (never reset or walked), her own sequence id bound to the stream she lands on // (seq_to_stream stays a permutation; her cells are never retagged). Requires unified KV off and flash attention. llama_persona_move persona_prepare(llama_persona_blocks & blocks) const override; - uint64_t persona_layout() const; + uint64_t persona_layout() const { return persona_layout_id; } llama_persona_move persona_check_save(llama_seq_id seq_id, llama_persona_blocks & out) const override; llama_persona_move persona_check_load(llama_seq_id seq_id, uint32_t stream, const llama_persona_blocks & in, llama_persona_slot & slot) const override; @@ -303,6 +303,10 @@ class llama_kv_cache : public llama_memory_i { // maps from a sequence id to a stream id std::vector seq_to_stream; + // this memory's persona layout fingerprint, computed once at construction (the allocation layout is immutable) + uint64_t persona_layout_id = 0; + uint64_t compute_persona_layout() const; + // pending stream copies that will be applied during the next update stream_copy_info sc_info; diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp index f4a2806ee5de..f958082c7e0b 100644 --- a/src/llama-memory-recurrent.cpp +++ b/src/llama-memory-recurrent.cpp @@ -125,6 +125,8 @@ llama_memory_recurrent::llama_memory_recurrent( ggml_type_name(type_r), (float)memory_size_r / (1024.0f * 1024.0f), ggml_type_name(type_s), (float)memory_size_s / (1024.0f * 1024.0f)); } + + persona_layout_id = compute_persona_layout(); // the allocation layout is immutable from here } void llama_memory_recurrent::clear(bool data) { @@ -394,7 +396,7 @@ llama_pos llama_memory_recurrent::seq_pos_max(llama_seq_id seq_id) const { static uint64_t rs_layout_mix(uint64_t h, uint64_t v) { return (h ^ v) * 0x100000001b3ull; } -uint64_t llama_memory_recurrent::persona_layout() const { +uint64_t llama_memory_recurrent::compute_persona_layout() const { uint64_t h = rs_layout_mix(0xcbf29ce484222325ull, r_l.size()); h = rs_layout_mix(h, size); h = rs_layout_mix(h, n_rs_seq); diff --git a/src/llama-memory-recurrent.h b/src/llama-memory-recurrent.h index 6dfdc4ce9675..13ac2127614b 100644 --- a/src/llama-memory-recurrent.h +++ b/src/llama-memory-recurrent.h @@ -89,7 +89,7 @@ class llama_memory_recurrent : public llama_memory_i { // a load takes the free cell reserved by check_load (a search over this memory's cells, one per sequence slot: // bounded by the slot count, not by context length). Her sequence id is kept. llama_persona_move persona_prepare(llama_persona_blocks & blocks) const override; - uint64_t persona_layout() const; + uint64_t persona_layout() const { return persona_layout_id; } llama_persona_move persona_check_save(llama_seq_id seq_id, llama_persona_blocks & out) const override; llama_persona_move persona_check_load(llama_seq_id seq_id, uint32_t stream, const llama_persona_blocks & in, llama_persona_slot & slot) const override; @@ -138,6 +138,10 @@ class llama_memory_recurrent : public llama_memory_i { private: uint32_t protected_first = 0, protected_count = 0; + + // this memory's persona layout fingerprint, computed once at construction (the allocation layout is immutable) + uint64_t persona_layout_id = 0; + uint64_t compute_persona_layout() const; //const llama_model & model; const llama_hparams & hparams; diff --git a/tests/test-persona-blocks.cpp b/tests/test-persona-blocks.cpp index 22deda7e5487..55012e0e3184 100644 --- a/tests/test-persona-blocks.cpp +++ b/tests/test-persona-blocks.cpp @@ -17,12 +17,33 @@ #include "../src/llama-context.h" #include +#include +#include #include #include #include #include #include +// allocation fault injection: while armed, every allocation in this process throws std::bad_alloc +static std::atomic g_fail_alloc { false }; + +static void * checked_alloc(std::size_t n) { + if (g_fail_alloc.load(std::memory_order_relaxed)) { + throw std::bad_alloc(); + } + if (void * p = std::malloc(n ? n : 1)) { + return p; + } + throw std::bad_alloc(); +} +void * operator new(std::size_t n) { return checked_alloc(n); } +void * operator new[](std::size_t n) { return checked_alloc(n); } +void operator delete(void * p) noexcept { std::free(p); } +void operator delete[](void * p) noexcept { std::free(p); } +void operator delete(void * p, std::size_t) noexcept { std::free(p); } +void operator delete[](void * p, std::size_t) noexcept { std::free(p); } + static void require(bool condition, const char * message) { if (!condition) { fprintf(stderr, "FAILED: %s\n", message); @@ -103,8 +124,19 @@ int main(int argc, char ** argv) { params.n_parallel = 2; params.n_ctx = 512; params.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_ENABLED; // V rows contiguous + // --test-rs-seq N: the speculative configuration serving uses (draft-mtp, n_max N), which gives the context N + // rollback snapshot groups (common_params_speculative::need_n_rs_seq); stripped before the common parse + std::vector args(argv, argv + argc); + for (size_t i = 1; i + 1 < args.size(); ++i) { + if (std::strcmp(args[i], "--test-rs-seq") == 0) { + params.speculative.types = { COMMON_SPECULATIVE_TYPE_DRAFT_MTP }; + params.speculative.draft.n_max = std::atoi(args[i + 1]); + args.erase(args.begin() + i, args.begin() + i + 2); + break; + } + } common_init(); - if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_COMMON)) { + if (!common_params_parse((int) args.size(), args.data(), params, LLAMA_EXAMPLE_COMMON)) { return 1; } ggml_backend_load_all(); @@ -238,6 +270,69 @@ int main(int argc, char ** argv) { f.require_continues("b after the exchange", 1, ref_b1); } + // 7. allocation faults: a commit allocates nothing (it runs with every allocation failing), and an allocation + // failure in the reserve phase leaves her whole and continuing exactly + { + llama_memory_t mem = llama_get_memory(f.ctx); + llama_memory_clear(mem, true); + f.prompt(0, 1); + llama_synchronize(f.ctx); + llama_persona_blocks c; + require_move(ctx.persona_prepare(c), llama_persona_move::done, "prepare persona c"); + require_move(mem->persona_check_save(0, c), llama_persona_move::done, "check (reserve) c's save"); + g_fail_alloc = true; + mem->persona_commit_save(0, c); // must not allocate: any allocation throws and aborts the test + g_fail_alloc = false; + require(f.pos_max(0) < 0, "c's commit took her out"); + llama_persona_slot slot; + require_move(mem->persona_check_load(0, 1 - mem->seq_stream(0), c, slot), llama_persona_move::done, "check c's load"); + g_fail_alloc = true; + mem->persona_commit_load(0, slot, c); + g_fail_alloc = false; + f.require_continues("c after allocation-free commits", 0, ref_a0); + + llama_memory_clear(mem, true); + f.prompt(0, 1); + llama_synchronize(f.ctx); + llama_persona_blocks d; + require_move(ctx.persona_prepare(d), llama_persona_move::done, "prepare persona d"); + bool reserve_failed = false; + g_fail_alloc = true; + try { + (void) mem->persona_check_save(0, d); + } catch (const std::bad_alloc &) { + reserve_failed = true; + } + g_fail_alloc = false; + require(reserve_failed, "the reserve phase allocates (and here fails)"); + require(f.pos_max(0) == f.n_prompt - 1, "a failed reserve leaves her in the memory"); + f.require_continues("her after a failed reserve", 0, ref_a0); + } + + // 6. with rollback snapshot groups (n_rs_seq > 0, e.g. --spec-type draft-mtp --spec-draft-n-max 4): her state is + // moved while a rollback is pending (two drafted tokens, one taken back) and she continues exactly as in place + if (llama_n_rs_seq(f.ctx) > 0) { + auto drafted_then_rolled_back = [&]() { + llama_memory_clear(llama_get_memory(f.ctx), true); + f.prompt(0, 1); + f.decode_one(0, 3 % f.n_vocab, f.n_prompt); + f.decode_one(0, 5 % f.n_vocab, f.n_prompt + 1); + require(llama_memory_seq_rm(llama_get_memory(f.ctx), 0, f.n_prompt + 1, -1), "take the second draft back"); + }; + drafted_then_rolled_back(); + const std::vector in_place = f.decode_one(0, 7 % f.n_vocab, f.n_prompt + 1); + + drafted_then_rolled_back(); + llama_persona_blocks r; + require_move(ctx.persona_prepare(r), llama_persona_move::done, "prepare persona r"); + require_move(ctx.persona_save(0, r), llama_persona_move::done, "r out with a rollback pending"); + require(!r.rs.has_state || r.rs.rs_idx > 0, "her pending rollback travels with her"); + require_move(ctx.persona_load(0, 1 - llama_get_memory(f.ctx)->seq_stream(0), r), llama_persona_move::done, "r in"); + require_identical("continues after a move with a rollback pending", in_place, + f.decode_one(0, 7 % f.n_vocab, f.n_prompt + 1)); + fprintf(stderr, "rollback groups exercised: n_rs_seq=%u, her rs_idx=%u\n", llama_n_rs_seq(f.ctx), r.rs.rs_idx); + } + fprintf(stderr, "test-persona-blocks: ok (%zu attention layers, %zu recurrent layers)\n", a.kv.k.size(), a.rs.r.size()); return 0; } From 0441cbbed89e0869bc34f1f531ad9df85aca069a Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 22:20:43 -0600 Subject: [PATCH 06/28] memory: recurrent rows move through per-tensor helpers (GCC -Werror=dangling-reference on a range-for over {make_pair(...)}) Same copies, no temporary pairs. Verified on Metal, M5 (serving down 04:19:15-04:20:23Z): test-persona-blocks passes on stories15M (ctest), tiny qwen35moe, and tiny qwen35moe --test-rs-seq 4 (pending rollback carried, continuation byte-identical). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- src/llama-memory-recurrent.cpp | 42 +++++++++++++++++++--------------- 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp index f958082c7e0b..f94c65df5962 100644 --- a/src/llama-memory-recurrent.cpp +++ b/src/llama-memory-recurrent.cpp @@ -448,16 +448,19 @@ void llama_memory_recurrent::persona_commit_save(llama_seq_id seq_id, llama_pers return; } const uint32_t n_groups = 1 + n_rs_seq; - for (size_t il = 0; il < r_l.size(); ++il) { - for (auto [src, dst] : { std::make_pair(r_l[il], &rs.r[il]), std::make_pair(s_l[il], &rs.s[il]) }) { - if (src == nullptr || dst->empty()) { - continue; - } - const size_t row = ggml_row_size(src->type, src->ne[0]); - for (uint32_t g = 0; g < n_groups; ++g) { - ggml_backend_tensor_get(src, dst->data() + g * row, (size_t) (g * size + tail) * src->nb[1], row); - } + // her row of one state tensor, in every snapshot group, into her reserved bytes + const auto rows_out = [&](const ggml_tensor * src, std::vector & dst) { + if (src == nullptr || dst.empty()) { + return; } + const size_t row = ggml_row_size(src->type, src->ne[0]); + for (uint32_t g = 0; g < n_groups; ++g) { + ggml_backend_tensor_get(src, dst.data() + g * row, (size_t) (g * size + tail) * src->nb[1], row); + } + }; + for (size_t il = 0; il < r_l.size(); ++il) { + rows_out(r_l[il], rs.r[il]); + rows_out(s_l[il], rs.s[il]); } auto & cell = cells[tail]; rs.pos = cell.pos; @@ -527,16 +530,19 @@ void llama_memory_recurrent::persona_commit_load(llama_seq_id seq_id, llama_pers } const int32_t cell_id = slot.cell; const uint32_t n_groups = 1 + n_rs_seq; - for (size_t il = 0; il < r_l.size(); ++il) { - for (auto [dst, src] : { std::make_pair(r_l[il], &rs.r[il]), std::make_pair(s_l[il], &rs.s[il]) }) { - if (dst == nullptr) { - continue; - } - const size_t row = ggml_row_size(dst->type, dst->ne[0]); - for (uint32_t g = 0; g < n_groups; ++g) { - ggml_backend_tensor_set(dst, src->data() + g * row, (size_t) (g * size + cell_id) * dst->nb[1], row); - } + // her row of one state tensor, in every snapshot group, from her bytes into the reserved cell + const auto rows_in = [&](ggml_tensor * dst, const std::vector & src) { + if (dst == nullptr) { + return; } + const size_t row = ggml_row_size(dst->type, dst->ne[0]); + for (uint32_t g = 0; g < n_groups; ++g) { + ggml_backend_tensor_set(dst, src.data() + g * row, (size_t) (g * size + cell_id) * dst->nb[1], row); + } + }; + for (size_t il = 0; il < r_l.size(); ++il) { + rows_in(r_l[il], rs.r[il]); + rows_in(s_l[il], rs.s[il]); } auto & cell = cells[cell_id]; cell.pos = rs.pos; From 45dadf0e67b9dc9c1c97fcf67b993a4c0a257d41 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 22:33:34 -0600 Subject: [PATCH 07/28] tests: test-persona-blocks joins the internal-API tests (Windows shared builds do not export llama_context internals); CI runs it on the generated hybrid and with rollback groups Windows CI (lld-link: undefined llama_context::persona_* / llama_persona_move_name) linked the test against a llama.dll that exports only LLAMA_API. It now builds in the existing 'NOT WIN32 OR NOT BUILD_SHARED_LIBS' block, beside test-llama-archs, and CI runs it three ways: - test-persona-blocks: stories15M (download fixture) - test-persona-blocks-hybrid: generated qwen35moe (generate-models fixture) - test-persona-blocks-rollback: generated qwen35moe --test-rs-seq 4 Checked by configure + ctest -N (tests #40, #41, #66 registered); no build beside serving. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tests/CMakeLists.txt | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index b998b9fb2484..4896b5e40653 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -260,6 +260,25 @@ if (NOT WIN32 OR NOT BUILD_SHARED_LIBS) FIXTURES_SETUP generate-models ) + # a persona's state moved raw between the memory and host memory is byte-identical, and a refused move changes + # nothing (CONTINUUM-ENGINE 4.14): on a plain KV model, on the generated hybrid (qwen35moe: attention + recurrent), + # and on the hybrid with the rollback groups serving's draft-mtp configuration creates + llama_build(test-persona-blocks.cpp) + llama_test( + test-persona-blocks + NAME test-persona-blocks-hybrid + LABEL main + ARGS -m "${MODEL_DIR}/qwen35moe-moe.gguf" + ) + set_tests_properties(test-persona-blocks-hybrid PROPERTIES FIXTURES_REQUIRED generate-models) + llama_test( + test-persona-blocks + NAME test-persona-blocks-rollback + LABEL main + ARGS -m "${MODEL_DIR}/qwen35moe-moe.gguf" --test-rs-seq 4 + ) + set_tests_properties(test-persona-blocks-rollback PROPERTIES FIXTURES_REQUIRED generate-models) + llama_test( test-recurrent-state-rollback LABEL main @@ -355,10 +374,11 @@ llama_build_and_test(test-dup-quantized.cpp) llama_build_and_test(test-state-restore-streams.cpp LABEL "model" ARGS -m "${MODEL_DEST}") set_tests_properties(test-state-restore-streams PROPERTIES FIXTURES_REQUIRED test-download-model) -# a persona's state moved raw between the memory and host memory is byte-identical, and a refused move changes nothing -# (CONTINUUM-ENGINE 4.14); also run on a hybrid model written by `test-llama-archs -a qwen35moe -o DIR` -llama_build_and_test(test-persona-blocks.cpp LABEL "model" ARGS -m "${MODEL_DEST}") -set_tests_properties(test-persona-blocks PROPERTIES FIXTURES_REQUIRED test-download-model) +if (NOT WIN32 OR NOT BUILD_SHARED_LIBS) + # test-persona-blocks (built above with the internal-API tests) on the downloaded plain KV model + llama_test(test-persona-blocks LABEL "model" ARGS -m "${MODEL_DEST}") + set_tests_properties(test-persona-blocks PROPERTIES FIXTURES_REQUIRED test-download-model) +endif() # Test state save/load functionality llama_build_and_test(test-save-load-state.cpp LABEL "model" ARGS -m "${MODEL_DEST}") From accc9e3b10466b842f092d985865b91f8b6646ab Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 16 Nov 2026 23:04:54 -0600 Subject: [PATCH 08/28] kv-cells: member swap that never allocates; a persona's cells move with it (Windows CI: the allocation-free commit allocated) windows/x64-cpu-static aborted (0xc0000409) in test-persona-blocks' allocation-fault variant: the commit allocated. std::swap of llama_kv_cells moves through a temporary, and MSVC's std::set/std::map move constructors allocate a sentinel node (libc++ does not, so macOS passed). llama_kv_cells::swap exchanges each member with its own container swap (no allocation on any standard library); the KV cache's persona commits use it. Not run locally: serving-down windows on the M5 are on hold (shutdown custody); CI (Windows static, Ubuntu, macOS) is the verification for this commit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- src/llama-kv-cache.cpp | 4 ++-- src/llama-kv-cells.h | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index 5f45c25a8166..f30c0bdfa52d 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -1305,7 +1305,7 @@ void llama_kv_cache::persona_commit_save(llama_seq_id seq_id, llama_persona_bloc } } out.seq = seq_id; - std::swap(out.kv.cells, cells); // hers out; the stream takes the prepared empty object + out.kv.cells.swap(cells); // hers out; the stream takes the prepared empty object v_heads[s] = 0; } @@ -1360,7 +1360,7 @@ void llama_kv_cache::persona_commit_load(llama_seq_id seq_id, llama_persona_slot ggml_backend_tensor_set(layer.v_stream[s], in.kv.v[i].data(), 0, in.kv.v[i].size()); } } - std::swap(in.kv.cells, v_cells[s]); // hers in; her blocks keep the stream's empty object for her next save + in.kv.cells.swap(v_cells[s]); // hers in; her blocks keep the stream's empty object for her next save v_heads[s] = 0; // bind her own sequence id to stream s; the sequence that held s takes her old stream (both empty of others) const uint32_t old = seq_to_stream[seq_id]; diff --git a/src/llama-kv-cells.h b/src/llama-kv-cells.h index fddd31a0b219..4279acfdfa29 100644 --- a/src/llama-kv-cells.h +++ b/src/llama-kv-cells.h @@ -31,6 +31,22 @@ struct llama_kv_cell_ext { // TODO: add unit tests class llama_kv_cells { public: + // Continuum fork (CONTINUUM-ENGINE 4.14): exchange two cells objects in place, member by member, with each + // container's own swap: never allocates on any standard library (a std::swap of the whole object moves through a + // temporary, and MSVC's node containers allocate a sentinel when move-constructed). A persona's metadata moves + // between her blocks and a stream with this. + void swap(llama_kv_cells & other) noexcept { + std::swap(has_shift, other.has_shift); + used.swap(other.used); + pos.swap(other.pos); + ext.swap(other.ext); + shift.swap(other.shift); + seq.swap(other.seq); + for (int s = 0; s < LLAMA_MAX_SEQ; ++s) { + seq_pos[s].swap(other.seq_pos[s]); + } + } + void reset() { for (uint32_t i = 0; i < pos.size(); ++i) { pos[i] = -1; From 2d54d48697c2e2df807f88d7789f358885631698 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 08:31:41 -0600 Subject: [PATCH 09/28] kv-cells: the two derived indices held natively, so a persona's metadata has no node containers CONTINUUM-ENGINE 4.14, the flash tier (direction agreed by Codex for an isolated prototype, not layout sign-off): llama_kv_cells derived `used` (std::set) and `seq_pos` (std::map per sequence) from its cells. A flash generation cannot hold node containers, and rebuilding them on load is the recomputation the design forbids. Now: - llama_kv_used: a bitmap over the cell rows with its count and extrema (bounded by the stream size, never a position); insert/erase O(1), an extremum leaving scans forward/back to the next occupied cell. - llama_kv_seq_pos: each sequence's positions sorted with their counts, its own array (a change to one sequence never moves another's). Exact on its O(1) paths (append at her newest position, rollback/removal of it); any other change (removal inside the range, a shift, a division that merges positions) marks it stale, and the next query recomputes it once from the cells (scan, sort, merge of equal positions), never cell by cell (a front discard cell by cell would be quadratic in a flat array). - swap stays allocation-free (vector swaps). test-kv-cell-index: 8 seeds x 20000 random cache operations (appends with repeats, shared sequences, removals, seq_rm/seq_keep, shifts below zero, divisions that merge) against a reference with the replaced std::set/std::map, compared after every step; `--cost` times the same append/discard/shift workload on both at 4k/32k/100k cells. Not yet: the flash generation itself (typed header, owner identity, checksums, one fenced generation with recurrent, draft, sampler and genome), and the cost receipts (need a serving-down window on the M5 to build). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- src/llama-kv-cell-index.h | 238 +++++++++++++++++++++++++++++++++++ src/llama-kv-cells.h | 65 +++++----- tests/CMakeLists.txt | 3 + tests/test-kv-cell-index.cpp | 195 ++++++++++++++++++++++++++++ 4 files changed, 469 insertions(+), 32 deletions(-) create mode 100644 src/llama-kv-cell-index.h create mode 100644 tests/test-kv-cell-index.cpp diff --git a/src/llama-kv-cell-index.h b/src/llama-kv-cell-index.h new file mode 100644 index 000000000000..f5901150f8ff --- /dev/null +++ b/src/llama-kv-cell-index.h @@ -0,0 +1,238 @@ +#pragma once + +// Continuum fork (CONTINUUM-ENGINE 4.14, the flash tier): the two indices llama_kv_cells derives from its cells, held +// in native memory. A persona's metadata then has no node containers (std::set, std::map), so her generation on flash +// can be the image of what is in memory and a load binds it, never rebuilding an index for state that did not change. +// +// - llama_kv_used: which cells are occupied, a bitmap over the cell rows (bounded by the stream size, never by a +// position), with its count and its extrema kept as cells change. +// - llama_kv_seq_pos: one sequence's positions, sorted, each with how many cells hold it (duplicates are allowed: cache +// reuse rm+add, repeated M-RoPE positions). Bounded by the cells (each cell adds at most one entry per sequence), +// never a histogram by absolute position. Each sequence owns its own array, so a change to one never moves +// another's. +// +// The common changes are O(1): a token appended at her newest position, and a rollback or removal of her newest +// position. Any other change (a removal inside the range, a shift, a division that merges positions) marks the +// sequence's index stale instead of editing it cell by cell, and the next query recomputes it once from the cells, the +// one truth (a scan, a sort, and a merge of equal positions): work done only because her positions actually changed. + +#include "llama.h" + +#include +#include +#include +#include +#include + +// Which cells are occupied: a bitmap over the cell rows, its count, and its extrema. +class llama_kv_used { +public: + void resize(uint32_t n_cells) { + words.assign((n_cells + 63) / 64, 0); + n_used = lo = hi = 0; + } + + void clear() { + std::fill(words.begin(), words.end(), 0); + n_used = lo = hi = 0; + } + + void insert(uint32_t i) { + uint64_t & word = words[i / 64]; + const uint64_t bit = uint64_t(1) << (i % 64); + if (word & bit) { + return; + } + word |= bit; + if (n_used++ == 0) { + lo = i; + hi = i + 1; + return; + } + lo = std::min(lo, i); + hi = std::max(hi, i + 1); + } + + void erase(uint32_t i) { + uint64_t & word = words[i / 64]; + const uint64_t bit = uint64_t(1) << (i % 64); + if (!(word & bit)) { + return; + } + word &= ~bit; + if (--n_used == 0) { + lo = hi = 0; + return; + } + if (i == lo) { + lo = next_from(i + 1); + } + if (i + 1 == hi) { + hi = prev_from(i) + 1; + } + } + + uint32_t size() const { return n_used; } + bool empty() const { return n_used == 0; } + + // the first occupied cell, 0 when none is + uint32_t min() const { return lo; } + + // one past the last occupied cell, 0 when none is + uint32_t max_p1() const { return hi; } + + void swap(llama_kv_used & other) noexcept { + words.swap(other.words); + std::swap(n_used, other.n_used); + std::swap(lo, other.lo); + std::swap(hi, other.hi); + } + + bool operator==(const llama_kv_used & other) const { + return n_used == other.n_used && lo == other.lo && hi == other.hi && words == other.words; + } + +private: + std::vector words; + uint32_t n_used = 0; + uint32_t lo = 0; + uint32_t hi = 0; + + // the first occupied cell at or after i; one exists (called only while n_used > 0, after an extremum at i - 1 left) + uint32_t next_from(uint32_t i) const { + for (size_t w = i / 64; w < words.size(); ++w) { + uint64_t word = words[w]; + if (w == i / 64) { + word &= ~uint64_t(0) << (i % 64); + } + if (word) { + return uint32_t(w * 64 + lowest_bit(word)); + } + } + assert(false && "an occupied cell remains"); + return 0; + } + + // the last occupied cell before i; one exists (called only while n_used > 0, after an extremum at i left) + uint32_t prev_from(uint32_t i) const { + for (size_t w = (i == 0 ? 0 : (i - 1) / 64) + 1; w-- > 0;) { + uint64_t word = words[w]; + if (w == (i - 1) / 64 && i % 64 != 0) { + word &= ~uint64_t(0) >> (64 - i % 64); + } + if (word) { + return uint32_t(w * 64 + highest_bit(word)); + } + } + assert(false && "an occupied cell remains"); + return 0; + } + + static uint32_t lowest_bit(uint64_t word) { + uint32_t b = 0; + while (!(word & 1)) { + word >>= 1; + ++b; + } + return b; + } + + static uint32_t highest_bit(uint64_t word) { + uint32_t b = 63; + while (!(word >> b)) { + --b; + } + return b; + } +}; + +// One position of one sequence, and how many of its cells hold it. +struct llama_kv_pos_count { + llama_pos pos; + int32_t n; +}; + +// One sequence's positions, sorted, each with its count: exact on its O(1) paths, else stale until recomputed. +class llama_kv_seq_pos { +public: + // a cell of this sequence now holds position p + void inc(llama_pos p) { + if (stale) { + return; + } + if (runs.empty() || runs.back().pos < p) { + runs.push_back({ p, 1 }); + return; + } + if (runs.back().pos == p) { + ++runs.back().n; + return; + } + stale = true; + } + + // a cell of this sequence no longer holds position p + void dec(llama_pos p) { + if (stale) { + return; + } + assert(!runs.empty()); + if (runs.back().pos == p) { + if (--runs.back().n == 0) { + runs.pop_back(); + } + return; + } + stale = true; + } + + void clear() { + runs.clear(); + stale = false; + } + + bool is_stale() const { return stale; } + + // recompute from the positions its cells hold now, in any order: sorted, equal positions merged with their counts + void settle(std::vector & positions) { + std::sort(positions.begin(), positions.end()); + runs.clear(); + for (const llama_pos p : positions) { + if (!runs.empty() && runs.back().pos == p) { + ++runs.back().n; + } else { + runs.push_back({ p, 1 }); + } + } + stale = false; + } + + bool empty() const { + assert(!stale); + return runs.empty(); + } + + llama_pos min() const { + assert(!stale && !runs.empty() && runs.front().n > 0); + return runs.front().pos; + } + + llama_pos max() const { + assert(!stale && !runs.empty() && runs.back().n > 0); + return runs.back().pos; + } + + const std::vector & entries() const { + assert(!stale); + return runs; + } + + void swap(llama_kv_seq_pos & other) noexcept { + runs.swap(other.runs); + std::swap(stale, other.stale); + } + +private: + std::vector runs; + bool stale = false; +}; diff --git a/src/llama-kv-cells.h b/src/llama-kv-cells.h index 4279acfdfa29..72417979d9ad 100644 --- a/src/llama-kv-cells.h +++ b/src/llama-kv-cells.h @@ -2,12 +2,11 @@ #include "llama.h" #include "llama-cparams.h" +#include "llama-kv-cell-index.h" #include #include #include -#include -#include #include struct llama_kv_cell_ext { @@ -81,6 +80,7 @@ class llama_kv_cells { ext.resize(n); shift.resize(n); seq.resize(n); + used.resize(n); reset(); } @@ -99,13 +99,13 @@ class llama_kv_cells { // the index of the first cell that is used // return 0 if no cells are used uint32_t used_min() const { - return used.empty() ? 0 : *used.begin(); + return used.min(); } // the index of the last cell that is used + 1 // return 0 if no cells are used uint32_t used_max_p1() const { - return used.empty() ? 0 : *used.rbegin() + 1; + return used.max_p1(); } bool get_has_shift() const { @@ -351,13 +351,8 @@ class llama_kv_cells { assert(seq_id >= 0); assert(seq_id < LLAMA_MAX_SEQ); - if (seq_pos[seq_id].empty()) { - return -1; - } - - assert(seq_pos[seq_id].begin()->second > 0); - - return seq_pos[seq_id].begin()->first; + const llama_kv_seq_pos & index = settled(seq_id); + return index.empty() ? -1 : index.min(); } // the maximum position of sequence seq_id currently present in any of the cells @@ -366,13 +361,8 @@ class llama_kv_cells { assert(seq_id >= 0); assert(seq_id < LLAMA_MAX_SEQ); - if (seq_pos[seq_id].empty()) { - return -1; - } - - assert(seq_pos[seq_id].rbegin()->second > 0); - - return seq_pos[seq_id].rbegin()->first; + const llama_kv_seq_pos & index = settled(seq_id); + return index.empty() ? -1 : index.max(); } // note: call only if the cell is not empty @@ -474,8 +464,8 @@ class llama_kv_cells { private: bool has_shift = false; - // set of indices of used cells (i.e. pos[i] != -1, allowed to not have any seq_id) - std::set used; + // the occupied cells (i.e. pos[i] != -1, allowed to not have any seq_id): a bitmap with its count and extrema + llama_kv_used used; std::vector pos; @@ -504,29 +494,40 @@ class llama_kv_cells { // the bitset seq[i] tells us which sequences are currently occupying the i-th cell std::vector seq; - // the set seq_pos[s][p] tells us how many times the position p is currently present for sequence s - // if the position p is not present, seq_pos[s][p] is not set - // this way seq_pos[s].begin() and seq_pos[s].rbegin() give us the min/max positions currently in the cache + // seq_pos[s] holds each position p currently present for sequence s with how many cells hold it, sorted, so its + // first and last entries are the min/max positions currently in the cache // - // note that we cannot a use an std::set because in some cases a position can occur more than once for the same seq: + // note that a position needs a count, not just presence, because in some cases a position can occur more than once for the same seq: // - during performing a cache reuse via (rm + add) // - some vision models have input embeddings with repeating positions // - std::map seq_pos[LLAMA_MAX_SEQ]; + // Continuum fork: each sequence's positions as a native sorted array with counts (llama-kv-cell-index.h), exact on + // its O(1) paths and recomputed from the cells at the next query after any other change (`settled`). + mutable llama_kv_seq_pos seq_pos[LLAMA_MAX_SEQ]; + + // sequence seq_id's index, recomputed from the cells first if a change left it stale + const llama_kv_seq_pos & settled(llama_seq_id seq_id) const { + llama_kv_seq_pos & index = seq_pos[seq_id]; + if (index.is_stale()) { + std::vector positions; + for (uint32_t i = used.min(); i < used.max_p1(); ++i) { + if (seq[i].test(seq_id)) { + positions.push_back(pos[i]); + } + } + index.settle(positions); + } + return index; + } // helper functions for updating `seq_pos`, once cell at a time: void seq_pos_dec(llama_seq_id s, llama_pos p) { - auto it = seq_pos[s].find(p); - assert(it != seq_pos[s].end()); - - if (--it->second == 0) { - seq_pos[s].erase(it); - } + seq_pos[s].dec(p); } void seq_pos_inc(llama_seq_id s, llama_pos p) { - seq_pos[s][p]++; + seq_pos[s].inc(p); } // remove cell i diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 4896b5e40653..885c2936adb2 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -189,6 +189,9 @@ endif () llama_build(test-recurrent-state-rollback.cpp) llama_build_and_test(test-server-view-end.cpp) +# llama_kv_cells' derived indices held natively answer exactly as the node containers they replace (CONTINUUM-ENGINE 4.14) +llama_build_and_test(test-kv-cell-index.cpp) + # 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-kv-cell-index.cpp b/tests/test-kv-cell-index.cpp new file mode 100644 index 000000000000..688f5772e9d5 --- /dev/null +++ b/tests/test-kv-cell-index.cpp @@ -0,0 +1,195 @@ +// Continuum fork (CONTINUUM-ENGINE 4.14, the flash tier): llama_kv_cells' derived indices held natively +// (llama-kv-cell-index.h) answer exactly as the std::set / std::map indices they replace. +// +// what this catches: an occupied-cell count or extremum, or a sequence's min/max position, that differs from what the +// cells hold after any mix of the operations the KV cache performs: appends, removals inside and at the ends, shared +// sequences (seq_add / seq_keep), shifts that drop cells below zero, and divisions that merge positions (pos_div is not +// injective). A reference model with the replaced node containers is checked after every step, and also times the same +// workloads, the old-versus-new read. + +#include "llama.h" + +#include "../src/llama-kv-cells.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +// The indices as they were: the oracle and the old-side baseline. +struct reference { + std::vector pos; + std::vector> seqs; + std::set used; + std::map seq_pos[LLAMA_MAX_SEQ]; + + explicit reference(uint32_t n) : pos(n, -1), seqs(n) {} + + void dec(llama_seq_id s, llama_pos p) { + auto it = seq_pos[s].find(p); + if (--it->second == 0) { + seq_pos[s].erase(it); + } + } + void pos_set(uint32_t i, llama_pos p) { pos[i] = p; used.insert(i); } + void seq_add(uint32_t i, llama_seq_id s) { seqs[i].insert(s); seq_pos[s][pos[i]]++; } + void rm(uint32_t i) { + for (auto s : seqs[i]) { dec(s, pos[i]); } + seqs[i].clear(); pos[i] = -1; used.erase(i); + } + void seq_rm(uint32_t i, llama_seq_id s) { + seqs[i].erase(s); dec(s, pos[i]); + if (seqs[i].empty()) { pos[i] = -1; used.erase(i); } + } + void seq_keep(uint32_t i, llama_seq_id s) { + if (seqs[i].count(s)) { + for (auto o : seqs[i]) { if (o != s) { dec(o, pos[i]); } } + seqs[i] = { s }; + } else if (!seqs[i].empty()) { + rm(i); + } + } + void pos_add(uint32_t i, llama_pos d) { + for (auto s : seqs[i]) { dec(s, pos[i]); } + pos[i] += d; + if (pos[i] < 0) { seqs[i].clear(); pos[i] = -1; used.erase(i); return; } + for (auto s : seqs[i]) { seq_pos[s][pos[i]]++; } + } + void pos_div(uint32_t i, int d) { + for (auto s : seqs[i]) { dec(s, pos[i]); } + pos[i] /= d; + for (auto s : seqs[i]) { seq_pos[s][pos[i]]++; } + } + llama_pos min(llama_seq_id s) const { return seq_pos[s].empty() ? -1 : seq_pos[s].begin()->first; } + llama_pos max(llama_seq_id s) const { return seq_pos[s].empty() ? -1 : seq_pos[s].rbegin()->first; } +}; + +int failures = 0; + +void expect(bool ok, const char * what, int step) { + if (!ok) { + fprintf(stderr, "FAIL at step %d: %s\n", step, what); + ++failures; + } +} + +void compare(const llama_kv_cells & cells, const reference & ref, int n_seq, int step) { + expect(cells.get_used() == ref.used.size(), "used count", step); + expect(cells.used_min() == (ref.used.empty() ? 0 : *ref.used.begin()), "first used cell", step); + expect(cells.used_max_p1() == (ref.used.empty() ? 0 : *ref.used.rbegin() + 1), "last used cell", step); + for (llama_seq_id s = 0; s < n_seq; ++s) { + expect(cells.seq_pos_min(s) == ref.min(s), "sequence min position", step); + expect(cells.seq_pos_max(s) == ref.max(s), "sequence max position", step); + } +} + +// Every operation the cache performs, at random, on both, compared after each step. +void equivalence(uint32_t n_cells, int n_seq, int steps, uint32_t seed) { + std::mt19937 rng(seed); + llama_kv_cells cells; + cells.resize(n_cells); + reference ref(n_cells); + llama_pos next_pos[LLAMA_MAX_SEQ] = {}; + auto pick = [&](uint32_t n) { return uint32_t(rng() % n); }; + + for (int step = 0; step < steps; ++step) { + const uint32_t i = pick(n_cells); + const llama_seq_id s = llama_seq_id(pick(uint32_t(n_seq))); + switch (pick(9)) { + case 0: case 1: case 2: { // append her next position (the common case), sometimes a repeat + if (!cells.is_empty(i)) { break; } + const llama_pos p = pick(8) == 0 ? std::max(0, next_pos[s] - 1) : next_pos[s]++; + cells.pos_set(i, p); ref.pos_set(i, p); + cells.seq_add(i, s); ref.seq_add(i, s); + break; + } + case 3: // a shared prefix: another sequence joins an occupied cell + if (cells.is_empty(i) || cells.seq_has(i, s)) { break; } + cells.seq_add(i, s); ref.seq_add(i, s); + break; + case 4: // remove a cell wherever it is + if (cells.is_empty(i)) { break; } + cells.rm(i); ref.rm(i); + break; + case 5: // one sequence leaves a cell + if (cells.is_empty(i) || !cells.seq_has(i, s)) { break; } + cells.seq_rm(i, s); ref.seq_rm(i, s); + break; + case 6: // keep only one sequence + cells.seq_keep(i, s); ref.seq_keep(i, s); + break; + case 7: { // shift, sometimes below zero (the cell is freed) + if (cells.is_empty(i)) { break; } + const llama_pos d = llama_pos(pick(64)) - 40; + cells.pos_add(i, d); ref.pos_add(i, d); + break; + } + case 8: { // divide: distinct positions can merge + if (cells.is_empty(i)) { break; } + const int d = 2 + int(pick(3)); + cells.pos_div(i, d); ref.pos_div(i, d); + break; + } + } + compare(cells, ref, n_seq, step); + if (failures) { return; } + } +} + +// The same workload on both, timed: her context appended token by token, its front half dropped (a context shift's +// discard), the rest shifted down, and her extrema read after each phase. +template +double timed(T & t, uint32_t n, Append append, Remove remove, Shift shift, Read read) { + const auto t0 = std::chrono::steady_clock::now(); + for (uint32_t i = 0; i < n; ++i) { append(t, i); } + read(t); + for (uint32_t i = 0; i < n / 2; ++i) { remove(t, i); } + read(t); + for (uint32_t i = n / 2; i < n; ++i) { shift(t, i); } + read(t); + return std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); +} + +void cost(uint32_t n) { + llama_kv_cells cells; + cells.resize(n); + reference ref(n); + volatile llama_pos sink = 0; + const llama_pos d = -llama_pos(n / 2); + const double now = timed(cells, n, + [](llama_kv_cells & c, uint32_t i) { c.pos_set(i, llama_pos(i)); c.seq_add(i, 0); }, + [](llama_kv_cells & c, uint32_t i) { c.rm(i); }, + [d](llama_kv_cells & c, uint32_t i) { c.pos_add(i, d); }, + [&sink](llama_kv_cells & c) { sink = c.seq_pos_min(0) + c.seq_pos_max(0) + llama_pos(c.get_used()); }); + const double before = timed(ref, n, + [](reference & r, uint32_t i) { r.pos_set(i, llama_pos(i)); r.seq_add(i, 0); }, + [](reference & r, uint32_t i) { r.rm(i); }, + [d](reference & r, uint32_t i) { r.pos_add(i, d); }, + [&sink](reference & r) { sink = r.min(0) + r.max(0) + llama_pos(r.used.size()); }); + printf("RECEIPT kv-cell-index n=%u: node containers %.3f ms, native %.3f ms\n", n, before, now); + (void) sink; +} + +} // namespace + +int main(int argc, char ** argv) { + for (uint32_t seed = 1; seed <= 8 && !failures; ++seed) { + equivalence(256, 4, 20000, seed); + } + if (failures) { + fprintf(stderr, "kv-cell-index: %d mismatches against the node-container indices\n", failures); + return 1; + } + printf("kv-cell-index: native indices match the node-container indices over 8 x 20000 random cache operations\n"); + if (argc > 1) { // --cost: the old-versus-new read at real lengths + for (uint32_t n : { 4096u, 32768u, 100000u }) { + cost(n); + } + } + return 0; +} From bd97171f865babf8feaeb48b4225fcb176463260 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 08:39:15 -0600 Subject: [PATCH 10/28] kv-cells: indices are settled before a persona leaves; a bind and every query after it recompute nothing Codex's review of 2d54d4869: a recomputation caused by a genuine change (a division that merges positions, a shift, an inner removal) is new work, but it is never deferred across a freeze. persona_check_save (the fallible reserve phase, where allocation may fail and leave her whole) now calls llama_kv_cells::settle_all, so her blocks leave a stream with every index valid and the commit, the bind and any later query perform no scan and no sort. A failed settle leaves the index stale (its flag is cleared last), never half-written. test-kv-cell-index: freeze_then_bind divides positions so they merge and removes one inside the range, settles as the save does, binds her object into a fresh stream by swap, and checks the bound object answers every query as the node-container reference does with zero recomputations (settles() counts them). The --cost read already charges the deferred recomputation: its extrema are read after each phase. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- src/llama-kv-cache.cpp | 2 ++ src/llama-kv-cells.h | 18 ++++++++++++++++++ tests/test-kv-cell-index.cpp | 29 +++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+) diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index f30c0bdfa52d..3c6c377767d5 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -1281,6 +1281,8 @@ llama_persona_move llama_kv_cache::persona_check_save(llama_seq_id seq_id, llama if (!cells_prepared(out.kv.cells, get_size()) || out.kv.k.size() != layers.size() || out.kv.v.size() != layers.size()) { return llama_persona_move::cells_not_prepared; } + // her indices leave valid: any recomputation a change left owed is paid here, never at her bind or later query + v_cells[seq_to_stream[seq_id]].settle_all(); // reserve: every byte the commit copies, so the commit never allocates const uint32_t n_rows = v_cells[seq_to_stream[seq_id]].used_max_p1(); for (size_t i = 0; i < layers.size(); ++i) { diff --git a/src/llama-kv-cells.h b/src/llama-kv-cells.h index 72417979d9ad..314bdcffa3ba 100644 --- a/src/llama-kv-cells.h +++ b/src/llama-kv-cells.h @@ -92,6 +92,20 @@ class llama_kv_cells { return pos[i] == -1; } + // Continuum fork (CONTINUUM-ENGINE 4.14): recompute every stale sequence index now. A persona's blocks leave a + // stream only with valid indices (her save's reserve phase calls this, where allocation may fail), so a bind or + // any query after it never scans or sorts: a recomputation is never deferred across a freeze. + void settle_all() const { + for (llama_seq_id s = 0; s < LLAMA_MAX_SEQ; ++s) { + settled(s); + } + } + + // how many index recomputations this object has made + uint64_t settles() const { + return n_settles; + } + uint32_t get_used() const { return used.size(); } @@ -505,10 +519,14 @@ class llama_kv_cells { // its O(1) paths and recomputed from the cells at the next query after any other change (`settled`). mutable llama_kv_seq_pos seq_pos[LLAMA_MAX_SEQ]; + // how many times an index was recomputed from the cells (the freeze and restore fixtures count them) + mutable uint64_t n_settles = 0; + // sequence seq_id's index, recomputed from the cells first if a change left it stale const llama_kv_seq_pos & settled(llama_seq_id seq_id) const { llama_kv_seq_pos & index = seq_pos[seq_id]; if (index.is_stale()) { + ++n_settles; std::vector positions; for (uint32_t i = used.min(); i < used.max_p1(); ++i) { if (seq[i].test(seq_id)) { diff --git a/tests/test-kv-cell-index.cpp b/tests/test-kv-cell-index.cpp index 688f5772e9d5..063e02fb67a6 100644 --- a/tests/test-kv-cell-index.cpp +++ b/tests/test-kv-cell-index.cpp @@ -141,6 +141,34 @@ void equivalence(uint32_t n_cells, int n_seq, int steps, uint32_t seed) { } } +// what this catches (Codex's review of 2d54d4869): an index left stale by a genuine change (a division that merges +// positions, a removal inside the range) carried across her freeze and recomputed only at her next query after the +// bind. Her save settles every index (llama_kv_cache::persona_check_save calls settle_all); the object bound to a stream +// then answers every query with no scan and no sort, and answers as the node-container indices do. +void freeze_then_bind() { + const uint32_t n = 64; + llama_kv_cells cells; + cells.resize(n); + reference ref(n); + for (uint32_t i = 0; i < 32; ++i) { + cells.pos_set(i, llama_pos(i)); ref.pos_set(i, llama_pos(i)); + cells.seq_add(i, llama_seq_id(i % 2)); ref.seq_add(i, llama_seq_id(i % 2)); + } + for (uint32_t i = 0; i < 32; ++i) { + cells.pos_div(i, 3); ref.pos_div(i, 3); + } + cells.rm(5); ref.rm(5); + const uint64_t before = cells.settles(); + cells.settle_all(); // her save's reserve phase + expect(cells.settles() > before, "the change was paid for at the freeze", -1); + + llama_kv_cells bound; + bound.resize(n); + bound.swap(cells); // her blocks bound to a stream + compare(bound, ref, 2, -1); + expect(bound.settles() == 0, "a query after the bind recomputed nothing", -1); +} + // The same workload on both, timed: her context appended token by token, its front half dropped (a context shift's // discard), the rest shifted down, and her extrema read after each phase. template @@ -181,6 +209,7 @@ int main(int argc, char ** argv) { for (uint32_t seed = 1; seed <= 8 && !failures; ++seed) { equivalence(256, 4, 20000, seed); } + freeze_then_bind(); if (failures) { fprintf(stderr, "kv-cell-index: %d mismatches against the node-container indices\n", failures); return 1; From 347a13ab2bae1491911df8f48eb3f61344d9f42d Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 09:48:10 -0600 Subject: [PATCH 11/28] test-kv-cell-index: main names no unused argv (GCC -Werror=unused-parameter on the Ubuntu build) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tests/test-kv-cell-index.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test-kv-cell-index.cpp b/tests/test-kv-cell-index.cpp index 063e02fb67a6..c70579e9086d 100644 --- a/tests/test-kv-cell-index.cpp +++ b/tests/test-kv-cell-index.cpp @@ -205,7 +205,7 @@ void cost(uint32_t n) { } // namespace -int main(int argc, char ** argv) { +int main(int argc, char ** /* argv: only the flag count is read */) { for (uint32_t seed = 1; seed <= 8 && !failures; ++seed) { equivalence(256, 4, 20000, seed); } From 8fe7f7d921e43bd49857d3084f22093d4c8c7cdb Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 10:33:38 -0600 Subject: [PATCH 12/28] test-kv-cell-index: the cost baseline is the exact previous llama_kv_cells, with allocation counts Codex's review of 347a13ab2: the timing reference kept each cell's sequences in a std::set, while the previous llama_kv_cells used bitset membership, so the old side was charged allocations it never made. The oracle stays as the equivalence check; the cost read now runs the same workload on kv-cells-previous.h (the class at accc9e3b1, verbatim but for its name) and on the native one, and counts this binary's allocations during each. Measured on the M5 (clang++ -O2 -Wall -Wextra -Werror, nice 19, three runs, ~16:35Z): n=4096 previous ~1.00 ms / 10240 allocations vs native ~0.54 ms / 37; n=32768 ~8.8 ms / 81920 vs ~4.2 ms / 46; n=100000 ~28.1 ms / 250000 vs ~12.85 ms / 52. The 4k slowdown reported earlier was an artifact of the simplified baseline (it skipped the previous class's per-cell work across every sequence), not of the native indices. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tests/kv-cells-previous.h | 537 +++++++++++++++++++++++++++++++++++ tests/test-kv-cell-index.cpp | 89 ++++-- 2 files changed, 599 insertions(+), 27 deletions(-) create mode 100644 tests/kv-cells-previous.h diff --git a/tests/kv-cells-previous.h b/tests/kv-cells-previous.h new file mode 100644 index 000000000000..d17e4b2fce14 --- /dev/null +++ b/tests/kv-cells-previous.h @@ -0,0 +1,537 @@ +#pragma once + +// The llama_kv_cells implementation before the native indices (fork accc9e3b1, src/llama-kv-cells.h), verbatim but for +// the class name: the old-versus-new timing baseline for test-kv-cell-index (Codex review of 347a13ab2), so the old side +// is charged exactly what the previous code allocated (bitset membership, std::set used, std::map seq_pos). + +#include "llama.h" +#include "../src/llama-kv-cells.h" // llama_kv_cell_ext, unchanged + +#include +#include +#include +#include +#include +#include + +// meta information about KV cells that can be part of multiple sequences at the same time +// TODO: add unit tests +class llama_kv_cells_previous { +public: + // Continuum fork (CONTINUUM-ENGINE 4.14): exchange two cells objects in place, member by member, with each + // container's own swap: never allocates on any standard library (a std::swap of the whole object moves through a + // temporary, and MSVC's node containers allocate a sentinel when move-constructed). A persona's metadata moves + // between her blocks and a stream with this. + void swap(llama_kv_cells_previous & other) noexcept { + std::swap(has_shift, other.has_shift); + used.swap(other.used); + pos.swap(other.pos); + ext.swap(other.ext); + shift.swap(other.shift); + seq.swap(other.seq); + for (int s = 0; s < LLAMA_MAX_SEQ; ++s) { + seq_pos[s].swap(other.seq_pos[s]); + } + } + + void reset() { + for (uint32_t i = 0; i < pos.size(); ++i) { + pos[i] = -1; + ext[i].reset(); + shift[i] = 0; + seq[i].reset(); + } + + has_shift = false; + + used.clear(); + + for (uint32_t s = 0; s < LLAMA_MAX_SEQ; ++s) { + seq_pos[s].clear(); + } + } + + void reset_shift() { + has_shift = false; + + for (uint32_t i = 0; i < shift.size(); ++i) { + shift[i] = 0; + } + } + + uint32_t size() const { + return pos.size(); + } + + void resize(uint32_t n) { + pos.resize(n); + ext.resize(n); + shift.resize(n); + seq.resize(n); + + reset(); + } + + bool is_empty(uint32_t i) const { + assert(i < pos.size()); + assert((pos[i] < 0 && pos[i] == -1) || pos[i] >= 0); + + return pos[i] == -1; + } + + uint32_t get_used() const { + return used.size(); + } + + // the index of the first cell that is used + // return 0 if no cells are used + uint32_t used_min() const { + return used.empty() ? 0 : *used.begin(); + } + + // the index of the last cell that is used + 1 + // return 0 if no cells are used + uint32_t used_max_p1() const { + return used.empty() ? 0 : *used.rbegin() + 1; + } + + bool get_has_shift() const { + return has_shift; + } + + // move cell isrc to idst (used during defrag) + //void mv(uint32_t isrc, uint32_t idst) { + // assert(isrc < pos.size()); + // assert(idst < pos.size()); + + // assert(pos[idst] == -1); + // assert(pos[isrc] != -1); + + // pos [idst] = pos [isrc]; + // shift[idst] = shift[isrc]; + // seq [idst] = seq [isrc]; + + // pos [isrc] = -1; + // shift[isrc] = 0; + // seq [isrc].reset(); + + // used.erase (isrc); + // used.insert(idst); + //} + + // copy the state of cells [i, i + n) (used for save/restore the state of the cells) + llama_kv_cells_previous cp(uint32_t i, uint32_t n) const { + assert(i + n <= pos.size()); + + llama_kv_cells_previous res; + + res.resize(n); + + for (uint32_t j = 0; j < n; ++j) { + const auto idx = i + j; + + res.pos[j] = pos[idx]; + res.ext[j] = ext[idx]; + res.seq[j] = seq[idx]; + + assert(shift[idx] == 0); + } + + return res; + } + + // copy the state of cells [idxs[0], idxs[1], ..., idxs[idxs.size() - 1]) + llama_kv_cells_previous cp(const std::vector & idxs) const { + llama_kv_cells_previous res; + + res.resize(idxs.size()); + + for (uint32_t j = 0; j < idxs.size(); ++j) { + const auto idx = idxs[j]; + + res.pos[j] = pos[idx]; + res.ext[j] = ext[idx]; + res.seq[j] = seq[idx]; + + assert(shift[idx] == 0); + } + + return res; + } + + // set the state of cells [i, i + other.pos.size()) (used for save/restore the state of the cells) + void set(uint32_t i, const llama_kv_cells_previous & other) { + assert(i + other.pos.size() <= pos.size()); + + for (uint32_t j = 0; j < other.pos.size(); ++j) { + const auto idx = i + j; + + if (pos[idx] == -1 && other.pos[j] != -1) { + used.insert(i + j); + } + + if (pos[idx] != -1 && other.pos[j] == -1) { + used.erase(i + j); + } + + if (pos[idx] != -1) { + seq_pos_rm(i + j); + } + + pos[idx] = other.pos[j]; + ext[idx] = other.ext[j]; + seq[idx] = other.seq[j]; + + if (pos[idx] != -1) { + seq_pos_add(i + j); + } + + assert(shift[idx] == 0); + } + } + + // set the state of cells [idxs[0], idxs[1], ..., idxs[idxs.size() - 1]) + void set(const std::vector & idxs, const llama_kv_cells_previous & other) { + assert(idxs.size() == other.pos.size()); + + for (uint32_t j = 0; j < other.pos.size(); ++j) { + const auto idx = idxs[j]; + + if (pos[idx] == -1 && other.pos[j] != -1) { + used.insert(idx); + } + + if (pos[idx] != -1 && other.pos[j] == -1) { + used.erase(idx); + } + + if (pos[idx] != -1) { + seq_pos_rm(idx); + } + + pos[idx] = other.pos[j]; + ext[idx] = other.ext[j]; + seq[idx] = other.seq[j]; + + if (pos[idx] != -1) { + seq_pos_add(idx); + } + + assert(shift[idx] == 0); + } + } + + // clear a non-empty cell + void rm(uint32_t i) { + assert(i < pos.size()); + assert(pos[i] != -1); + + seq_pos_rm(i); + seq[i].reset(); + + pos[i] = -1; + ext[i].reset(); + shift[i] = 0; + + used.erase(i); + } + + // note: call only if the cell has seq_id + // return true if the cell becomes empty + bool seq_rm(uint32_t i, llama_seq_id seq_id) { + assert(i < pos.size()); + assert(seq[i].test(seq_id)); + assert(pos[i] != -1); + assert(seq_id >= 0); + + seq[i].reset(seq_id); + seq_pos_dec(seq_id, pos[i]); + + if (seq[i].none()) { + pos[i] = -1; + ext[i].reset(); + shift[i] = 0; + + used.erase(i); + + return true; + } + + return false; + } + + // return true if the cell becomes empty (i.e. it did not contain seq_id before the call) + bool seq_keep(uint32_t i, llama_seq_id seq_id) { + assert(i < pos.size()); + + if (seq[i].test(seq_id)) { + seq_pos_rm(i); + seq[i].reset(); + + seq[i].set(seq_id); + seq_pos_inc(seq_id, pos[i]); + + return false; + } + + if (seq[i].any()) { + seq_pos_rm(i); + seq[i].reset(); + + pos[i] = -1; + ext[i].reset(); + shift[i] = 0; + + used.erase(i); + + return true; + } + + assert(pos[i] == -1); + + return false; + } + + // number of different sequences in the cell + int seq_count(uint32_t i) const { + assert(i < pos.size()); + assert(pos[i] != -1); + + return seq[i].count(); + } + + // check if the cell contains seq_id + bool seq_has(uint32_t i, llama_seq_id seq_id) const { + assert(i < pos.size()); + assert(seq_id >= 0); + + return seq[i].test(seq_id); + } + + // note: call only if the cell is not empty and the seq_id is not in the cell + void seq_add(uint32_t i, llama_seq_id seq_id) { + assert(i < pos.size()); + assert(pos[i] != -1); + assert(!seq[i].test(seq_id)); + + seq[i].set(seq_id); + seq_pos_inc(seq_id, pos[i]); + } + + // return the sequence id of this cell + // note: call only for cells with exactly one sequence + llama_seq_id seq_get(uint32_t i) const { + assert(seq[i].count() == 1); + + for (int s = 0; s < LLAMA_MAX_SEQ; ++s) { + if (seq[i].test(s)) { + return s; + } + } + + return -1; + } + + // the minimum position of sequence seq_id currently present in any of the cells + // return -1 if the sequence is not present + llama_pos seq_pos_min(llama_seq_id seq_id) const { + assert(seq_id >= 0); + assert(seq_id < LLAMA_MAX_SEQ); + + if (seq_pos[seq_id].empty()) { + return -1; + } + + assert(seq_pos[seq_id].begin()->second > 0); + + return seq_pos[seq_id].begin()->first; + } + + // the maximum position of sequence seq_id currently present in any of the cells + // return -1 if the sequence is not present + llama_pos seq_pos_max(llama_seq_id seq_id) const { + assert(seq_id >= 0); + assert(seq_id < LLAMA_MAX_SEQ); + + if (seq_pos[seq_id].empty()) { + return -1; + } + + assert(seq_pos[seq_id].rbegin()->second > 0); + + return seq_pos[seq_id].rbegin()->first; + } + + // note: call only if the cell is not empty + llama_pos pos_get(uint32_t i) const { + assert(i < pos.size()); + assert(pos[i] != -1); + + return pos[i]; + } + + const llama_kv_cell_ext & ext_get(uint32_t i) const { + assert(i < pos.size()); + assert(pos[i] != -1); + + return ext[i]; + } + + // note: call only if the cell is not empty + llama_pos get_shift(uint32_t i) const { + assert(i < pos.size()); + assert(pos[i] != -1); + + return shift[i]; + } + + // check if a cell is not empty and its position is within [p0, p1) + bool pos_in(uint32_t i, llama_pos p0, llama_pos p1) const { + assert(i < pos.size()); + + return pos[i] >= p0 && pos[i] < p1; + } + + // set the position of an empty cell + // does not modify "has_shift" + // note: call only if the cell is empty + void pos_set(uint32_t i, llama_pos p) { + assert(i < pos.size()); + assert(pos[i] == -1); + assert(seq[i].none()); + + pos[i] = p; + + used.insert(i); + } + + void ext_set(uint32_t i, llama_kv_cell_ext p) { + assert(i < ext.size()); + ext[i] = p; + } + + // pos[i] = pos[i] + d + // sets "has_shift" to true + // note: call only if the cell is not empty + bool pos_add(uint32_t i, llama_pos d) { + assert(i < pos.size()); + assert(pos[i] != -1); + + seq_pos_rm(i); + + pos[i] += d; + shift[i] += d; + + has_shift = true; + + if (pos[i] < 0) { + seq[i].reset(); + pos[i] = -1; + shift[i] = 0; + + used.erase(i); + + return true; + } + + seq_pos_add(i); + + return false; + } + + // pos[i] = pos[i] / d + // sets "has_shift" to true + // note: call only if the cell is not empty + void pos_div(uint32_t i, int d) { + assert(i < pos.size()); + assert(pos[i] != -1); + + const llama_pos p_old = pos[i]; + + seq_pos_rm(i); + + pos[i] /= d; + shift[i] += p_old - pos[i]; + + seq_pos_add(i); + + has_shift = true; + } + +private: + bool has_shift = false; + + // set of indices of used cells (i.e. pos[i] != -1, allowed to not have any seq_id) + std::set used; + + std::vector pos; + + // stores extra info per cell + std::vector ext; + + // this array accumulates any applied shifts to the pos array since the last reset_shift() call + // this is used to queue multiple updates to the pos array, which in the end can be applied in one go: + // + // cells.pos_add(x, shift_x); + // cells.pos_div(y, shift_y); + // ... + // + // if (cells.has_shift()) { + // for (int i = 0; i < n; ++i) { + // auto shift_i = cells.get_shift(i); + // ... + // } + // cells.reset_shift(); + // } + // + std::vector shift; + + using seq_set_t = std::bitset; + + // the bitset seq[i] tells us which sequences are currently occupying the i-th cell + std::vector seq; + + // the set seq_pos[s][p] tells us how many times the position p is currently present for sequence s + // if the position p is not present, seq_pos[s][p] is not set + // this way seq_pos[s].begin() and seq_pos[s].rbegin() give us the min/max positions currently in the cache + // + // note that we cannot a use an std::set because in some cases a position can occur more than once for the same seq: + // - during performing a cache reuse via (rm + add) + // - some vision models have input embeddings with repeating positions + // + std::map seq_pos[LLAMA_MAX_SEQ]; + + // helper functions for updating `seq_pos`, once cell at a time: + + void seq_pos_dec(llama_seq_id s, llama_pos p) { + auto it = seq_pos[s].find(p); + assert(it != seq_pos[s].end()); + + if (--it->second == 0) { + seq_pos[s].erase(it); + } + } + + void seq_pos_inc(llama_seq_id s, llama_pos p) { + seq_pos[s][p]++; + } + + // remove cell i + void seq_pos_rm(uint32_t i) { + for (int s = 0; s < LLAMA_MAX_SEQ; ++s) { + if (seq[i].test(s)) { + seq_pos_dec(s, pos[i]); + } + } + } + + // add cell i + void seq_pos_add(uint32_t i) { + for (int s = 0; s < LLAMA_MAX_SEQ; ++s) { + if (seq[i].test(s)) { + seq_pos_inc(s, pos[i]); + } + } + } +}; + diff --git a/tests/test-kv-cell-index.cpp b/tests/test-kv-cell-index.cpp index c70579e9086d..092c6861ad4e 100644 --- a/tests/test-kv-cell-index.cpp +++ b/tests/test-kv-cell-index.cpp @@ -10,11 +10,14 @@ #include "llama.h" #include "../src/llama-kv-cells.h" +#include "kv-cells-previous.h" +#include #include #include #include #include +#include #include #include #include @@ -169,42 +172,74 @@ void freeze_then_bind() { expect(bound.settles() == 0, "a query after the bind recomputed nothing", -1); } -// The same workload on both, timed: her context appended token by token, its front half dropped (a context shift's -// discard), the rest shifted down, and her extrema read after each phase. -template -double timed(T & t, uint32_t n, Append append, Remove remove, Shift shift, Read read) { - const auto t0 = std::chrono::steady_clock::now(); - for (uint32_t i = 0; i < n; ++i) { append(t, i); } - read(t); - for (uint32_t i = 0; i < n / 2; ++i) { remove(t, i); } - read(t); - for (uint32_t i = n / 2; i < n; ++i) { shift(t, i); } - read(t); - return std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); -} +// The same workload on the previous implementation (kv-cells-previous.h, verbatim) and the native one, timed and with +// the allocations it makes counted: her context appended token by token, its front half dropped (a context shift's +// discard), the rest shifted down, and her extrema read after each phase (so a deferred recomputation is charged). +std::atomic counting{ false }; +std::atomic allocations{ 0 }; -void cost(uint32_t n) { - llama_kv_cells cells; +struct measured { + double ms; + uint64_t allocations; +}; + +template +measured workload(uint32_t n) { + Cells cells; cells.resize(n); - reference ref(n); volatile llama_pos sink = 0; const llama_pos d = -llama_pos(n / 2); - const double now = timed(cells, n, - [](llama_kv_cells & c, uint32_t i) { c.pos_set(i, llama_pos(i)); c.seq_add(i, 0); }, - [](llama_kv_cells & c, uint32_t i) { c.rm(i); }, - [d](llama_kv_cells & c, uint32_t i) { c.pos_add(i, d); }, - [&sink](llama_kv_cells & c) { sink = c.seq_pos_min(0) + c.seq_pos_max(0) + llama_pos(c.get_used()); }); - const double before = timed(ref, n, - [](reference & r, uint32_t i) { r.pos_set(i, llama_pos(i)); r.seq_add(i, 0); }, - [](reference & r, uint32_t i) { r.rm(i); }, - [d](reference & r, uint32_t i) { r.pos_add(i, d); }, - [&sink](reference & r) { sink = r.min(0) + r.max(0) + llama_pos(r.used.size()); }); - printf("RECEIPT kv-cell-index n=%u: node containers %.3f ms, native %.3f ms\n", n, before, now); + auto read = [&] { sink = cells.seq_pos_min(0) + cells.seq_pos_max(0) + llama_pos(cells.get_used()); }; + allocations = 0; + counting = true; + const auto t0 = std::chrono::steady_clock::now(); + for (uint32_t i = 0; i < n; ++i) { + cells.pos_set(i, llama_pos(i)); + cells.seq_add(i, 0); + } + read(); + for (uint32_t i = 0; i < n / 2; ++i) { + cells.rm(i); + } + read(); + for (uint32_t i = n / 2; i < n; ++i) { + cells.pos_add(i, d); + } + read(); + const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + counting = false; (void) sink; + return { ms, allocations.load() }; +} + +void cost(uint32_t n) { + const measured before = workload(n); + const measured now = workload(n); + printf("RECEIPT kv-cell-index n=%u: previous %.3f ms, %llu allocations | native %.3f ms, %llu allocations\n", n, + before.ms, (unsigned long long) before.allocations, now.ms, (unsigned long long) now.allocations); } } // namespace +// Counts this binary's allocations while a workload runs (counting is off otherwise). +void * operator new(std::size_t size) { + if (counting.load(std::memory_order_relaxed)) { + allocations.fetch_add(1, std::memory_order_relaxed); + } + if (void * p = std::malloc(size == 0 ? 1 : size)) { + return p; + } + throw std::bad_alloc(); +} + +void operator delete(void * p) noexcept { + std::free(p); +} + +void operator delete(void * p, std::size_t) noexcept { + std::free(p); +} + int main(int argc, char ** /* argv: only the flag count is read */) { for (uint32_t seed = 1; seed <= 8 && !failures; ++seed) { equivalence(256, 4, 20000, seed); From cab708e722ebd37f4560773ca60a795463b2cfe5 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 10:40:25 -0600 Subject: [PATCH 13/28] test-kv-cell-index: time with the allocation counter off; count allocations in a separate pass of the same workload Codex's review of 8fe7f7d92: the counter's atomic add per allocation charged the side that allocates more. M5, -O2, nice 19, three runs ~16:41Z, timing with counting off: n=4096 previous 0.93-0.96 ms vs native 0.52-0.53; n=32768 8.47-8.64 vs 4.15-4.17; n=100000 26.8-27.8 vs 12.7-12.9. Allocations (separate pass): 10240/81920/250000 vs 37/46/52. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tests/test-kv-cell-index.cpp | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/tests/test-kv-cell-index.cpp b/tests/test-kv-cell-index.cpp index 092c6861ad4e..8d4d0eeb7602 100644 --- a/tests/test-kv-cell-index.cpp +++ b/tests/test-kv-cell-index.cpp @@ -184,14 +184,14 @@ struct measured { }; template -measured workload(uint32_t n) { +measured workload(uint32_t n, bool count) { Cells cells; cells.resize(n); volatile llama_pos sink = 0; const llama_pos d = -llama_pos(n / 2); auto read = [&] { sink = cells.seq_pos_min(0) + cells.seq_pos_max(0) + llama_pos(cells.get_used()); }; allocations = 0; - counting = true; + counting = count; const auto t0 = std::chrono::steady_clock::now(); for (uint32_t i = 0; i < n; ++i) { cells.pos_set(i, llama_pos(i)); @@ -213,10 +213,14 @@ measured workload(uint32_t n) { } void cost(uint32_t n) { - const measured before = workload(n); - const measured now = workload(n); + // Timed with the counter off (its atomic add per allocation would charge the side that allocates more), and the + // allocations counted in a separate pass of the identical workload. + const double before_ms = workload(n, false).ms; + const double now_ms = workload(n, false).ms; + const uint64_t before_allocs = workload(n, true).allocations; + const uint64_t now_allocs = workload(n, true).allocations; printf("RECEIPT kv-cell-index n=%u: previous %.3f ms, %llu allocations | native %.3f ms, %llu allocations\n", n, - before.ms, (unsigned long long) before.allocations, now.ms, (unsigned long long) now.allocations); + before_ms, (unsigned long long) before_allocs, now_ms, (unsigned long long) now_allocs); } } // namespace From 6b31e003046656b2c57e752224601fe92ab181d4 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 11:32:06 -0600 Subject: [PATCH 14/28] kv cells: a query never writes an index; each cache operation settles what it changed as it returns llama-server answers /slots and /metrics on its worker thread while a decode runs (yield_to_queue), and /slots reads kv_pos_min/kv_pos_max. The lazy index recomputed a stale sequence inside that const query, so a query wrote the index the decode thread was changing. Now: - the owner settles: llama_kv_cache's cell-changing operations (seq_rm, seq_cp, seq_keep, seq_add, seq_div, prepare, apply_ubatch, state_read) settle every stale index as they return, on their own thread; a bitset of stale sequences means settling visits only those; - a query is pure: a stale index (a missed settle) is answered exactly from the cells without writing it, and counted (stale_queries, an atomic: the only thing a query writes), so a miss is loud in tests, never wrong; - persona_check_save no longer settles (it is const, and every change was settled by its operation). test-kv-cell-index: every random operation is followed by the cache's settle, after which no query is answered from the cells; queries_never_write checks a stale query is exact, counted, and leaves the index stale. Cost unchanged (M5, --cost): 4k 0.91 -> 0.53 ms, 32k 8.5 -> 4.2 ms, 100k 27.0 -> 13.0 ms. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- src/llama-kv-cache.cpp | 21 ++++++++- src/llama-kv-cell-index.h | 20 ++++++++ src/llama-kv-cells.h | 90 +++++++++++++++++++++++++++--------- tests/test-kv-cell-index.cpp | 42 +++++++++++++++-- 4 files changed, 145 insertions(+), 28 deletions(-) diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index 3c6c377767d5..720ef3365a3a 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -13,6 +13,17 @@ #include #include +// Continuum fork (CONTINUUM-ENGINE 4.14): settles every index a change left stale as the operation that made it returns, +// on the thread that made it, so a query (from any thread) never writes an index. +struct llama_kv_settle_on_return { + llama_kv_cells_vec & v_cells; + ~llama_kv_settle_on_return() { + for (auto & cells : v_cells) { + cells.settle_all(); + } + } +}; + static bool ggml_is_power_of_2(int n) { return (n & (n - 1)) == 0; } @@ -381,6 +392,7 @@ void llama_kv_cache::clear(bool data) { } bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) { + const llama_kv_settle_on_return settle{ v_cells }; // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] if (other) { return true; @@ -450,6 +462,7 @@ bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) { } void llama_kv_cache::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) { + const llama_kv_settle_on_return settle{ v_cells }; // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] if (other) { return; @@ -542,6 +555,7 @@ void llama_kv_cache::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, ll } void llama_kv_cache::seq_keep(llama_seq_id seq_id) { + const llama_kv_settle_on_return settle{ v_cells }; // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] if (other) { return; @@ -569,6 +583,7 @@ void llama_kv_cache::seq_keep(llama_seq_id seq_id) { } void llama_kv_cache::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos shift) { + const llama_kv_settle_on_return settle{ v_cells }; // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] if (other) { return; @@ -619,6 +634,7 @@ void llama_kv_cache::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, ll } void llama_kv_cache::seq_div(llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) { + const llama_kv_settle_on_return settle{ v_cells }; // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] if (other) { return; @@ -754,6 +770,7 @@ llama_memory_context_ptr llama_kv_cache::init_update(llama_context * lctx, bool } llama_kv_cache::slot_info_vec_t llama_kv_cache::prepare(const std::vector & ubatches) { + const llama_kv_settle_on_return settle{ v_cells }; llama_kv_cache::slot_info_vec_t res; struct state_t { @@ -1100,6 +1117,7 @@ llama_kv_cache::slot_info llama_kv_cache::find_slot(const llama_ubatch & ubatch, } void llama_kv_cache::apply_ubatch(const slot_info & sinfo, const llama_ubatch & ubatch) { + const llama_kv_settle_on_return settle{ v_cells }; // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] if (other) { return; @@ -1281,8 +1299,6 @@ llama_persona_move llama_kv_cache::persona_check_save(llama_seq_id seq_id, llama if (!cells_prepared(out.kv.cells, get_size()) || out.kv.k.size() != layers.size() || out.kv.v.size() != layers.size()) { return llama_persona_move::cells_not_prepared; } - // her indices leave valid: any recomputation a change left owed is paid here, never at her bind or later query - v_cells[seq_to_stream[seq_id]].settle_all(); // reserve: every byte the commit copies, so the commit never allocates const uint32_t n_rows = v_cells[seq_to_stream[seq_id]].used_max_p1(); for (size_t i = 0; i < layers.size(); ++i) { @@ -2205,6 +2221,7 @@ void llama_kv_cache::state_write(llama_io_write_i & io, llama_seq_id seq_id, lla } void llama_kv_cache::state_read(llama_io_read_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) { + const llama_kv_settle_on_return settle{ v_cells }; // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] if (other) { return; diff --git a/src/llama-kv-cell-index.h b/src/llama-kv-cell-index.h index f5901150f8ff..c8666e10b516 100644 --- a/src/llama-kv-cell-index.h +++ b/src/llama-kv-cell-index.h @@ -19,6 +19,7 @@ #include "llama.h" #include +#include #include #include #include @@ -236,3 +237,22 @@ class llama_kv_seq_pos { std::vector runs; bool stale = false; }; + +// A count any thread may add to (a query answered from the cells because its index was stale), copied with its object. +// Queries arrive from other threads (llama-server answers /slots and /metrics while a decode runs), so the count is the +// one thing a query writes. +class llama_kv_query_count { +public: + llama_kv_query_count() = default; + llama_kv_query_count(const llama_kv_query_count & other) : n(other.load()) {} + llama_kv_query_count & operator=(const llama_kv_query_count & other) { + n.store(other.load(), std::memory_order_relaxed); + return *this; + } + + void add() const { n.fetch_add(1, std::memory_order_relaxed); } + uint64_t load() const { return n.load(std::memory_order_relaxed); } + +private: + mutable std::atomic n{ 0 }; +}; diff --git a/src/llama-kv-cells.h b/src/llama-kv-cells.h index 314bdcffa3ba..531e8b938837 100644 --- a/src/llama-kv-cells.h +++ b/src/llama-kv-cells.h @@ -44,6 +44,7 @@ class llama_kv_cells { for (int s = 0; s < LLAMA_MAX_SEQ; ++s) { seq_pos[s].swap(other.seq_pos[s]); } + std::swap(stale, other.stale); } void reset() { @@ -61,6 +62,7 @@ class llama_kv_cells { for (uint32_t s = 0; s < LLAMA_MAX_SEQ; ++s) { seq_pos[s].clear(); } + stale.reset(); } void reset_shift() { @@ -92,13 +94,24 @@ class llama_kv_cells { return pos[i] == -1; } - // Continuum fork (CONTINUUM-ENGINE 4.14): recompute every stale sequence index now. A persona's blocks leave a - // stream only with valid indices (her save's reserve phase calls this, where allocation may fail), so a bind or - // any query after it never scans or sorts: a recomputation is never deferred across a freeze. - void settle_all() const { + // Continuum fork (CONTINUUM-ENGINE 4.14): recompute every stale sequence index now, on the thread that changed the + // cells. llama_kv_cache calls this as each of its operations returns, so a query never writes an index: queries + // arrive from other threads while a decode runs, and a persona's blocks leave a stream with valid indices. + void settle_all() { + if (stale.none()) { + return; + } for (llama_seq_id s = 0; s < LLAMA_MAX_SEQ; ++s) { - settled(s); + if (stale.test(s)) { + settle(s); + } } + stale.reset(); + } + + // any sequence index a change left stale and nothing has settled yet + bool has_stale() const { + return stale.any(); } // how many index recomputations this object has made @@ -106,6 +119,12 @@ class llama_kv_cells { return n_settles; } + // how many queries were answered from the cells because an index was stale: a missed settle, 0 when every change + // was settled by its operation + uint64_t stale_queries() const { + return n_stale_queries.load(); + } + uint32_t get_used() const { return used.size(); } @@ -365,7 +384,10 @@ class llama_kv_cells { assert(seq_id >= 0); assert(seq_id < LLAMA_MAX_SEQ); - const llama_kv_seq_pos & index = settled(seq_id); + const llama_kv_seq_pos & index = seq_pos[seq_id]; + if (index.is_stale()) { + return unsettled_extremum(seq_id, false); + } return index.empty() ? -1 : index.min(); } @@ -375,7 +397,10 @@ class llama_kv_cells { assert(seq_id >= 0); assert(seq_id < LLAMA_MAX_SEQ); - const llama_kv_seq_pos & index = settled(seq_id); + const llama_kv_seq_pos & index = seq_pos[seq_id]; + if (index.is_stale()) { + return unsettled_extremum(seq_id, true); + } return index.empty() ? -1 : index.max(); } @@ -516,36 +541,57 @@ class llama_kv_cells { // - some vision models have input embeddings with repeating positions // // Continuum fork: each sequence's positions as a native sorted array with counts (llama-kv-cell-index.h), exact on - // its O(1) paths and recomputed from the cells at the next query after any other change (`settled`). - mutable llama_kv_seq_pos seq_pos[LLAMA_MAX_SEQ]; + // its O(1) paths; any other change marks it stale (`stale`), and the operation that made the change settles it. + llama_kv_seq_pos seq_pos[LLAMA_MAX_SEQ]; + + // the sequences whose index a change left stale, so settling visits only those + std::bitset stale; // how many times an index was recomputed from the cells (the freeze and restore fixtures count them) - mutable uint64_t n_settles = 0; + uint64_t n_settles = 0; + + // queries answered from the cells because an index was stale (the only thing a query writes) + llama_kv_query_count n_stale_queries; + + // recompute sequence seq_id's index from the cells + void settle(llama_seq_id seq_id) { + ++n_settles; + std::vector positions; + for (uint32_t i = used.min(); i < used.max_p1(); ++i) { + if (seq[i].test(seq_id)) { + positions.push_back(pos[i]); + } + } + seq_pos[seq_id].settle(positions); + } - // sequence seq_id's index, recomputed from the cells first if a change left it stale - const llama_kv_seq_pos & settled(llama_seq_id seq_id) const { - llama_kv_seq_pos & index = seq_pos[seq_id]; - if (index.is_stale()) { - ++n_settles; - std::vector positions; - for (uint32_t i = used.min(); i < used.max_p1(); ++i) { - if (seq[i].test(seq_id)) { - positions.push_back(pos[i]); - } + // a stale sequence's min or max read from the cells without writing its index, counted: correct, and a defect + // (the operation that changed the cells did not settle them) + llama_pos unsettled_extremum(llama_seq_id seq_id, bool want_max) const { + n_stale_queries.add(); + llama_pos found = -1; + for (uint32_t i = used.min(); i < used.max_p1(); ++i) { + if (seq[i].test(seq_id) && (found == -1 || (want_max ? pos[i] > found : pos[i] < found))) { + found = pos[i]; } - index.settle(positions); } - return index; + return found; } // helper functions for updating `seq_pos`, once cell at a time: void seq_pos_dec(llama_seq_id s, llama_pos p) { seq_pos[s].dec(p); + if (seq_pos[s].is_stale()) { + stale.set(s); + } } void seq_pos_inc(llama_seq_id s, llama_pos p) { seq_pos[s].inc(p); + if (seq_pos[s].is_stale()) { + stale.set(s); + } } // remove cell i diff --git a/tests/test-kv-cell-index.cpp b/tests/test-kv-cell-index.cpp index 8d4d0eeb7602..32f0db7543c1 100644 --- a/tests/test-kv-cell-index.cpp +++ b/tests/test-kv-cell-index.cpp @@ -139,11 +139,40 @@ void equivalence(uint32_t n_cells, int n_seq, int steps, uint32_t seed) { break; } } + // a stale index is answered from the cells, correct, before anything settles it compare(cells, ref, n_seq, step); + // what llama_kv_cache does as the operation returns; after it every answer is the index's, none from the cells + cells.settle_all(); + const uint64_t answered_from_cells = cells.stale_queries(); + compare(cells, ref, n_seq, step); + expect(!cells.has_stale(), "settling leaves no stale index", step); + expect(cells.stale_queries() == answered_from_cells, "a settled index answers every query", step); if (failures) { return; } } } +// what this catches: a query that writes. llama-server answers /slots and /metrics on another thread while a decode +// changes the cells, so a query that recomputed a stale index in place would race the decode. A query on a stale index +// answers correctly from the cells, counted, and leaves the index exactly as stale as it found it. +void queries_never_write() { + const uint32_t n = 64; + llama_kv_cells cells; + cells.resize(n); + reference ref(n); + for (uint32_t i = 0; i < 16; ++i) { + cells.pos_set(i, llama_pos(i)); ref.pos_set(i, llama_pos(i)); + cells.seq_add(i, 0); ref.seq_add(i, 0); + } + cells.rm(3); ref.rm(3); // inside the range: stale + expect(cells.has_stale(), "a removal inside the range leaves the index stale", -2); + for (int q = 0; q < 4; ++q) { + expect(cells.seq_pos_min(0) == ref.min(0) && cells.seq_pos_max(0) == ref.max(0), "a stale query is exact", -2); + } + expect(cells.has_stale(), "a query left the index stale (it wrote nothing)", -2); + expect(cells.settles() == 0, "a query recomputed nothing", -2); + expect(cells.stale_queries() == 8, "each stale query is counted", -2); +} + // what this catches (Codex's review of 2d54d4869): an index left stale by a genuine change (a division that merges // positions, a removal inside the range) carried across her freeze and recomputed only at her next query after the // bind. Her save settles every index (llama_kv_cache::persona_check_save calls settle_all); the object bound to a stream @@ -162,16 +191,20 @@ void freeze_then_bind() { } cells.rm(5); ref.rm(5); const uint64_t before = cells.settles(); - cells.settle_all(); // her save's reserve phase - expect(cells.settles() > before, "the change was paid for at the freeze", -1); + cells.settle_all(); // the cache's operation returning, before her save + expect(cells.settles() > before, "the change was paid for before the freeze", -1); llama_kv_cells bound; bound.resize(n); bound.swap(cells); // her blocks bound to a stream compare(bound, ref, 2, -1); - expect(bound.settles() == 0, "a query after the bind recomputed nothing", -1); + expect(bound.settles() == 0 && bound.stale_queries() == 0, "a query after the bind answered from the index", -1); } +// the native cells settle as the cache's operation returns; the previous indices had nothing to settle +void settle(llama_kv_cells_previous &) {} +void settle(llama_kv_cells & cells) { cells.settle_all(); } + // The same workload on the previous implementation (kv-cells-previous.h, verbatim) and the native one, timed and with // the allocations it makes counted: her context appended token by token, its front half dropped (a context shift's // discard), the rest shifted down, and her extrema read after each phase (so a deferred recomputation is charged). @@ -189,7 +222,7 @@ measured workload(uint32_t n, bool count) { cells.resize(n); volatile llama_pos sink = 0; const llama_pos d = -llama_pos(n / 2); - auto read = [&] { sink = cells.seq_pos_min(0) + cells.seq_pos_max(0) + llama_pos(cells.get_used()); }; + auto read = [&] { settle(cells); sink =cells.seq_pos_min(0) + cells.seq_pos_max(0) + llama_pos(cells.get_used()); }; allocations = 0; counting = count; const auto t0 = std::chrono::steady_clock::now(); @@ -249,6 +282,7 @@ int main(int argc, char ** /* argv: only the flag count is read */) { equivalence(256, 4, 20000, seed); } freeze_then_bind(); + queries_never_write(); if (failures) { fprintf(stderr, "kv-cell-index: %d mismatches against the node-container indices\n", failures); return 1; From 6aea5d49339a92bfee8fdbebc7301448e1f303ac Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 11:42:20 -0600 Subject: [PATCH 15/28] server: /slots reads the cache on the main thread only; a deterministic late-arrival capacity test /slots and /cells read the cache (kv_pos_min/kv_pos_max, llama_memory_cell_usage; this fork's additions, #92) and SLOT_GET is answered on the queue's worker while a decode changes the cache (yield_to_queue). Now the main thread reads them: yield_decoding reads every slot's positions and the cell usage, then yields; the yield's mutex orders that read before the worker's, and the worker answers from what was read, never the cache. On the main thread (not yielding) SLOT_GET reads first. All four decode/draft yields go through yield_decoding. test_completion_unified_late_arrival_overflows: the capacity contract behind test_completion_unified's all-pass case, made deterministic. The 40-token request is sent only after /slots shows the three 90-token requests 40+ tokens in; 12 + 4g + 3d cells exceed 256 before it can finish, so it and the batch fail with "Context size has been exceeded" on any machine. Both Windows failures on #147 had the fourth request posted 15 and 25 ms late (d = 41, 255 cells). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tools/server/server-context.cpp | 80 ++++++++++++++++------ tools/server/tests/unit/test_completion.py | 30 ++++++++ 2 files changed, 88 insertions(+), 22 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 15831cececbc..ab3f74909525 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -725,6 +725,19 @@ struct server_slot { common_speculative_print_stats(spec); } + // The engine's positions for this slot's sequence as the main loop last read them (Continuum fork). /slots is + // answered on the queue's worker while a decode changes the cache (yield_to_queue), so it reports these, read on + // the main thread before every yield, never the cache itself. -1 when the sequence is empty. + llama_pos kv_pos_min_read = -1; + llama_pos kv_pos_max_read = -1; + + // main thread only: read this slot's positions from the cache + void read_kv_positions() { + llama_memory_t mem = llama_get_memory(ctx_tgt); + kv_pos_min_read = llama_memory_seq_pos_min(mem, id); + kv_pos_max_read = llama_memory_seq_pos_max(mem, id); + } + json to_json(bool only_metrics = false) const { json res; @@ -737,13 +750,9 @@ struct server_slot { {"learn_graph_steps", learn_graph_steps}, }; - // The engine's own positions for this slot's sequence (Continuum fork): what its cache holds - // now, in flight or idle. -1 when the sequence is empty. - { - llama_memory_t mem = llama_get_memory(ctx_tgt); - res["kv_pos_min"] = llama_memory_seq_pos_min(mem, id); - res["kv_pos_max"] = llama_memory_seq_pos_max(mem, id); - } + // The engine's own positions for this slot's sequence as last read by the main loop (Continuum fork). + res["kv_pos_min"] = kv_pos_min_read; + res["kv_pos_max"] = kv_pos_max_read; // The slot's context checkpoints as they sit in host memory now (Continuum fork): their count // and their bytes, so the core prices the checkpoint store from what it holds, not a guess. @@ -914,6 +923,34 @@ struct server_context_impl { // the report never names a size the slots refuse (it said 524288 while each slot capped at // 262144, the M5 2026-11-11). int n_ctx_slot = 0; + + // Every cell holder's occupancy as the main loop last read it (Continuum fork, GET /cells), beside each slot's + // positions (server_slot::kv_pos_*_read). A decode runs on the main thread while the queue's worker answers + // /slots (yield_to_queue), so the main thread reads the cache here before it yields, the yield's mutex orders the + // read before the worker's, and the worker never touches the cache a decode is changing. + std::vector cells_read; + + // main thread only + void read_kv_state() { + for (auto & slot : slots) { + slot.read_kv_positions(); + } + llama_memory_t mem = llama_get_memory(ctx_tgt); + cells_read.resize(std::max(cells_read.capacity(), 8)); + int32_t n = llama_memory_cell_usage(mem, cells_read.data(), (int32_t) cells_read.size()); + if (n > (int32_t) cells_read.size()) { + cells_read.resize(n); + n = llama_memory_cell_usage(mem, cells_read.data(), n); + } + cells_read.resize(n); + } + + // every decode or draft that lets the queue run beside it: the state /slots reports is read first + void yield_decoding(std::function && work) { + read_kv_state(); + queue_tasks.yield_to_queue(std::move(work)); + } + void publish_busy_slots() { int n = 0; for (const auto & slot : slots) { @@ -2817,6 +2854,12 @@ struct server_context_impl { } break; case SERVER_TASK_TYPE_SLOT_GET: { + // On the main thread the cache is read now; on the worker during a decode, the main thread + // read it just before it yielded (yield_decoding), and the worker reads only those. + if (!is_yielding) { + read_kv_state(); + } + json slots_data = json::array(); int n_idle_slots = 0; @@ -2834,19 +2877,12 @@ struct server_context_impl { res->id = task.id; res->slots_data = std::move(slots_data); res->n_idle_slots = n_idle_slots; - // Every cell holder's occupancy, read in the same main-loop pass as the slots so - // the two agree (Continuum fork, GET /cells). + // Every cell holder's occupancy, read in the same main-thread read as the slots' positions + // so the two agree (Continuum fork, GET /cells). { - llama_memory_t mem = llama_get_memory(ctx_tgt); - std::vector holders(8); - int32_t n = llama_memory_cell_usage(mem, holders.data(), (int32_t) holders.size()); - if (n > (int32_t) holders.size()) { - holders.resize(n); - n = llama_memory_cell_usage(mem, holders.data(), n); - } json cells = json::array(); - for (int32_t i = 0; i < n; ++i) { - cells.push_back({ {"holder", holders[i].holder}, {"used", holders[i].used}, {"size", holders[i].size} }); + for (const auto & holder : cells_read) { + cells.push_back({ {"holder", holder.holder}, {"used", holder.used}, {"size", holder.size} }); } res->cells = std::move(cells); } @@ -3559,7 +3595,7 @@ struct server_context_impl { // generate the actual drafts (if any) if (!drafting.empty()) { - queue_tasks.yield_to_queue([&]() { + yield_decoding([&]() { common_speculative_draft(spec.get()); }); } @@ -4049,7 +4085,7 @@ struct server_context_impl { // encode on the worker thread, so we can still handle metrics tasks size_t n_tokens_out = 0; int32_t res = 0; - queue_tasks.yield_to_queue([&]() { + yield_decoding([&]() { res = process_mtmd_chunk(slot, slot.mbatch, cur_token_idx, n_tokens_out); }); @@ -4281,7 +4317,7 @@ struct server_context_impl { // yield to the queue, so we can still handle metrics tasks while decoding // note: the sync is done here too, so that the wait is also covered by the yield int ret = 0; - queue_tasks.yield_to_queue([&]() { + yield_decoding([&]() { ret = llama_decode(ctx_tgt, batch_view); if (ret == 0 && has_output) { llama_synchronize(ctx_tgt); @@ -4346,7 +4382,7 @@ struct server_context_impl { // ref: https://github.com/ggml-org/llama.cpp/pull/22728#issuecomment-4400925384 if (spec) { bool ok = true; - queue_tasks.yield_to_queue([&]() { + yield_decoding([&]() { ok = common_speculative_process(spec.get(), batch_view); }); diff --git a/tools/server/tests/unit/test_completion.py b/tools/server/tests/unit/test_completion.py index 9375e0110e53..0da9322610c2 100644 --- a/tools/server/tests/unit/test_completion.py +++ b/tools/server/tests/unit/test_completion.py @@ -403,6 +403,36 @@ def test_completion_unified(n_ctx, n_slots, n_predict_vals, expected_success): assert res.body["timings"]["predicted_n"] == n_predict +# Continuum fork (#147): the capacity contract test_completion_unified's all-pass case rests on, made deterministic. +# Four requests share 256 unified cells (3-token prompts). A 40-token request starting d decode steps behind three +# 90-token ones needs, at g tokens in, 3 * (3 + g + d) + (3 + g) = 12 + 4g + 3d cells: past 256 before it reaches 40 +# once d > 28. So that case passes only when the four arrive together; in its two Windows failures on #147 the fourth +# was posted 15 and 25 ms late (d = 41 at the overflow, 32 + 73 + 73 + 77 = 255 cells). Here the late request is sent +# only after /slots shows every early request at least 40 tokens in, so the overflow is certain on any machine. Its +# /slots polling also exercises the reads a decode answers beside it (yield_decoding). +def test_completion_unified_late_arrival_overflows(): + global server + from concurrent.futures import ThreadPoolExecutor + server.n_slots = 4 + server.kv_unified = True + server.n_ctx = 256 + server.server_slots = True + server.start() + request = lambda n_predict: server.make_request("POST", "/completion", {"prompt": "A", "n_predict": n_predict}) + with ThreadPoolExecutor(max_workers=3) as pool: + early = [pool.submit(request, 90) for _ in range(3)] + while True: + busy = [s for s in server.make_request("GET", "/slots").body if s["is_processing"]] + if len(busy) == 3 and min(s["next_token"][0]["n_decoded"] for s in busy) >= 40: + break + assert not any(f.done() for f in early), "an early request ended before the late one was sent" + late = request(40) + early_results = [f.result() for f in early] + assert late.status_code == 500, "the late request cannot fit beside three requests 40+ tokens ahead" + assert "Context size has been exceeded" in str(late.body) + assert all(res.status_code == 500 for res in early_results), "an exceeded context ends every request in the batch" + + @pytest.mark.parametrize( "prompt,n_predict,response_fields", [ From b8f7f5842800d56fc2338e1ee89aec3c5e036190 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 13:48:09 -0600 Subject: [PATCH 16/28] llama: a public seam for a persona's move: init, save, load, free, status The persona move (CONTINUUM-ENGINE 4.14: raw block copies plus a swap of her cell records, two-phase, typed refusals) was internal to llama_context, so the server could not switch personas with it and still serialized through llama_state_seq. llama_persona is now an opaque handle to her host blocks, prepared once for the context's memory; llama_persona_save moves a sequence out (her stream left empty) and llama_persona_load binds her back, as the sequence she was saved from, into an empty stream. Status codes are the existing llama_persona_move values, named by llama_persona_status_name. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- include/llama.h | 19 +++++++++++++++++++ src/llama-context.cpp | 31 +++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/include/llama.h b/include/llama.h index 6ff7b047fd40..4bc7bc80ca33 100644 --- a/include/llama.h +++ b/include/llama.h @@ -927,6 +927,25 @@ extern "C" { struct llama_memory_cells_report * out, int32_t n_max); + // A persona's execution state as native blocks in host memory (Continuum fork, CONTINUUM-ENGINE 4.14). A switch + // between personas is raw row copies and a swap of her cell records: nothing tokenized, serialized, walked or + // recomputed. Her blocks stay tagged with the sequence they were saved from and load back under it, into any empty + // stream; the memory must hold one stream per sequence (not unified) with V not transposed (flash attention on). + struct llama_persona; + + // Blocks prepared once for this context's memory (sized to a stream), empty. NULL when the memory has no persona move. + LLAMA_API struct llama_persona * llama_persona_init(struct llama_context * ctx); + LLAMA_API void llama_persona_free(struct llama_persona * persona); + + // Move sequence seq_id's state out of the memory into persona's blocks; her stream is left empty. Two-phase: a + // refusal leaves both sides as they were. 0 when done, else a status for llama_persona_status_name. + LLAMA_API int32_t llama_persona_save(struct llama_context * ctx, llama_seq_id seq_id, struct llama_persona * persona); + + // Bind persona's blocks into the empty stream as sequence seq_id (the sequence they were saved from). 0 when done. + LLAMA_API int32_t llama_persona_load(struct llama_context * ctx, llama_seq_id seq_id, uint32_t stream, struct llama_persona * persona); + + LLAMA_API const char * llama_persona_status_name(int32_t status); + // // State / sessions // diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 52c459bf74b5..c320fede9ebd 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -4237,3 +4237,34 @@ 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; } + +// Continuum fork (CONTINUUM-ENGINE 4.14): the public seam of a persona's move (llama-persona-blocks.h). + +struct llama_persona { + llama_persona_blocks blocks; +}; + +llama_persona * llama_persona_init(llama_context * ctx) { + auto * persona = new llama_persona(); + if (ctx->persona_prepare(persona->blocks) != llama_persona_move::done) { + delete persona; + return nullptr; + } + return persona; +} + +void llama_persona_free(llama_persona * persona) { + delete persona; +} + +int32_t llama_persona_save(llama_context * ctx, llama_seq_id seq_id, llama_persona * persona) { + return (int32_t) ctx->persona_save(seq_id, persona->blocks); +} + +int32_t llama_persona_load(llama_context * ctx, llama_seq_id seq_id, uint32_t stream, llama_persona * persona) { + return (int32_t) ctx->persona_load(seq_id, stream, persona->blocks); +} + +const char * llama_persona_status_name(int32_t status) { + return llama_persona_move_name((llama_persona_move) status); +} From 0f1acdbeff02c650a6990863cce62445a6662c9e Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 14:30:23 -0600 Subject: [PATCH 17/28] llama: a persona's token history as one reserved contiguous buffer, appended by one validated transaction (prototype, CONTINUUM-ENGINE 4.14) Her token ids live in one reserved array owned with her blocks. A request appends only its new ids: the header names persona, epoch, expected frontier and the request's 128-bit identity; the owner validates all of it, then writes the delta into reserved capacity (never an allocation or a copy of what she holds). The same request again returns its receipt; the same identity with another delta is refused; past capacity is refused for the owner to grow. Her generated tokens join the same tail as she samples them. test-persona-tokens: three acts with generated reasoning (history == served + generated + new), replay/changed, stale/foreign/moved/empty, no_room; measured on the M5 at -O2 with the writes read back: a 2,048-token append onto a 100k-token history, 756-846 ns. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- src/llama-persona-tokens.h | 150 ++++++++++++++++++++++++++++++++++ tests/CMakeLists.txt | 2 + tests/test-persona-tokens.cpp | 95 +++++++++++++++++++++ 3 files changed, 247 insertions(+) create mode 100644 src/llama-persona-tokens.h create mode 100644 tests/test-persona-tokens.cpp diff --git a/src/llama-persona-tokens.h b/src/llama-persona-tokens.h new file mode 100644 index 000000000000..0fe6f41a8a91 --- /dev/null +++ b/src/llama-persona-tokens.h @@ -0,0 +1,150 @@ +#pragma once + +#include "llama.h" + +#include +#include +#include +#include + +// A persona's token history: one contiguous, reserved buffer of her token ids, owned with her blocks +// (CONTINUUM-ENGINE 4.14, "the persona is one contiguous structure; a request appends token ids"). +// +// Her tokens are what her blocks hold, in order: what she was served and what she generated, exactly. +// A request never re-sends them; it appends only its new ids, in one validated transaction: +// - its header names her persona, her epoch, the frontier it expects her history to end at, and the +// request's own identity (a 128-bit id the caller mints); +// - the owner validates all of it, then writes the delta into capacity already reserved: never an +// allocation or a copy of what she holds (growth is the admitted owner's, measured separately); +// - the same request again returns its receipt, unchanged; a different delta under the same identity is +// refused; a lost response is never a reason to append twice. +// Plain arrays and memcpy: no containers, no encoding. + +struct llama_persona_request_id { + uint64_t hi = 0; + uint64_t lo = 0; + + bool operator==(const llama_persona_request_id & o) const { return hi == o.hi && lo == o.lo; } + bool empty() const { return hi == 0 && lo == 0; } +}; + +// A fixed-width header: what a request asserts about her history before its delta is appended. +struct llama_persona_append { + uint64_t persona = 0; + uint64_t epoch = 0; + uint64_t frontier = 0; // where the request expects her history to end now + llama_persona_request_id request; +}; + +enum class llama_persona_append_status { + appended, // the delta is now hers + replayed, // this request was already appended: its receipt, nothing written + wrong_persona, // the header names another persona + wrong_epoch, // her epoch moved (a new view started): the request is stale + moved, // her history does not end where the request expects + changed, // the same request identity with a different delta: refused, never overwritten + no_room, // her reserved capacity cannot hold the delta: her owner grows it first + empty_request, // a request with no identity cannot be made idempotent +}; + +inline const char * llama_persona_append_status_name(llama_persona_append_status s) { + switch (s) { + case llama_persona_append_status::appended: return "appended"; + case llama_persona_append_status::replayed: return "replayed"; + case llama_persona_append_status::wrong_persona: return "wrong_persona"; + case llama_persona_append_status::wrong_epoch: return "wrong_epoch"; + case llama_persona_append_status::moved: return "moved"; + case llama_persona_append_status::changed: return "changed"; + case llama_persona_append_status::no_room: return "no_room"; + case llama_persona_append_status::empty_request: return "empty_request"; + } + return "unknown"; +} + +struct llama_persona_receipt { + llama_persona_append_status status = llama_persona_append_status::empty_request; + uint64_t from = 0; // where the delta starts in her history + uint64_t to = 0; // her frontier after it +}; + +class llama_persona_tokens { +public: + llama_persona_tokens(uint64_t persona, uint64_t epoch, size_t capacity) + : persona_(persona), epoch_(epoch), capacity_(capacity), ids_(new llama_token[capacity]) {} + + uint64_t persona() const { return persona_; } + uint64_t epoch() const { return epoch_; } + uint64_t frontier() const { return n_; } + size_t capacity() const { return capacity_; } + const llama_token * data() const { return ids_.get(); } + + // Her generated tokens join her history as she samples them: the same reserved tail, one id at a time. + bool generated(llama_token id) { + if (n_ >= capacity_) { + return false; + } + ids_[n_++] = id; + return true; + } + + // One validated transaction: check her identity, epoch and frontier, then write the delta into the + // reserved tail. `delta` is read in place (the caller's buffer, valid for the call). + llama_persona_receipt append(const llama_persona_append & h, const llama_token * delta, size_t n_delta) { + llama_persona_receipt r; + if (h.request.empty()) { + return r; + } + if (h.persona != persona_) { + r.status = llama_persona_append_status::wrong_persona; + return r; + } + if (h.epoch != epoch_) { + r.status = llama_persona_append_status::wrong_epoch; + return r; + } + // The same request again: its receipt if it carries the same delta, refused if it does not. + if (has_last_ && h.request == last_.request) { + const bool same = h.frontier == last_from_ && n_delta == last_.to - last_.from && + std::memcmp(ids_.get() + last_.from, delta, n_delta * sizeof(llama_token)) == 0; + r = last_; + r.status = same ? llama_persona_append_status::replayed : llama_persona_append_status::changed; + return r; + } + if (h.frontier != n_) { + r.status = llama_persona_append_status::moved; + r.to = n_; + return r; + } + if (n_delta > capacity_ - n_) { + r.status = llama_persona_append_status::no_room; + r.to = n_; + return r; + } + std::memcpy(ids_.get() + n_, delta, n_delta * sizeof(llama_token)); + r.status = llama_persona_append_status::appended; + r.from = n_; + r.to = n_ + n_delta; + n_ = r.to; + last_from_ = h.frontier; + last_ = { r.status, r.from, r.to }; + last_.request = h.request; + has_last_ = true; + return r; + } + +private: + struct last_append : llama_persona_receipt { + llama_persona_request_id request; + last_append() = default; + last_append(llama_persona_append_status s, uint64_t f, uint64_t t) { status = s; from = f; to = t; } + }; + + uint64_t persona_; + uint64_t epoch_; + size_t capacity_; + std::unique_ptr ids_; + uint64_t n_ = 0; + bool has_last_ = false; + uint64_t last_from_ = 0; + last_append last_; +}; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 885c2936adb2..9e772f7345c8 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -191,6 +191,8 @@ llama_build_and_test(test-server-view-end.cpp) # llama_kv_cells' derived indices held natively answer exactly as the node containers they replace (CONTINUUM-ENGINE 4.14) llama_build_and_test(test-kv-cell-index.cpp) +# a persona's token history appends only a request's new ids, in one validated transaction (CONTINUUM-ENGINE 4.14) +llama_build_and_test(test-persona-tokens.cpp) # 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-persona-tokens.cpp b/tests/test-persona-tokens.cpp new file mode 100644 index 000000000000..e254af31dcd9 --- /dev/null +++ b/tests/test-persona-tokens.cpp @@ -0,0 +1,95 @@ +// A persona's token history appends only a request's new ids, in one validated transaction +// (src/llama-persona-tokens.h, CONTINUUM-ENGINE 4.14). + +#include "../src/llama-persona-tokens.h" + +#include +#include +#include +#include + +#define CHECK(cond) do { if (!(cond)) { fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, #cond); exit(1); } } while (0) + +using status = llama_persona_append_status; + +int main() { + const llama_persona_request_id act1{ 1, 1 }, act2{ 1, 2 }, act3{ 1, 3 }; + + // what this catches: her history rebuilt per act. Three acts: each request appends only its new ids + // after what she generated; her history is exactly served + generated + new, in order. + { + llama_persona_tokens her(7, 1, 64); + const llama_token prompt[] = { 1, 40, 9, 2, 7 }; + CHECK(her.append({ 7, 1, 0, act1 }, prompt, 5).status == status::appended); + std::vector expect(prompt, prompt + 5); + const llama_persona_request_id acts[] = { act2, act3, { 1, 4 } }; + for (int a = 0; a < 3; a++) { + for (llama_token g : { (llama_token) (50 + a), (llama_token) (60 + a) }) { // her reasoning and call + CHECK(her.generated(g)); + expect.push_back(g); + } + const llama_token delta[] = { 9, 1, (llama_token) (70 + a), 9, 2, 7 }; + const auto r = her.append({ 7, 1, her.frontier(), acts[a] }, delta, 6); + CHECK(r.status == status::appended && r.from + 6 == r.to && r.to == her.frontier()); + expect.insert(expect.end(), delta, delta + 6); + } + CHECK(her.frontier() == expect.size()); + CHECK(std::equal(expect.begin(), expect.end(), her.data())); + } + // what this catches: a lost response read as permission to append again. The same request returns + // its receipt and writes nothing; the same identity with another delta is refused. + { + llama_persona_tokens her(7, 1, 16); + const llama_token delta[] = { 1, 2, 3 }; + const auto first = her.append({ 7, 1, 0, act1 }, delta, 3); + const auto again = her.append({ 7, 1, 0, act1 }, delta, 3); + CHECK(again.status == status::replayed && again.from == first.from && again.to == first.to && her.frontier() == 3); + const llama_token other[] = { 1, 2, 4 }; + CHECK(her.append({ 7, 1, 0, act1 }, other, 3).status == status::changed && her.frontier() == 3); + } + // what this catches: a stale or foreign request appended to her history. + { + llama_persona_tokens her(7, 2, 16); + const llama_token delta[] = { 1 }; + CHECK(her.append({ 8, 2, 0, act1 }, delta, 1).status == status::wrong_persona); + CHECK(her.append({ 7, 1, 0, act1 }, delta, 1).status == status::wrong_epoch); + CHECK(her.append({ 7, 2, 5, act1 }, delta, 1).status == status::moved); + CHECK(her.append({ 7, 2, 0, {} }, delta, 1).status == status::empty_request); + CHECK(her.frontier() == 0); + } + // what this catches: an append past her reserved capacity growing it in place (an allocation and a copy + // of what she holds on the hot path): refused, her owner grows first. + { + llama_persona_tokens her(7, 1, 4); + const llama_token delta[] = { 1, 2, 3, 4, 5 }; + CHECK(her.append({ 7, 1, 0, act1 }, delta, 5).status == status::no_room && her.frontier() == 0); + } + // The cost of an act's append at her real size: a 100k-token history, a 2k-token delta. Printed, not + // asserted: the receipt for the design's "a memcpy of the delta" (no prefix touched). + { + llama_persona_tokens her(7, 1, 1 << 20); + std::vector prompt(100000, 5); + CHECK(her.append({ 7, 1, 0, act1 }, prompt.data(), prompt.size()).status == status::appended); + std::vector delta(2048, 6); + volatile llama_token sink = 0; + const auto t0 = std::chrono::steady_clock::now(); + uint64_t n = 0; + for (uint64_t i = 0; i < 100; i++) { + const auto r = her.append({ 7, 1, her.frontier(), { 2, i + 1 } }, delta.data(), delta.size()); + sink = her.data()[r.to - 1]; + n += r.status == status::appended; + } + const double ns = std::chrono::duration(std::chrono::steady_clock::now() - t0).count() / 100; + CHECK(n == 100); + // Read what was written, or the optimizer removes the copies and the number is a lie. + uint64_t sum = 0; + for (uint64_t i = 0; i < her.frontier(); i++) { + sum += (uint64_t) her.data()[i]; + } + CHECK(sum == 100000ull * 5 + 100ull * 2048 * 6); + fprintf(stderr, "append of a 2048-token delta onto a %llu-token history: %.0f ns each\n", + (unsigned long long) prompt.size(), ns); + } + fprintf(stderr, "test-persona-tokens: ok\n"); + return 0; +} From d8537680be1c241b7a563a807fb8b0241555a96c Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 14:41:57 -0600 Subject: [PATCH 18/28] llama: persona token appends are idempotent across her whole sequence, not only the last request Codex's review of 0f1acdbef: a last-request receipt let a delayed retry of A after B read as 'moved', and an empty retry at the same frontier be accepted twice. Each append now carries her request sequence (1, 2, 3 per persona and epoch); every committed append keeps its receipt at index seq - 1. A retry of any committed sequence returns its original receipt and writes nothing; the same sequence with another identity or delta is 'changed'; a later sequence first is 'out_of_order'. Raw contract explicit: a null delta only with length 0 (an empty append commits its sequence); capacity checked without overflow (SIZE_MAX is no_room). test-persona-tokens adds delayed, duplicate, empty and reordered retries; -Wall -Wextra clean; the M5 at -O2 with writes read back: 644-795 ns per 2,048-token append onto 100k. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- src/llama-persona-tokens.h | 88 ++++++++++++++++++-------------- tests/test-persona-tokens.cpp | 95 ++++++++++++++++++++++++----------- 2 files changed, 117 insertions(+), 66 deletions(-) diff --git a/src/llama-persona-tokens.h b/src/llama-persona-tokens.h index 0fe6f41a8a91..f303ced66727 100644 --- a/src/llama-persona-tokens.h +++ b/src/llama-persona-tokens.h @@ -6,19 +6,22 @@ #include #include #include +#include // A persona's token history: one contiguous, reserved buffer of her token ids, owned with her blocks // (CONTINUUM-ENGINE 4.14, "the persona is one contiguous structure; a request appends token ids"). // // Her tokens are what her blocks hold, in order: what she was served and what she generated, exactly. // A request never re-sends them; it appends only its new ids, in one validated transaction: -// - its header names her persona, her epoch, the frontier it expects her history to end at, and the -// request's own identity (a 128-bit id the caller mints); +// - its header names her persona, her epoch, her request sequence (1, 2, 3, ... minted by her one +// caller), the frontier it expects her history to end at, and the request's own 128-bit identity; // - the owner validates all of it, then writes the delta into capacity already reserved: never an // allocation or a copy of what she holds (growth is the admitted owner's, measured separately); -// - the same request again returns its receipt, unchanged; a different delta under the same identity is -// refused; a lost response is never a reason to append twice. -// Plain arrays and memcpy: no containers, no encoding. +// - every committed append keeps its receipt, indexed by its sequence: a retry of ANY committed +// sequence, however delayed or reordered, gets its original receipt and writes nothing; the same +// sequence with another identity or delta is refused; a lost response is never a reason to append twice. +// Raw contract: `delta` may be null only when `n_delta` is 0 (an empty append still commits its sequence +// and receipt); capacity is checked without overflow. Plain arrays and memcpy: no encoding. struct llama_persona_request_id { uint64_t hi = 0; @@ -32,19 +35,21 @@ struct llama_persona_request_id { struct llama_persona_append { uint64_t persona = 0; uint64_t epoch = 0; + uint64_t seq = 0; // her request sequence in this epoch, from 1 uint64_t frontier = 0; // where the request expects her history to end now llama_persona_request_id request; }; enum class llama_persona_append_status { appended, // the delta is now hers - replayed, // this request was already appended: its receipt, nothing written + replayed, // this sequence was already appended by this request: its receipt, nothing written wrong_persona, // the header names another persona wrong_epoch, // her epoch moved (a new view started): the request is stale - moved, // her history does not end where the request expects - changed, // the same request identity with a different delta: refused, never overwritten + out_of_order, // not her next sequence: a gap, or a sequence she never committed + moved, // her next sequence, but her history does not end where the request expects + changed, // a committed sequence with another identity or delta: refused, never overwritten no_room, // her reserved capacity cannot hold the delta: her owner grows it first - empty_request, // a request with no identity cannot be made idempotent + invalid, // no identity, no sequence, or a null delta with a length }; inline const char * llama_persona_append_status_name(llama_persona_append_status s) { @@ -53,16 +58,18 @@ inline const char * llama_persona_append_status_name(llama_persona_append_status case llama_persona_append_status::replayed: return "replayed"; case llama_persona_append_status::wrong_persona: return "wrong_persona"; case llama_persona_append_status::wrong_epoch: return "wrong_epoch"; + case llama_persona_append_status::out_of_order: return "out_of_order"; case llama_persona_append_status::moved: return "moved"; case llama_persona_append_status::changed: return "changed"; case llama_persona_append_status::no_room: return "no_room"; - case llama_persona_append_status::empty_request: return "empty_request"; + case llama_persona_append_status::invalid: return "invalid"; } return "unknown"; } struct llama_persona_receipt { - llama_persona_append_status status = llama_persona_append_status::empty_request; + llama_persona_append_status status = llama_persona_append_status::invalid; + uint64_t seq = 0; uint64_t from = 0; // where the delta starts in her history uint64_t to = 0; // her frontier after it }; @@ -75,6 +82,7 @@ class llama_persona_tokens { uint64_t persona() const { return persona_; } uint64_t epoch() const { return epoch_; } uint64_t frontier() const { return n_; } + uint64_t committed() const { return committed_.size(); } size_t capacity() const { return capacity_; } const llama_token * data() const { return ids_.get(); } @@ -87,12 +95,13 @@ class llama_persona_tokens { return true; } - // One validated transaction: check her identity, epoch and frontier, then write the delta into the - // reserved tail. `delta` is read in place (the caller's buffer, valid for the call). + // One validated transaction: check her identity, epoch, sequence and frontier, then write the delta + // into the reserved tail. `delta` is read in place (the caller's buffer, valid for the call). llama_persona_receipt append(const llama_persona_append & h, const llama_token * delta, size_t n_delta) { llama_persona_receipt r; - if (h.request.empty()) { - return r; + r.seq = h.seq; + if (h.request.empty() || h.seq == 0 || (delta == nullptr && n_delta != 0)) { + return r; // invalid } if (h.persona != persona_) { r.status = llama_persona_append_status::wrong_persona; @@ -102,12 +111,18 @@ class llama_persona_tokens { r.status = llama_persona_append_status::wrong_epoch; return r; } - // The same request again: its receipt if it carries the same delta, refused if it does not. - if (has_last_ && h.request == last_.request) { - const bool same = h.frontier == last_from_ && n_delta == last_.to - last_.from && - std::memcmp(ids_.get() + last_.from, delta, n_delta * sizeof(llama_token)) == 0; - r = last_; + // A committed sequence: its own receipt for the same request and delta, refused for anything else. + if (h.seq <= committed_.size()) { + const commit_record & c = committed_[h.seq - 1]; + const bool same = c.request == h.request && c.expected == h.frontier && n_delta == c.to - c.from && + (n_delta == 0 || std::memcmp(ids_.get() + c.from, delta, n_delta * sizeof(llama_token)) == 0); r.status = same ? llama_persona_append_status::replayed : llama_persona_append_status::changed; + r.from = c.from; + r.to = c.to; + return r; + } + if (h.seq != committed_.size() + 1) { + r.status = llama_persona_append_status::out_of_order; return r; } if (h.frontier != n_) { @@ -115,36 +130,35 @@ class llama_persona_tokens { r.to = n_; return r; } - if (n_delta > capacity_ - n_) { + if (n_delta > capacity_ - n_) { // n_ <= capacity_ always: no overflow r.status = llama_persona_append_status::no_room; r.to = n_; return r; } - std::memcpy(ids_.get() + n_, delta, n_delta * sizeof(llama_token)); - r.status = llama_persona_append_status::appended; - r.from = n_; - r.to = n_ + n_delta; - n_ = r.to; - last_from_ = h.frontier; - last_ = { r.status, r.from, r.to }; - last_.request = h.request; - has_last_ = true; + if (n_delta != 0) { + std::memcpy(ids_.get() + n_, delta, n_delta * sizeof(llama_token)); + } + r.status = llama_persona_append_status::appended; + r.from = n_; + r.to = n_ + n_delta; + committed_.push_back({ h.request, h.frontier, r.from, r.to }); + n_ = r.to; return r; } private: - struct last_append : llama_persona_receipt { + // One committed append, at index seq - 1: who appended it, what it expected, and where it landed. + struct commit_record { llama_persona_request_id request; - last_append() = default; - last_append(llama_persona_append_status s, uint64_t f, uint64_t t) { status = s; from = f; to = t; } + uint64_t expected; + uint64_t from; + uint64_t to; }; uint64_t persona_; uint64_t epoch_; size_t capacity_; std::unique_ptr ids_; - uint64_t n_ = 0; - bool has_last_ = false; - uint64_t last_from_ = 0; - last_append last_; + uint64_t n_ = 0; + std::vector committed_; }; diff --git a/tests/test-persona-tokens.cpp b/tests/test-persona-tokens.cpp index e254af31dcd9..2d9138af894e 100644 --- a/tests/test-persona-tokens.cpp +++ b/tests/test-persona-tokens.cpp @@ -3,7 +3,9 @@ #include "../src/llama-persona-tokens.h" +#include #include +#include #include #include #include @@ -12,76 +14,111 @@ using status = llama_persona_append_status; -int main() { - const llama_persona_request_id act1{ 1, 1 }, act2{ 1, 2 }, act3{ 1, 3 }; +static llama_persona_request_id id(uint64_t n) { return { 1, n }; } + +static llama_persona_append header(uint64_t persona, uint64_t epoch, uint64_t seq, uint64_t frontier, llama_persona_request_id request) { + llama_persona_append h; + h.persona = persona; + h.epoch = epoch; + h.seq = seq; + h.frontier = frontier; + h.request = request; + return h; +} +int main() { // what this catches: her history rebuilt per act. Three acts: each request appends only its new ids // after what she generated; her history is exactly served + generated + new, in order. { llama_persona_tokens her(7, 1, 64); const llama_token prompt[] = { 1, 40, 9, 2, 7 }; - CHECK(her.append({ 7, 1, 0, act1 }, prompt, 5).status == status::appended); + CHECK(her.append(header(7, 1, 1, 0, id(1)), prompt, 5).status == status::appended); std::vector expect(prompt, prompt + 5); - const llama_persona_request_id acts[] = { act2, act3, { 1, 4 } }; - for (int a = 0; a < 3; a++) { + for (uint64_t a = 0; a < 3; a++) { for (llama_token g : { (llama_token) (50 + a), (llama_token) (60 + a) }) { // her reasoning and call CHECK(her.generated(g)); expect.push_back(g); } const llama_token delta[] = { 9, 1, (llama_token) (70 + a), 9, 2, 7 }; - const auto r = her.append({ 7, 1, her.frontier(), acts[a] }, delta, 6); + const auto r = her.append(header(7, 1, a + 2, her.frontier(), id(a + 2)), delta, 6); CHECK(r.status == status::appended && r.from + 6 == r.to && r.to == her.frontier()); expect.insert(expect.end(), delta, delta + 6); } - CHECK(her.frontier() == expect.size()); + CHECK(her.frontier() == expect.size() && her.committed() == 4); CHECK(std::equal(expect.begin(), expect.end(), her.data())); } - // what this catches: a lost response read as permission to append again. The same request returns - // its receipt and writes nothing; the same identity with another delta is refused. + // what this catches: a lost response read as permission to append again, however late the retry comes. + // A then B commit; a delayed retry of A (after B) gets A's original receipt and writes nothing; so does a + // duplicate of B; A's sequence with another request or delta is refused. + { + llama_persona_tokens her(7, 1, 16); + const llama_token a[] = { 1, 2, 3 }, b[] = { 4, 5 }, other[] = { 1, 2, 4 }; + const auto ra = her.append(header(7, 1, 1, 0, id(1)), a, 3); + const auto rb = her.append(header(7, 1, 2, 3, id(2)), b, 2); + CHECK(ra.status == status::appended && rb.status == status::appended && her.frontier() == 5); + const auto late_a = her.append(header(7, 1, 1, 0, id(1)), a, 3); + CHECK(late_a.status == status::replayed && late_a.from == ra.from && late_a.to == ra.to); + CHECK(her.append(header(7, 1, 2, 3, id(2)), b, 2).status == status::replayed); + CHECK(her.append(header(7, 1, 1, 0, id(1)), other, 3).status == status::changed); + CHECK(her.append(header(7, 1, 1, 0, id(9)), a, 3).status == status::changed); + CHECK(her.frontier() == 5 && her.committed() == 2); + } + // what this catches: empty appends at the same frontier letting a retried request be accepted twice. + // Each empty append commits its own sequence; a retry of the first is its receipt, never a new append. + { + llama_persona_tokens her(7, 1, 16); + CHECK(her.append(header(7, 1, 1, 0, id(1)), nullptr, 0).status == status::appended); + CHECK(her.append(header(7, 1, 2, 0, id(2)), nullptr, 0).status == status::appended); + CHECK(her.append(header(7, 1, 1, 0, id(1)), nullptr, 0).status == status::replayed); + CHECK(her.committed() == 2 && her.frontier() == 0); + } + // what this catches: a reordered request (a later sequence arriving first) appended out of order. { llama_persona_tokens her(7, 1, 16); - const llama_token delta[] = { 1, 2, 3 }; - const auto first = her.append({ 7, 1, 0, act1 }, delta, 3); - const auto again = her.append({ 7, 1, 0, act1 }, delta, 3); - CHECK(again.status == status::replayed && again.from == first.from && again.to == first.to && her.frontier() == 3); - const llama_token other[] = { 1, 2, 4 }; - CHECK(her.append({ 7, 1, 0, act1 }, other, 3).status == status::changed && her.frontier() == 3); + const llama_token d[] = { 1 }; + CHECK(her.append(header(7, 1, 2, 0, id(2)), d, 1).status == status::out_of_order); + CHECK(her.append(header(7, 1, 1, 0, id(1)), d, 1).status == status::appended); + CHECK(her.append(header(7, 1, 2, 1, id(2)), d, 1).status == status::appended); + CHECK(her.frontier() == 2); } - // what this catches: a stale or foreign request appended to her history. + // what this catches: a stale, foreign or malformed request appended to her history. { llama_persona_tokens her(7, 2, 16); - const llama_token delta[] = { 1 }; - CHECK(her.append({ 8, 2, 0, act1 }, delta, 1).status == status::wrong_persona); - CHECK(her.append({ 7, 1, 0, act1 }, delta, 1).status == status::wrong_epoch); - CHECK(her.append({ 7, 2, 5, act1 }, delta, 1).status == status::moved); - CHECK(her.append({ 7, 2, 0, {} }, delta, 1).status == status::empty_request); - CHECK(her.frontier() == 0); + const llama_token d[] = { 1 }; + CHECK(her.append(header(8, 2, 1, 0, id(1)), d, 1).status == status::wrong_persona); + CHECK(her.append(header(7, 1, 1, 0, id(1)), d, 1).status == status::wrong_epoch); + CHECK(her.append(header(7, 2, 1, 5, id(1)), d, 1).status == status::moved); + CHECK(her.append(header(7, 2, 1, 0, {}), d, 1).status == status::invalid); + CHECK(her.append(header(7, 2, 0, 0, id(1)), d, 1).status == status::invalid); + CHECK(her.append(header(7, 2, 1, 0, id(1)), nullptr, 1).status == status::invalid); + CHECK(her.frontier() == 0 && her.committed() == 0); } // what this catches: an append past her reserved capacity growing it in place (an allocation and a copy - // of what she holds on the hot path): refused, her owner grows first. + // of what she holds on the hot path): refused, her owner grows first; a length that would overflow too. { llama_persona_tokens her(7, 1, 4); - const llama_token delta[] = { 1, 2, 3, 4, 5 }; - CHECK(her.append({ 7, 1, 0, act1 }, delta, 5).status == status::no_room && her.frontier() == 0); + const llama_token d[] = { 1, 2, 3, 4, 5 }; + CHECK(her.append(header(7, 1, 1, 0, id(1)), d, 5).status == status::no_room && her.frontier() == 0); + CHECK(her.append(header(7, 1, 1, 0, id(1)), d, SIZE_MAX).status == status::no_room); } // The cost of an act's append at her real size: a 100k-token history, a 2k-token delta. Printed, not - // asserted: the receipt for the design's "a memcpy of the delta" (no prefix touched). + // asserted; the writes are read back so the optimizer cannot remove them. { llama_persona_tokens her(7, 1, 1 << 20); std::vector prompt(100000, 5); - CHECK(her.append({ 7, 1, 0, act1 }, prompt.data(), prompt.size()).status == status::appended); + CHECK(her.append(header(7, 1, 1, 0, id(1)), prompt.data(), prompt.size()).status == status::appended); std::vector delta(2048, 6); volatile llama_token sink = 0; const auto t0 = std::chrono::steady_clock::now(); uint64_t n = 0; for (uint64_t i = 0; i < 100; i++) { - const auto r = her.append({ 7, 1, her.frontier(), { 2, i + 1 } }, delta.data(), delta.size()); + const auto r = her.append(header(7, 1, i + 2, her.frontier(), id(i + 2)), delta.data(), delta.size()); sink = her.data()[r.to - 1]; n += r.status == status::appended; } const double ns = std::chrono::duration(std::chrono::steady_clock::now() - t0).count() / 100; + (void) sink; CHECK(n == 100); - // Read what was written, or the optimizer removes the copies and the number is a lie. uint64_t sum = 0; for (uint64_t i = 0; i < her.frontier(); i++) { sum += (uint64_t) her.data()[i]; From f3eb5ecbce015d042f34b52f2b73278ff7318c21 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 14:48:51 -0600 Subject: [PATCH 19/28] llama: persona receipts are reserved with her tokens; an accepted append never allocates Codex on d8537680b: the receipt push_back could allocate on the hot path after the delta was written. Receipts are now a fixed array reserved at construction beside her tokens; both reservations are checked before any write, and either running out is no_room (an empty append consumes a receipt). Test: receipt exhaustion leaves her tokens, frontier and commits unchanged, and a committed sequence still replays. M5 -O2, reads back: 395-608 ns per 2,048-token append onto 100k (1,773 ns once, first touch of the reserved pages). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- src/llama-persona-tokens.h | 25 +++++++++++++++---------- tests/test-persona-tokens.cpp | 27 ++++++++++++++++++++------- 2 files changed, 35 insertions(+), 17 deletions(-) diff --git a/src/llama-persona-tokens.h b/src/llama-persona-tokens.h index f303ced66727..03c47c9400c1 100644 --- a/src/llama-persona-tokens.h +++ b/src/llama-persona-tokens.h @@ -6,7 +6,6 @@ #include #include #include -#include // A persona's token history: one contiguous, reserved buffer of her token ids, owned with her blocks // (CONTINUUM-ENGINE 4.14, "the persona is one contiguous structure; a request appends token ids"). @@ -48,7 +47,7 @@ enum class llama_persona_append_status { out_of_order, // not her next sequence: a gap, or a sequence she never committed moved, // her next sequence, but her history does not end where the request expects changed, // a committed sequence with another identity or delta: refused, never overwritten - no_room, // her reserved capacity cannot hold the delta: her owner grows it first + no_room, // her reserved tokens or receipts cannot hold this append: her owner grows them first invalid, // no identity, no sequence, or a null delta with a length }; @@ -76,13 +75,16 @@ struct llama_persona_receipt { class llama_persona_tokens { public: - llama_persona_tokens(uint64_t persona, uint64_t epoch, size_t capacity) - : persona_(persona), epoch_(epoch), capacity_(capacity), ids_(new llama_token[capacity]) {} + // Both arrays are reserved here, by her admitted owner: an accepted append writes into them and never + // allocates (`capacity` token ids, `receipts` committed appends, one per request sequence). + llama_persona_tokens(uint64_t persona, uint64_t epoch, size_t capacity, size_t receipts) + : persona_(persona), epoch_(epoch), capacity_(capacity), ids_(new llama_token[capacity]), + receipt_capacity_(receipts), committed_(new commit_record[receipts]) {} uint64_t persona() const { return persona_; } uint64_t epoch() const { return epoch_; } uint64_t frontier() const { return n_; } - uint64_t committed() const { return committed_.size(); } + uint64_t committed() const { return n_committed_; } size_t capacity() const { return capacity_; } const llama_token * data() const { return ids_.get(); } @@ -112,7 +114,7 @@ class llama_persona_tokens { return r; } // A committed sequence: its own receipt for the same request and delta, refused for anything else. - if (h.seq <= committed_.size()) { + if (h.seq <= n_committed_) { const commit_record & c = committed_[h.seq - 1]; const bool same = c.request == h.request && c.expected == h.frontier && n_delta == c.to - c.from && (n_delta == 0 || std::memcmp(ids_.get() + c.from, delta, n_delta * sizeof(llama_token)) == 0); @@ -121,7 +123,7 @@ class llama_persona_tokens { r.to = c.to; return r; } - if (h.seq != committed_.size() + 1) { + if (h.seq != n_committed_ + 1) { r.status = llama_persona_append_status::out_of_order; return r; } @@ -130,7 +132,8 @@ class llama_persona_tokens { r.to = n_; return r; } - if (n_delta > capacity_ - n_) { // n_ <= capacity_ always: no overflow + // Both reservations are checked before anything is written: a refusal leaves her exactly as she was. + if (n_delta > capacity_ - n_ || n_committed_ == receipt_capacity_) { // n_ <= capacity_ always: no overflow r.status = llama_persona_append_status::no_room; r.to = n_; return r; @@ -141,7 +144,7 @@ class llama_persona_tokens { r.status = llama_persona_append_status::appended; r.from = n_; r.to = n_ + n_delta; - committed_.push_back({ h.request, h.frontier, r.from, r.to }); + committed_[n_committed_++] = { h.request, h.frontier, r.from, r.to }; n_ = r.to; return r; } @@ -160,5 +163,7 @@ class llama_persona_tokens { size_t capacity_; std::unique_ptr ids_; uint64_t n_ = 0; - std::vector committed_; + size_t receipt_capacity_; + std::unique_ptr committed_; + uint64_t n_committed_ = 0; }; diff --git a/tests/test-persona-tokens.cpp b/tests/test-persona-tokens.cpp index 2d9138af894e..81ce0588da59 100644 --- a/tests/test-persona-tokens.cpp +++ b/tests/test-persona-tokens.cpp @@ -30,7 +30,7 @@ int main() { // what this catches: her history rebuilt per act. Three acts: each request appends only its new ids // after what she generated; her history is exactly served + generated + new, in order. { - llama_persona_tokens her(7, 1, 64); + llama_persona_tokens her(7, 1, 64, 16); const llama_token prompt[] = { 1, 40, 9, 2, 7 }; CHECK(her.append(header(7, 1, 1, 0, id(1)), prompt, 5).status == status::appended); std::vector expect(prompt, prompt + 5); @@ -51,7 +51,7 @@ int main() { // A then B commit; a delayed retry of A (after B) gets A's original receipt and writes nothing; so does a // duplicate of B; A's sequence with another request or delta is refused. { - llama_persona_tokens her(7, 1, 16); + llama_persona_tokens her(7, 1, 16, 16); const llama_token a[] = { 1, 2, 3 }, b[] = { 4, 5 }, other[] = { 1, 2, 4 }; const auto ra = her.append(header(7, 1, 1, 0, id(1)), a, 3); const auto rb = her.append(header(7, 1, 2, 3, id(2)), b, 2); @@ -66,7 +66,7 @@ int main() { // what this catches: empty appends at the same frontier letting a retried request be accepted twice. // Each empty append commits its own sequence; a retry of the first is its receipt, never a new append. { - llama_persona_tokens her(7, 1, 16); + llama_persona_tokens her(7, 1, 16, 16); CHECK(her.append(header(7, 1, 1, 0, id(1)), nullptr, 0).status == status::appended); CHECK(her.append(header(7, 1, 2, 0, id(2)), nullptr, 0).status == status::appended); CHECK(her.append(header(7, 1, 1, 0, id(1)), nullptr, 0).status == status::replayed); @@ -74,7 +74,7 @@ int main() { } // what this catches: a reordered request (a later sequence arriving first) appended out of order. { - llama_persona_tokens her(7, 1, 16); + llama_persona_tokens her(7, 1, 16, 16); const llama_token d[] = { 1 }; CHECK(her.append(header(7, 1, 2, 0, id(2)), d, 1).status == status::out_of_order); CHECK(her.append(header(7, 1, 1, 0, id(1)), d, 1).status == status::appended); @@ -83,7 +83,7 @@ int main() { } // what this catches: a stale, foreign or malformed request appended to her history. { - llama_persona_tokens her(7, 2, 16); + llama_persona_tokens her(7, 2, 16, 16); const llama_token d[] = { 1 }; CHECK(her.append(header(8, 2, 1, 0, id(1)), d, 1).status == status::wrong_persona); CHECK(her.append(header(7, 1, 1, 0, id(1)), d, 1).status == status::wrong_epoch); @@ -96,15 +96,28 @@ int main() { // what this catches: an append past her reserved capacity growing it in place (an allocation and a copy // of what she holds on the hot path): refused, her owner grows first; a length that would overflow too. { - llama_persona_tokens her(7, 1, 4); + llama_persona_tokens her(7, 1, 4, 16); const llama_token d[] = { 1, 2, 3, 4, 5 }; CHECK(her.append(header(7, 1, 1, 0, id(1)), d, 5).status == status::no_room && her.frontier() == 0); CHECK(her.append(header(7, 1, 1, 0, id(1)), d, SIZE_MAX).status == status::no_room); } + // what this catches: an accepted append allocating its receipt on the hot path, or a refused one leaving + // a half-written append. Receipts are reserved; when they are used up the append is refused before any + // write, an empty append included, and her tokens, frontier and commits are unchanged. + { + llama_persona_tokens her(7, 1, 16, 2); + const llama_token d[] = { 1, 2 }; + CHECK(her.append(header(7, 1, 1, 0, id(1)), d, 2).status == status::appended); + CHECK(her.append(header(7, 1, 2, 2, id(2)), nullptr, 0).status == status::appended); + CHECK(her.append(header(7, 1, 3, 2, id(3)), d, 2).status == status::no_room); + CHECK(her.append(header(7, 1, 3, 2, id(3)), nullptr, 0).status == status::no_room); + CHECK(her.frontier() == 2 && her.committed() == 2 && her.data()[0] == 1 && her.data()[1] == 2); + CHECK(her.append(header(7, 1, 1, 0, id(1)), d, 2).status == status::replayed); + } // The cost of an act's append at her real size: a 100k-token history, a 2k-token delta. Printed, not // asserted; the writes are read back so the optimizer cannot remove them. { - llama_persona_tokens her(7, 1, 1 << 20); + llama_persona_tokens her(7, 1, 1 << 20, 128); std::vector prompt(100000, 5); CHECK(her.append(header(7, 1, 1, 0, id(1)), prompt.data(), prompt.size()).status == status::appended); std::vector delta(2048, 6); From e046d2ac82b964ca153eab0f9d85ab87dde6658e Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 17 Nov 2026 14:50:09 -0600 Subject: [PATCH 20/28] llama: her token history lives in the persona beside her blocks; a C seam to reserve, append and read it llama_persona now owns her llama_persona_tokens, so a save or load of her blocks carries her token history by reference, never a copy. C API: llama_persona_reserve_tokens (her admitted owner reserves tokens and receipts once), llama_persona_append (fixed-width header + ids read in place, returns the receipt), llama_persona_token_ids, llama_persona_append_status_name. The internal request struct is llama_persona_append_request (the C function owns the name). Syntax-checked llama-context.cpp; test-persona-tokens ok. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- include/llama.h | 35 ++++++++++++++++++++++++++++ src/llama-context.cpp | 43 ++++++++++++++++++++++++++++++++++- src/llama-persona-tokens.h | 4 ++-- tests/test-persona-tokens.cpp | 4 ++-- 4 files changed, 81 insertions(+), 5 deletions(-) diff --git a/include/llama.h b/include/llama.h index 4bc7bc80ca33..442f73241b21 100644 --- a/include/llama.h +++ b/include/llama.h @@ -946,6 +946,41 @@ extern "C" { LLAMA_API const char * llama_persona_status_name(int32_t status); + // Her token history, held in the persona beside her blocks (so it moves with them by reference, never copied): + // one reserved buffer of her token ids and one of her append receipts. A request appends only its new ids, in + // one validated transaction (see llama_persona_append). Reserved once by her admitted owner; 0 when done. + LLAMA_API int32_t llama_persona_reserve_tokens(struct llama_persona * persona, uint64_t persona_id, uint64_t epoch, + size_t n_tokens, size_t n_receipts); + + // What an append asserts about her history: her persona, her epoch, her request sequence (1, 2, 3, ...), the + // frontier it expects her history to end at, and the request's own 128-bit identity. + struct llama_persona_append_header { + uint64_t persona; + uint64_t epoch; + uint64_t seq; + uint64_t frontier; + uint64_t request_hi; + uint64_t request_lo; + }; + + struct llama_persona_append_receipt { + int32_t status; // llama_persona_append_status_name; 0 = appended, 1 = replayed (its original receipt) + uint64_t seq; + uint64_t from; // where the delta starts in her history + uint64_t to; // her frontier after it + }; + + // Append `delta` (n ids, read in place; null only when n is 0) to her history after validating `header`. A retry + // of a committed sequence returns its original receipt and writes nothing; nothing allocates. + LLAMA_API struct llama_persona_append_receipt llama_persona_append(struct llama_persona * persona, + const struct llama_persona_append_header * header, + const llama_token * delta, size_t n); + + // Her history as held: the ids and their count (her frontier). NULL before llama_persona_reserve_tokens. + LLAMA_API const llama_token * llama_persona_token_ids(const struct llama_persona * persona, uint64_t * n); + + LLAMA_API const char * llama_persona_append_status_name(int32_t status); + // // State / sessions // diff --git a/src/llama-context.cpp b/src/llama-context.cpp index c320fede9ebd..917c3aa932d1 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -1,4 +1,5 @@ #include "llama-context.h" +#include "llama-persona-tokens.h" #include "ggml.h" #include "llama-arch.h" @@ -4241,9 +4242,49 @@ llama_context * llama_get_ctx_other(struct llama_context * ctx) { // Continuum fork (CONTINUUM-ENGINE 4.14): the public seam of a persona's move (llama-persona-blocks.h). struct llama_persona { - llama_persona_blocks blocks; + llama_persona_blocks blocks; + std::unique_ptr tokens; // her token history, beside her blocks (llama-persona-tokens.h) }; +int32_t llama_persona_reserve_tokens(llama_persona * persona, uint64_t persona_id, uint64_t epoch, size_t n_tokens, size_t n_receipts) { + persona->tokens = std::make_unique(persona_id, epoch, n_tokens, n_receipts); + return 0; +} + +llama_persona_append_receipt llama_persona_append(llama_persona * persona, const llama_persona_append_header * header, + const llama_token * delta, size_t n) { + llama_persona_append_receipt out = { (int32_t) llama_persona_append_status::invalid, 0, 0, 0 }; + if (persona->tokens == nullptr || header == nullptr) { + return out; + } + llama_persona_append_request h; + h.persona = header->persona; + h.epoch = header->epoch; + h.seq = header->seq; + h.frontier = header->frontier; + h.request.hi = header->request_hi; + h.request.lo = header->request_lo; + const llama_persona_receipt r = persona->tokens->append(h, delta, n); + out.status = (int32_t) r.status; + out.seq = r.seq; + out.from = r.from; + out.to = r.to; + return out; +} + +const llama_token * llama_persona_token_ids(const llama_persona * persona, uint64_t * n) { + if (persona->tokens == nullptr) { + *n = 0; + return nullptr; + } + *n = persona->tokens->frontier(); + return persona->tokens->data(); +} + +const char * llama_persona_append_status_name(int32_t status) { + return llama_persona_append_status_name((llama_persona_append_status) status); +} + llama_persona * llama_persona_init(llama_context * ctx) { auto * persona = new llama_persona(); if (ctx->persona_prepare(persona->blocks) != llama_persona_move::done) { diff --git a/src/llama-persona-tokens.h b/src/llama-persona-tokens.h index 03c47c9400c1..b8a280332407 100644 --- a/src/llama-persona-tokens.h +++ b/src/llama-persona-tokens.h @@ -31,7 +31,7 @@ struct llama_persona_request_id { }; // A fixed-width header: what a request asserts about her history before its delta is appended. -struct llama_persona_append { +struct llama_persona_append_request { uint64_t persona = 0; uint64_t epoch = 0; uint64_t seq = 0; // her request sequence in this epoch, from 1 @@ -99,7 +99,7 @@ class llama_persona_tokens { // One validated transaction: check her identity, epoch, sequence and frontier, then write the delta // into the reserved tail. `delta` is read in place (the caller's buffer, valid for the call). - llama_persona_receipt append(const llama_persona_append & h, const llama_token * delta, size_t n_delta) { + llama_persona_receipt append(const llama_persona_append_request & h, const llama_token * delta, size_t n_delta) { llama_persona_receipt r; r.seq = h.seq; if (h.request.empty() || h.seq == 0 || (delta == nullptr && n_delta != 0)) { diff --git a/tests/test-persona-tokens.cpp b/tests/test-persona-tokens.cpp index 81ce0588da59..51c41b14dde8 100644 --- a/tests/test-persona-tokens.cpp +++ b/tests/test-persona-tokens.cpp @@ -16,8 +16,8 @@ using status = llama_persona_append_status; static llama_persona_request_id id(uint64_t n) { return { 1, n }; } -static llama_persona_append header(uint64_t persona, uint64_t epoch, uint64_t seq, uint64_t frontier, llama_persona_request_id request) { - llama_persona_append h; +static llama_persona_append_request header(uint64_t persona, uint64_t epoch, uint64_t seq, uint64_t frontier, llama_persona_request_id request) { + llama_persona_append_request h; h.persona = persona; h.epoch = epoch; h.seq = seq; From b004e38fabc06a4e3ac5a0c70c4fd8cdc6ded507 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 00:16:17 -0600 Subject: [PATCH 21/28] llama: her blocks move only under the owner of her token history; a second reserve and an allocation failure are statuses Codex on #147 at e046: persona/generation ownership. llama_persona_reserve_tokens replaced an existing history (dropping it) and could throw bad_alloc across the C boundary; her blocks carried sequence and layout but no owner, so blocks saved under one epoch could load under another. - reserve_tokens: already_reserved when her history exists (it would be dropped); out_of_memory on allocation failure, nothing changed. Both are llama_persona_move statuses. - save / load before a reserve: no_owner. - A completed save stamps her blocks with her owner (persona + epoch of her token history); a load of blocks stamped by another persona or epoch of her returns wrong_owner before any write. - llama_persona_owner reads the stamp (the flash tier writes it into its header next slice). test-persona-blocks, public seam only: no_owner before a reserve, already_reserved on a second reserve, the save stamped with exactly the reserved owner, and her next tokens byte-identical after an owned move into the other stream. wrong_owner is reachable only once blocks outlive their persona object (the flash tier); its check is in place and its fixture comes with that slice. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- include/llama.h | 7 ++++++ src/llama-context.cpp | 45 ++++++++++++++++++++++++++++++++--- src/llama-memory.cpp | 4 ++++ src/llama-persona-blocks.h | 9 +++++++ tests/test-persona-blocks.cpp | 21 ++++++++++++++++ 5 files changed, 83 insertions(+), 3 deletions(-) diff --git a/include/llama.h b/include/llama.h index 442f73241b21..62aff2a545b0 100644 --- a/include/llama.h +++ b/include/llama.h @@ -946,6 +946,13 @@ extern "C" { LLAMA_API const char * llama_persona_status_name(int32_t status); + // Her blocks move only under an owner: the persona and epoch her token history was reserved for. A save or load + // before llama_persona_reserve_tokens returns no_owner; a completed save stamps her blocks with the owner; a load + // of blocks stamped by another persona or another epoch of her returns wrong_owner before anything is written. + // Reserving twice returns already_reserved (it would drop her history); an allocation failure returns + // out_of_memory and changes nothing. llama_persona_owner reads the stamp (false before a completed save). + LLAMA_API bool llama_persona_owner(const struct llama_persona * persona, uint64_t * persona_id, uint64_t * epoch); + // Her token history, held in the persona beside her blocks (so it moves with them by reference, never copied): // one reserved buffer of her token ids and one of her append receipts. A request appends only its new ids, in // one validated transaction (see llama_persona_append). Reserved once by her admitted owner; 0 when done. diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 917c3aa932d1..f556e77c51e1 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -1,4 +1,6 @@ #include "llama-context.h" + +#include #include "llama-persona-tokens.h" #include "ggml.h" @@ -4246,9 +4248,18 @@ struct llama_persona { std::unique_ptr tokens; // her token history, beside her blocks (llama-persona-tokens.h) }; +// Her token history is reserved once and owns her blocks from then on: a second reserve would drop her history, so +// it is refused; an allocation failure is a status, never an exception across the C boundary, and changes nothing. int32_t llama_persona_reserve_tokens(llama_persona * persona, uint64_t persona_id, uint64_t epoch, size_t n_tokens, size_t n_receipts) { - persona->tokens = std::make_unique(persona_id, epoch, n_tokens, n_receipts); - return 0; + if (persona->tokens != nullptr) { + return (int32_t) llama_persona_move::already_reserved; + } + try { + persona->tokens = std::make_unique(persona_id, epoch, n_tokens, n_receipts); + } catch (const std::bad_alloc &) { + return (int32_t) llama_persona_move::out_of_memory; + } + return (int32_t) llama_persona_move::done; } llama_persona_append_receipt llama_persona_append(llama_persona * persona, const llama_persona_append_header * header, @@ -4298,14 +4309,42 @@ void llama_persona_free(llama_persona * persona) { delete persona; } +// Her blocks move only under an owner: the persona and epoch of her token history. A completed save stamps them +// with it; a load refuses blocks stamped by another persona or another epoch of her before anything is written. int32_t llama_persona_save(llama_context * ctx, llama_seq_id seq_id, llama_persona * persona) { - return (int32_t) ctx->persona_save(seq_id, persona->blocks); + if (persona->tokens == nullptr) { + return (int32_t) llama_persona_move::no_owner; + } + const llama_persona_move m = ctx->persona_save(seq_id, persona->blocks); + if (m == llama_persona_move::done) { + persona->blocks.owned = true; + persona->blocks.owner = persona->tokens->persona(); + persona->blocks.owner_epoch = persona->tokens->epoch(); + } + return (int32_t) m; } int32_t llama_persona_load(llama_context * ctx, llama_seq_id seq_id, uint32_t stream, llama_persona * persona) { + if (persona->tokens == nullptr) { + return (int32_t) llama_persona_move::no_owner; + } + const llama_persona_blocks & b = persona->blocks; + if (b.owned && (b.owner != persona->tokens->persona() || b.owner_epoch != persona->tokens->epoch())) { + return (int32_t) llama_persona_move::wrong_owner; + } return (int32_t) ctx->persona_load(seq_id, stream, persona->blocks); } +// Whose blocks these are, as stamped by the last completed save (false before any). +bool llama_persona_owner(const llama_persona * persona, uint64_t * persona_id, uint64_t * epoch) { + if (!persona->blocks.owned) { + return false; + } + *persona_id = persona->blocks.owner; + *epoch = persona->blocks.owner_epoch; + return true; +} + const char * llama_persona_status_name(int32_t status) { return llama_persona_move_name((llama_persona_move) status); } diff --git a/src/llama-memory.cpp b/src/llama-memory.cpp index 5f84200704dc..62786146a1db 100644 --- a/src/llama-memory.cpp +++ b/src/llama-memory.cpp @@ -73,6 +73,10 @@ const char * llama_persona_move_name(llama_persona_move m) { case llama_persona_move::no_free_cell: return "no_free_cell"; case llama_persona_move::wrong_persona: return "wrong_persona"; case llama_persona_move::invalid_rollback: return "invalid_rollback"; + case llama_persona_move::no_owner: return "no_owner"; + case llama_persona_move::wrong_owner: return "wrong_owner"; + case llama_persona_move::already_reserved: return "already_reserved"; + case llama_persona_move::out_of_memory: return "out_of_memory"; } return "unknown"; } diff --git a/src/llama-persona-blocks.h b/src/llama-persona-blocks.h index c278c59ebacc..376e5bc059e4 100644 --- a/src/llama-persona-blocks.h +++ b/src/llama-persona-blocks.h @@ -36,6 +36,11 @@ struct llama_rs_seq_blocks { // were prepared for (a fingerprint of layer count, stream size, row types and sizes, snapshot groups) struct llama_persona_blocks { llama_seq_id seq = -1; + // whose blocks these are: the owner of her token history when they were saved (persona + epoch), stamped by + // the public seam on a completed save and checked before any load; never retagged + bool owned = false; + uint64_t owner = 0; + uint64_t owner_epoch = 0; uint64_t kv_layout = 0; uint64_t rs_layout = 0; llama_kv_stream_blocks kv; @@ -64,6 +69,10 @@ enum class llama_persona_move { no_free_cell, // no free recurrent cell to load into wrong_persona, // her blocks belong to another sequence (her metadata is tagged with it; never retagged) invalid_rollback, // her rollback index exceeds this memory's snapshot groups + no_owner, // her token history is not reserved: blocks cannot be saved or loaded without an owner + wrong_owner, // her blocks were saved by another persona or another epoch of her + already_reserved, // her token history is already reserved: a second reserve would drop it + out_of_memory, // reserving her token history failed to allocate; nothing changed }; const char * llama_persona_move_name(llama_persona_move m); diff --git a/tests/test-persona-blocks.cpp b/tests/test-persona-blocks.cpp index 55012e0e3184..5aff7f7dd652 100644 --- a/tests/test-persona-blocks.cpp +++ b/tests/test-persona-blocks.cpp @@ -333,6 +333,27 @@ int main(int argc, char ** argv) { fprintf(stderr, "rollback groups exercised: n_rs_seq=%u, her rs_idx=%u\n", llama_n_rs_seq(f.ctx), r.rs.rs_idx); } + // the public seam's owner (Codex on #147 at e046): her blocks move only under the owner of her token history. + { + auto st = [](int32_t s) { return (llama_persona_move) s; }; + llama_memory_clear(llama_get_memory(f.ctx), true); + f.prompt(0, 1); + llama_persona * p = llama_persona_init(f.ctx); + require(p != nullptr, "a persona for this memory"); + uint64_t who = 0, when = 0; + require(!llama_persona_owner(p, &who, &when), "no owner before a completed save"); + require_move(st(llama_persona_save(f.ctx, 0, p)), llama_persona_move::no_owner, "save before her history is reserved"); + require_move(st(llama_persona_reserve_tokens(p, 0xA11CE, 7, 64, 8)), llama_persona_move::done, "reserve her history"); + require_move(st(llama_persona_reserve_tokens(p, 0xB0B, 7, 64, 8)), llama_persona_move::already_reserved, + "a second reserve would drop her history"); + require_move(st(llama_persona_save(f.ctx, 0, p)), llama_persona_move::done, "save under her owner"); + require(llama_persona_owner(p, &who, &when) && who == 0xA11CE && when == 7, "her blocks are stamped with her owner"); + const uint32_t other = 1 - llama_get_memory(f.ctx)->seq_stream(0); + require_move(st(llama_persona_load(f.ctx, 0, other, p)), llama_persona_move::done, "load under the same owner"); + f.require_continues("continues after an owned move through the public seam", 0, ref_a0); + llama_persona_free(p); + } + fprintf(stderr, "test-persona-blocks: ok (%zu attention layers, %zu recurrent layers)\n", a.kv.k.size(), a.rs.r.size()); return 0; } From 6078f439c4a6e9faedbda6de673ea20031671ccd Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 00:16:57 -0600 Subject: [PATCH 22/28] test-persona-tokens: zero allocations on the append path is measured, not stated (Codex on #147 at f3eb) Every allocation in the test binary is counted. At a real-size history (100k tokens, 2k deltas), after the one reserve: an accepted append, eight more, a refusal for no room, a wrong epoch, a stale frontier and a replay together allocate nothing (g_allocations unchanged). Her capacity and receipts are fixed at reserve; the hot path only writes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tests/test-persona-tokens.cpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/tests/test-persona-tokens.cpp b/tests/test-persona-tokens.cpp index 51c41b14dde8..2ae4c9fb593d 100644 --- a/tests/test-persona-tokens.cpp +++ b/tests/test-persona-tokens.cpp @@ -9,6 +9,20 @@ #include #include #include +#include +#include + +// Every allocation in this test binary is counted, so "an accepted append never allocates" is measured, not stated. +static std::atomic g_allocations { 0 }; +void * operator new(std::size_t n) { + g_allocations.fetch_add(1, std::memory_order_relaxed); + if (void * p = std::malloc(n ? n : 1)) { + return p; + } + throw std::bad_alloc(); +} +void operator delete(void * p) noexcept { std::free(p); } +void operator delete(void * p, std::size_t) noexcept { std::free(p); } #define CHECK(cond) do { if (!(cond)) { fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, #cond); exit(1); } } while (0) @@ -114,6 +128,27 @@ int main() { CHECK(her.frontier() == 2 && her.committed() == 2 && her.data()[0] == 1 && her.data()[1] == 2); CHECK(her.append(header(7, 1, 1, 0, id(1)), d, 2).status == status::replayed); } + // what this catches (Codex on #147 at f3eb: fixed-capacity evidence): any allocation on the append path. At her + // real size, after the one reserve, accepted, refused (no room, wrong epoch, stale frontier) and replayed + // appends together allocate nothing: her capacity and receipts are fixed at reserve and the hot path only writes. + { + llama_persona_tokens her(7, 1, 1 << 17, 64); + std::vector prompt(100000, 5); + std::vector delta(2048, 6); + std::vector too_much(1 << 17, 7); + const uint64_t before = g_allocations.load(); + CHECK(her.append(header(7, 1, 1, 0, id(1)), prompt.data(), prompt.size()).status == status::appended); + for (uint64_t i = 0; i < 8; i++) { + CHECK(her.append(header(7, 1, i + 2, her.frontier(), id(i + 2)), delta.data(), delta.size()).status == status::appended); + } + CHECK(her.append(header(7, 1, 10, her.frontier(), id(10)), too_much.data(), too_much.size()).status == status::no_room); + CHECK(her.append(header(7, 2, 10, her.frontier(), id(10)), delta.data(), delta.size()).status == status::wrong_epoch); + CHECK(her.append(header(7, 1, 10, 0, id(10)), delta.data(), delta.size()).status != status::appended); + CHECK(her.append(header(7, 1, 1, 0, id(1)), prompt.data(), prompt.size()).status == status::replayed); + CHECK(g_allocations.load() == before); + fprintf(stderr, "fixed capacity: %llu appends and refusals at a %llu-token history, 0 allocations\n", + (unsigned long long) 13, (unsigned long long) her.frontier()); + } // The cost of an act's append at her real size: a 100k-token history, a 2k-token delta. Printed, not // asserted; the writes are read back so the optimizer cannot remove them. { From bc9c9ae13adad70cb314999ce06cd08c89d56538 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 00:23:08 -0600 Subject: [PATCH 23/28] llama: llama_persona_bind places her in an empty stream the memory chooses; the caller never numbers streams The persona engine must not number streams (Joel: nothing is sized or numbered by the caller), but llama_persona_load took a stream index and the public API had no way to ask which was empty. - llama_memory_i::persona_empty_stream: the memory that owns the streams answers (KV cache: the first stream with no used cells, bounded by its stream count, no cell walk; hybrid: its attention cache; -1 when none is empty or the cache is unified). - llama_context::persona_bind and the C seam's llama_persona_bind: place her there, or no_empty_stream with nothing changed; otherwise exactly load's owner and layout checks (persona_owner_check is shared by load and bind). test-persona-blocks (public seam): the owned move binds into a stream the memory chose and her next tokens are byte-identical; with both streams occupied a bind returns no_empty_stream and both residents continue untouched. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- include/llama.h | 4 ++++ src/llama-context.cpp | 33 ++++++++++++++++++++++++++++++--- src/llama-context.h | 2 ++ src/llama-kv-cache.cpp | 12 ++++++++++++ src/llama-kv-cache.h | 1 + src/llama-memory-hybrid.h | 1 + src/llama-memory.cpp | 1 + src/llama-memory.h | 3 +++ src/llama-persona-blocks.h | 1 + tests/test-persona-blocks.cpp | 14 ++++++++++++-- 10 files changed, 67 insertions(+), 5 deletions(-) diff --git a/include/llama.h b/include/llama.h index 62aff2a545b0..6fa7a5426662 100644 --- a/include/llama.h +++ b/include/llama.h @@ -944,6 +944,10 @@ extern "C" { // Bind persona's blocks into the empty stream as sequence seq_id (the sequence they were saved from). 0 when done. LLAMA_API int32_t llama_persona_load(struct llama_context * ctx, llama_seq_id seq_id, uint32_t stream, struct llama_persona * persona); + // Bind her blocks as sequence seq_id into an empty stream the memory chooses: the caller never numbers streams. + // no_empty_stream when none is empty; otherwise exactly llama_persona_load's checks and statuses. + LLAMA_API int32_t llama_persona_bind(struct llama_context * ctx, llama_seq_id seq_id, struct llama_persona * persona); + LLAMA_API const char * llama_persona_status_name(int32_t status); // Her blocks move only under an owner: the persona and epoch her token history was reserved for. A save or load diff --git a/src/llama-context.cpp b/src/llama-context.cpp index f556e77c51e1..826f4de51c1b 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -2601,6 +2601,17 @@ llama_persona_move llama_context::persona_load(llama_seq_id seq_id, uint32_t str return llama_persona_move::done; } +llama_persona_move llama_context::persona_bind(llama_seq_id seq_id, llama_persona_blocks & in) { + if (!memory) { + return llama_persona_move::unsupported; + } + const int32_t stream = memory->persona_empty_stream(); + if (stream < 0) { + return llama_persona_move::no_empty_stream; + } + return persona_load(seq_id, (uint32_t) stream, in); +} + llm_graph_params llama_context::graph_params( llm_graph_result * res, const llama_ubatch & ubatch, @@ -4324,17 +4335,33 @@ int32_t llama_persona_save(llama_context * ctx, llama_seq_id seq_id, llama_perso return (int32_t) m; } -int32_t llama_persona_load(llama_context * ctx, llama_seq_id seq_id, uint32_t stream, llama_persona * persona) { +static llama_persona_move persona_owner_check(const llama_persona * persona) { if (persona->tokens == nullptr) { - return (int32_t) llama_persona_move::no_owner; + return llama_persona_move::no_owner; } const llama_persona_blocks & b = persona->blocks; if (b.owned && (b.owner != persona->tokens->persona() || b.owner_epoch != persona->tokens->epoch())) { - return (int32_t) llama_persona_move::wrong_owner; + return llama_persona_move::wrong_owner; + } + return llama_persona_move::done; +} + +int32_t llama_persona_load(llama_context * ctx, llama_seq_id seq_id, uint32_t stream, llama_persona * persona) { + const llama_persona_move owner = persona_owner_check(persona); + if (owner != llama_persona_move::done) { + return (int32_t) owner; } return (int32_t) ctx->persona_load(seq_id, stream, persona->blocks); } +int32_t llama_persona_bind(llama_context * ctx, llama_seq_id seq_id, llama_persona * persona) { + const llama_persona_move owner = persona_owner_check(persona); + if (owner != llama_persona_move::done) { + return (int32_t) owner; + } + return (int32_t) ctx->persona_bind(seq_id, persona->blocks); +} + // Whose blocks these are, as stamped by the last completed save (false before any). bool llama_persona_owner(const llama_persona * persona, uint64_t * persona_id, uint64_t * epoch) { if (!persona->blocks.owned) { diff --git a/src/llama-context.h b/src/llama-context.h index 30e7393c6e81..e705509f2202 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -64,6 +64,8 @@ struct llama_context { llama_persona_move persona_prepare(llama_persona_blocks & blocks) const; llama_persona_move persona_save(llama_seq_id seq_id, llama_persona_blocks & out); llama_persona_move persona_load(llama_seq_id seq_id, uint32_t stream, llama_persona_blocks & in); + // load her into an empty stream the memory chooses (no_empty_stream when none is) + llama_persona_move persona_bind(llama_seq_id seq_id, llama_persona_blocks & in); bool opt_state_write_initial(FILE * optimizer, const char * binding); bool opt_state_write(FILE * optimizer, const char * binding); bool opt_shadow_state_write(const llama_adapter_lora * shadow, FILE * optimizer, const char * binding); diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index 720ef3365a3a..8b9ac5ad2cbf 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -1327,6 +1327,18 @@ void llama_kv_cache::persona_commit_save(llama_seq_id seq_id, llama_persona_bloc v_heads[s] = 0; } +int32_t llama_kv_cache::persona_empty_stream() const { + if (n_stream == 1) { + return -1; // unified: one stream holds every sequence, so there is nothing empty to bind into + } + for (uint32_t s = 0; s < n_stream; ++s) { + if (v_cells[s].get_used() == 0) { + return (int32_t) s; + } + } + return -1; +} + llama_persona_move llama_kv_cache::persona_check_load(llama_seq_id seq_id, uint32_t stream, const llama_persona_blocks & in, llama_persona_slot & slot) const { if (n_stream == 1 || stream >= n_stream) { diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h index 3a0272f2f5da..6e85ed9c25be 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -180,6 +180,7 @@ class llama_kv_cache : public llama_memory_i { // (seq_to_stream stays a permutation; her cells are never retagged). Requires unified KV off and flash attention. llama_persona_move persona_prepare(llama_persona_blocks & blocks) const override; uint64_t persona_layout() const { return persona_layout_id; } + int32_t persona_empty_stream() const override; llama_persona_move persona_check_save(llama_seq_id seq_id, llama_persona_blocks & out) const override; llama_persona_move persona_check_load(llama_seq_id seq_id, uint32_t stream, const llama_persona_blocks & in, llama_persona_slot & slot) const override; diff --git a/src/llama-memory-hybrid.h b/src/llama-memory-hybrid.h index e30f48cefc05..8715212f1d78 100644 --- a/src/llama-memory-hybrid.h +++ b/src/llama-memory-hybrid.h @@ -90,6 +90,7 @@ class llama_memory_hybrid : public llama_memory_i { // her whole state: both halves are checked (and the destination reserved) before either commits llama_persona_move persona_prepare(llama_persona_blocks & blocks) const override; llama_persona_move persona_check_save(llama_seq_id seq_id, llama_persona_blocks & out) const override; + int32_t persona_empty_stream() const override { return mem_attn->persona_empty_stream(); } llama_persona_move persona_check_load(llama_seq_id seq_id, uint32_t stream, const llama_persona_blocks & in, llama_persona_slot & slot) const override; void persona_commit_save(llama_seq_id seq_id, llama_persona_blocks & out) override; diff --git a/src/llama-memory.cpp b/src/llama-memory.cpp index 62786146a1db..798eac3a47dc 100644 --- a/src/llama-memory.cpp +++ b/src/llama-memory.cpp @@ -77,6 +77,7 @@ const char * llama_persona_move_name(llama_persona_move m) { case llama_persona_move::wrong_owner: return "wrong_owner"; case llama_persona_move::already_reserved: return "already_reserved"; case llama_persona_move::out_of_memory: return "out_of_memory"; + case llama_persona_move::no_empty_stream: return "no_empty_stream"; } return "unknown"; } diff --git a/src/llama-memory.h b/src/llama-memory.h index 4a49526d3ab8..5fa23b155c92 100644 --- a/src/llama-memory.h +++ b/src/llama-memory.h @@ -170,6 +170,9 @@ struct llama_memory_i { (void) seq_id; (void) stream; (void) in; (void) slot; return llama_persona_move::unsupported; } + // An empty stream for a load to place her in, chosen by the memory that owns the streams (the caller never numbers + // them); -1 when none is empty or the memory has no streams to move into. + virtual int32_t persona_empty_stream() const { return -1; } virtual void persona_commit_save(llama_seq_id seq_id, llama_persona_blocks & out) { (void) seq_id; (void) out; } virtual void persona_commit_load(llama_seq_id seq_id, llama_persona_slot & slot, llama_persona_blocks & in) { (void) seq_id; (void) slot; (void) in; diff --git a/src/llama-persona-blocks.h b/src/llama-persona-blocks.h index 376e5bc059e4..5c99b2eddf5f 100644 --- a/src/llama-persona-blocks.h +++ b/src/llama-persona-blocks.h @@ -73,6 +73,7 @@ enum class llama_persona_move { wrong_owner, // her blocks were saved by another persona or another epoch of her already_reserved, // her token history is already reserved: a second reserve would drop it out_of_memory, // reserving her token history failed to allocate; nothing changed + no_empty_stream, // a bind found no empty stream to place her in }; const char * llama_persona_move_name(llama_persona_move m); diff --git a/tests/test-persona-blocks.cpp b/tests/test-persona-blocks.cpp index 5aff7f7dd652..a75ccc9b11ad 100644 --- a/tests/test-persona-blocks.cpp +++ b/tests/test-persona-blocks.cpp @@ -348,9 +348,19 @@ int main(int argc, char ** argv) { "a second reserve would drop her history"); require_move(st(llama_persona_save(f.ctx, 0, p)), llama_persona_move::done, "save under her owner"); require(llama_persona_owner(p, &who, &when) && who == 0xA11CE && when == 7, "her blocks are stamped with her owner"); - const uint32_t other = 1 - llama_get_memory(f.ctx)->seq_stream(0); - require_move(st(llama_persona_load(f.ctx, 0, other, p)), llama_persona_move::done, "load under the same owner"); + require_move(st(llama_persona_bind(f.ctx, 0, p)), llama_persona_move::done, "bound into a stream the memory chose"); f.require_continues("continues after an owned move through the public seam", 0, ref_a0); + + // every stream occupied: a bind places nobody and changes nothing + llama_persona * q = llama_persona_init(f.ctx); + require(q != nullptr, "a second persona"); + require_move(st(llama_persona_reserve_tokens(q, 0xB0B, 1, 64, 8)), llama_persona_move::done, "reserve q"); + llama_memory_clear(llama_get_memory(f.ctx), true); + f.prompt(0, 1); + f.prompt(1, 2); + require_move(st(llama_persona_bind(f.ctx, 1, q)), llama_persona_move::no_empty_stream, "no empty stream to bind into"); + f.require_continues("both residents untouched by the refused bind", 0, ref_a0); + llama_persona_free(q); llama_persona_free(p); } From 53609c55678992557537dbe724481ded84fddbb5 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 00:35:15 -0600 Subject: [PATCH 24/28] llama: her token history is sized by nothing at creation; her owner grows it ahead of need Joel: nothing sized at creation, it's dynamic. llama_persona_reserve_tokens took a fixed capacity (n_tokens, n_receipts) and the tokens class held that size for life. - llama_persona_tokens(persona, epoch) starts empty; grow(more_tokens, more_receipts) adds room keeping everything she holds (nothrow; false on allocation failure, unchanged). - C seam: llama_persona_reserve_tokens(persona, id, epoch) names only her owner; llama_persona_grow_tokens(persona, more_tokens, more_receipts) is called by her owner between acts (no_owner before a reserve, out_of_memory on failure). An append on the hot path still only writes: it returns no_room when her owner did not grow her in time. - Tests: every history starts unsized and is grown; a new case shows an append refused for room, her owner grows her, the same request lands with her history kept and her earlier commit replayable; the zero-allocation measurement now follows growth ahead. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- include/llama.h | 12 ++++++--- src/llama-context.cpp | 12 +++++++-- src/llama-persona-tokens.h | 37 ++++++++++++++++++++++----- tests/test-persona-blocks.cpp | 7 ++--- tests/test-persona-tokens.cpp | 48 ++++++++++++++++++++++++++--------- 5 files changed, 88 insertions(+), 28 deletions(-) diff --git a/include/llama.h b/include/llama.h index 6fa7a5426662..0bc4659a95fe 100644 --- a/include/llama.h +++ b/include/llama.h @@ -958,10 +958,14 @@ extern "C" { LLAMA_API bool llama_persona_owner(const struct llama_persona * persona, uint64_t * persona_id, uint64_t * epoch); // Her token history, held in the persona beside her blocks (so it moves with them by reference, never copied): - // one reserved buffer of her token ids and one of her append receipts. A request appends only its new ids, in - // one validated transaction (see llama_persona_append). Reserved once by her admitted owner; 0 when done. - LLAMA_API int32_t llama_persona_reserve_tokens(struct llama_persona * persona, uint64_t persona_id, uint64_t epoch, - size_t n_tokens, size_t n_receipts); + // one buffer of her token ids and one of her append receipts, grown by her owner. A request appends only its new ids, in + // one validated transaction (see llama_persona_append). Owned once by her admitted owner; 0 when done. + LLAMA_API int32_t llama_persona_reserve_tokens(struct llama_persona * persona, uint64_t persona_id, uint64_t epoch); + + // Grow her history by more_tokens ids and more_receipts appends, keeping what she holds. Her owner calls it ahead + // of need, between acts, never inside one: sized by nothing at creation. no_owner before a reserve; out_of_memory + // on allocation failure, with her history unchanged. + LLAMA_API int32_t llama_persona_grow_tokens(struct llama_persona * persona, size_t more_tokens, size_t more_receipts); // What an append asserts about her history: her persona, her epoch, her request sequence (1, 2, 3, ...), the // frontier it expects her history to end at, and the request's own 128-bit identity. diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 826f4de51c1b..7e657175fb44 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -4261,18 +4261,26 @@ struct llama_persona { // Her token history is reserved once and owns her blocks from then on: a second reserve would drop her history, so // it is refused; an allocation failure is a status, never an exception across the C boundary, and changes nothing. -int32_t llama_persona_reserve_tokens(llama_persona * persona, uint64_t persona_id, uint64_t epoch, size_t n_tokens, size_t n_receipts) { +int32_t llama_persona_reserve_tokens(llama_persona * persona, uint64_t persona_id, uint64_t epoch) { if (persona->tokens != nullptr) { return (int32_t) llama_persona_move::already_reserved; } try { - persona->tokens = std::make_unique(persona_id, epoch, n_tokens, n_receipts); + persona->tokens = std::make_unique(persona_id, epoch); } catch (const std::bad_alloc &) { return (int32_t) llama_persona_move::out_of_memory; } return (int32_t) llama_persona_move::done; } +// Her owner grows her history ahead of need, between acts: an append on the hot path only writes into it. +int32_t llama_persona_grow_tokens(llama_persona * persona, size_t more_tokens, size_t more_receipts) { + if (persona->tokens == nullptr) { + return (int32_t) llama_persona_move::no_owner; + } + return (int32_t) (persona->tokens->grow(more_tokens, more_receipts) ? llama_persona_move::done : llama_persona_move::out_of_memory); +} + llama_persona_append_receipt llama_persona_append(llama_persona * persona, const llama_persona_append_header * header, const llama_token * delta, size_t n) { llama_persona_append_receipt out = { (int32_t) llama_persona_append_status::invalid, 0, 0, 0 }; diff --git a/src/llama-persona-tokens.h b/src/llama-persona-tokens.h index b8a280332407..41cb73544a12 100644 --- a/src/llama-persona-tokens.h +++ b/src/llama-persona-tokens.h @@ -5,6 +5,7 @@ #include #include #include +#include #include // A persona's token history: one contiguous, reserved buffer of her token ids, owned with her blocks @@ -75,11 +76,33 @@ struct llama_persona_receipt { class llama_persona_tokens { public: - // Both arrays are reserved here, by her admitted owner: an accepted append writes into them and never - // allocates (`capacity` token ids, `receipts` committed appends, one per request sequence). - llama_persona_tokens(uint64_t persona, uint64_t epoch, size_t capacity, size_t receipts) - : persona_(persona), epoch_(epoch), capacity_(capacity), ids_(new llama_token[capacity]), - receipt_capacity_(receipts), committed_(new commit_record[receipts]) {} + // Her history is owned from the start and sized by nothing: it begins empty and her owner grows it ahead of + // need, off the hot path (grow). An accepted append only writes into what has been grown; it never allocates. + llama_persona_tokens(uint64_t persona, uint64_t epoch) : persona_(persona), epoch_(epoch) {} + + // Add room for `more_tokens` ids and `more_receipts` appends, keeping everything she holds. Called by her owner + // between acts, never inside one. False on allocation failure, with her history unchanged. + bool grow(size_t more_tokens, size_t more_receipts) { + if (more_tokens > SIZE_MAX - capacity_ || more_receipts > SIZE_MAX - receipt_capacity_) { + return false; + } + std::unique_ptr ids(new (std::nothrow) llama_token[capacity_ + more_tokens]); + std::unique_ptr committed(new (std::nothrow) commit_record[receipt_capacity_ + more_receipts]); + if (!ids || !committed) { + return false; + } + if (n_ > 0) { + std::memcpy(ids.get(), ids_.get(), n_ * sizeof(llama_token)); + } + for (uint64_t i = 0; i < n_committed_; ++i) { + committed[i] = committed_[i]; + } + ids_.swap(ids); + committed_.swap(committed); + capacity_ += more_tokens; + receipt_capacity_ += more_receipts; + return true; + } uint64_t persona() const { return persona_; } uint64_t epoch() const { return epoch_; } @@ -160,10 +183,10 @@ class llama_persona_tokens { uint64_t persona_; uint64_t epoch_; - size_t capacity_; + size_t capacity_ = 0; std::unique_ptr ids_; uint64_t n_ = 0; - size_t receipt_capacity_; + size_t receipt_capacity_ = 0; std::unique_ptr committed_; uint64_t n_committed_ = 0; }; diff --git a/tests/test-persona-blocks.cpp b/tests/test-persona-blocks.cpp index a75ccc9b11ad..257924f3445a 100644 --- a/tests/test-persona-blocks.cpp +++ b/tests/test-persona-blocks.cpp @@ -343,8 +343,9 @@ int main(int argc, char ** argv) { uint64_t who = 0, when = 0; require(!llama_persona_owner(p, &who, &when), "no owner before a completed save"); require_move(st(llama_persona_save(f.ctx, 0, p)), llama_persona_move::no_owner, "save before her history is reserved"); - require_move(st(llama_persona_reserve_tokens(p, 0xA11CE, 7, 64, 8)), llama_persona_move::done, "reserve her history"); - require_move(st(llama_persona_reserve_tokens(p, 0xB0B, 7, 64, 8)), llama_persona_move::already_reserved, + require_move(st(llama_persona_reserve_tokens(p, 0xA11CE, 7)), llama_persona_move::done, "reserve her history"); + require_move(st(llama_persona_grow_tokens(p, 64, 8)), llama_persona_move::done, "her owner grows her history ahead"); + require_move(st(llama_persona_reserve_tokens(p, 0xB0B, 7)), llama_persona_move::already_reserved, "a second reserve would drop her history"); require_move(st(llama_persona_save(f.ctx, 0, p)), llama_persona_move::done, "save under her owner"); require(llama_persona_owner(p, &who, &when) && who == 0xA11CE && when == 7, "her blocks are stamped with her owner"); @@ -354,7 +355,7 @@ int main(int argc, char ** argv) { // every stream occupied: a bind places nobody and changes nothing llama_persona * q = llama_persona_init(f.ctx); require(q != nullptr, "a second persona"); - require_move(st(llama_persona_reserve_tokens(q, 0xB0B, 1, 64, 8)), llama_persona_move::done, "reserve q"); + require_move(st(llama_persona_reserve_tokens(q, 0xB0B, 1)), llama_persona_move::done, "reserve q"); llama_memory_clear(llama_get_memory(f.ctx), true); f.prompt(0, 1); f.prompt(1, 2); diff --git a/tests/test-persona-tokens.cpp b/tests/test-persona-tokens.cpp index 2ae4c9fb593d..f24772def695 100644 --- a/tests/test-persona-tokens.cpp +++ b/tests/test-persona-tokens.cpp @@ -44,7 +44,8 @@ int main() { // what this catches: her history rebuilt per act. Three acts: each request appends only its new ids // after what she generated; her history is exactly served + generated + new, in order. { - llama_persona_tokens her(7, 1, 64, 16); + llama_persona_tokens her(7, 1); + CHECK(her.grow(64, 16)); const llama_token prompt[] = { 1, 40, 9, 2, 7 }; CHECK(her.append(header(7, 1, 1, 0, id(1)), prompt, 5).status == status::appended); std::vector expect(prompt, prompt + 5); @@ -65,7 +66,8 @@ int main() { // A then B commit; a delayed retry of A (after B) gets A's original receipt and writes nothing; so does a // duplicate of B; A's sequence with another request or delta is refused. { - llama_persona_tokens her(7, 1, 16, 16); + llama_persona_tokens her(7, 1); + CHECK(her.grow(16, 16)); const llama_token a[] = { 1, 2, 3 }, b[] = { 4, 5 }, other[] = { 1, 2, 4 }; const auto ra = her.append(header(7, 1, 1, 0, id(1)), a, 3); const auto rb = her.append(header(7, 1, 2, 3, id(2)), b, 2); @@ -80,7 +82,8 @@ int main() { // what this catches: empty appends at the same frontier letting a retried request be accepted twice. // Each empty append commits its own sequence; a retry of the first is its receipt, never a new append. { - llama_persona_tokens her(7, 1, 16, 16); + llama_persona_tokens her(7, 1); + CHECK(her.grow(16, 16)); CHECK(her.append(header(7, 1, 1, 0, id(1)), nullptr, 0).status == status::appended); CHECK(her.append(header(7, 1, 2, 0, id(2)), nullptr, 0).status == status::appended); CHECK(her.append(header(7, 1, 1, 0, id(1)), nullptr, 0).status == status::replayed); @@ -88,7 +91,8 @@ int main() { } // what this catches: a reordered request (a later sequence arriving first) appended out of order. { - llama_persona_tokens her(7, 1, 16, 16); + llama_persona_tokens her(7, 1); + CHECK(her.grow(16, 16)); const llama_token d[] = { 1 }; CHECK(her.append(header(7, 1, 2, 0, id(2)), d, 1).status == status::out_of_order); CHECK(her.append(header(7, 1, 1, 0, id(1)), d, 1).status == status::appended); @@ -97,7 +101,8 @@ int main() { } // what this catches: a stale, foreign or malformed request appended to her history. { - llama_persona_tokens her(7, 2, 16, 16); + llama_persona_tokens her(7, 2); + CHECK(her.grow(16, 16)); const llama_token d[] = { 1 }; CHECK(her.append(header(8, 2, 1, 0, id(1)), d, 1).status == status::wrong_persona); CHECK(her.append(header(7, 1, 1, 0, id(1)), d, 1).status == status::wrong_epoch); @@ -110,16 +115,33 @@ int main() { // what this catches: an append past her reserved capacity growing it in place (an allocation and a copy // of what she holds on the hot path): refused, her owner grows first; a length that would overflow too. { - llama_persona_tokens her(7, 1, 4, 16); + llama_persona_tokens her(7, 1); + CHECK(her.grow(4, 16)); const llama_token d[] = { 1, 2, 3, 4, 5 }; CHECK(her.append(header(7, 1, 1, 0, id(1)), d, 5).status == status::no_room && her.frontier() == 0); CHECK(her.append(header(7, 1, 1, 0, id(1)), d, SIZE_MAX).status == status::no_room); } + // what this catches (Joel: nothing sized at creation): a history that cannot grow. Out of room, the append is + // refused and writes nothing; her owner grows her (between acts) and the same request lands, with everything + // she held kept and her earlier commit still replayable. + { + llama_persona_tokens her(7, 1); + const llama_token d[] = { 1, 2, 3, 4, 5 }; + CHECK(her.append(header(7, 1, 1, 0, id(1)), d, 2).status == status::no_room && her.frontier() == 0); + CHECK(her.grow(2, 1)); + CHECK(her.append(header(7, 1, 1, 0, id(1)), d, 2).status == status::appended); + CHECK(her.append(header(7, 1, 2, 2, id(2)), d + 2, 3).status == status::no_room && her.frontier() == 2); + CHECK(her.grow(3, 1)); + CHECK(her.append(header(7, 1, 2, 2, id(2)), d + 2, 3).status == status::appended && her.frontier() == 5); + CHECK(her.data()[0] == 1 && her.data()[4] == 5); + CHECK(her.append(header(7, 1, 1, 0, id(1)), d, 2).status == status::replayed); + } // what this catches: an accepted append allocating its receipt on the hot path, or a refused one leaving // a half-written append. Receipts are reserved; when they are used up the append is refused before any // write, an empty append included, and her tokens, frontier and commits are unchanged. { - llama_persona_tokens her(7, 1, 16, 2); + llama_persona_tokens her(7, 1); + CHECK(her.grow(16, 2)); const llama_token d[] = { 1, 2 }; CHECK(her.append(header(7, 1, 1, 0, id(1)), d, 2).status == status::appended); CHECK(her.append(header(7, 1, 2, 2, id(2)), nullptr, 0).status == status::appended); @@ -128,11 +150,12 @@ int main() { CHECK(her.frontier() == 2 && her.committed() == 2 && her.data()[0] == 1 && her.data()[1] == 2); CHECK(her.append(header(7, 1, 1, 0, id(1)), d, 2).status == status::replayed); } - // what this catches (Codex on #147 at f3eb: fixed-capacity evidence): any allocation on the append path. At her - // real size, after the one reserve, accepted, refused (no room, wrong epoch, stale frontier) and replayed + // what this catches (Codex on #147 at f3eb): any allocation on the append path. At her + // real size, after her owner grew her history ahead, accepted, refused (no room, wrong epoch, stale frontier) and replayed // appends together allocate nothing: her capacity and receipts are fixed at reserve and the hot path only writes. { - llama_persona_tokens her(7, 1, 1 << 17, 64); + llama_persona_tokens her(7, 1); + CHECK(her.grow(1 << 17, 64)); std::vector prompt(100000, 5); std::vector delta(2048, 6); std::vector too_much(1 << 17, 7); @@ -146,13 +169,14 @@ int main() { CHECK(her.append(header(7, 1, 10, 0, id(10)), delta.data(), delta.size()).status != status::appended); CHECK(her.append(header(7, 1, 1, 0, id(1)), prompt.data(), prompt.size()).status == status::replayed); CHECK(g_allocations.load() == before); - fprintf(stderr, "fixed capacity: %llu appends and refusals at a %llu-token history, 0 allocations\n", + fprintf(stderr, "grown ahead: %llu appends and refusals at a %llu-token history, 0 allocations\n", (unsigned long long) 13, (unsigned long long) her.frontier()); } // The cost of an act's append at her real size: a 100k-token history, a 2k-token delta. Printed, not // asserted; the writes are read back so the optimizer cannot remove them. { - llama_persona_tokens her(7, 1, 1 << 20, 128); + llama_persona_tokens her(7, 1); + CHECK(her.grow(1 << 20, 128)); std::vector prompt(100000, 5); CHECK(her.append(header(7, 1, 1, 0, id(1)), prompt.data(), prompt.size()).status == status::appended); std::vector delta(2048, 6); From 8f558c48559f8ecfe43f88c637d33c992aa3dd24 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 00:37:18 -0600 Subject: [PATCH 25/28] llama: no reserve; a persona is made with her owner and her history grows and shrinks with her Joel: "we don't reserve, we literally do the opposite: we grow and shrink, we switch contexts." - llama_persona_init(ctx, persona_id, epoch) makes her owned from the start; reserve_tokens is gone, with the no_owner and already_reserved statuses and their checks (unreachable now). - llama_persona_grow_tokens adds room ahead of need; llama_persona_shrink_tokens gives back the room she does not hold as she cools, dropping nothing. Both between acts, never inside one. - Header and class docs say grown, not reserved. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- include/llama.h | 25 ++++++++++---------- src/llama-context.cpp | 44 +++++++++++------------------------ src/llama-memory.cpp | 2 -- src/llama-persona-blocks.h | 4 +--- src/llama-persona-tokens.h | 32 +++++++++++++++++++++---- tests/test-persona-blocks.cpp | 16 +++++-------- 6 files changed, 59 insertions(+), 64 deletions(-) diff --git a/include/llama.h b/include/llama.h index 0bc4659a95fe..11c03a6ae0a7 100644 --- a/include/llama.h +++ b/include/llama.h @@ -933,8 +933,10 @@ extern "C" { // stream; the memory must hold one stream per sequence (not unified) with V not transposed (flash attention on). struct llama_persona; - // Blocks prepared once for this context's memory (sized to a stream), empty. NULL when the memory has no persona move. - LLAMA_API struct llama_persona * llama_persona_init(struct llama_context * ctx); + // One persona: her blocks prepared for this context's memory and her token history, owned by persona_id at epoch + // from the start (nothing is reserved or sized here; her history grows and shrinks with her). NULL when the memory + // has no persona move. + LLAMA_API struct llama_persona * llama_persona_init(struct llama_context * ctx, uint64_t persona_id, uint64_t epoch); LLAMA_API void llama_persona_free(struct llama_persona * persona); // Move sequence seq_id's state out of the memory into persona's blocks; her stream is left empty. Two-phase: a @@ -950,22 +952,19 @@ extern "C" { LLAMA_API const char * llama_persona_status_name(int32_t status); - // Her blocks move only under an owner: the persona and epoch her token history was reserved for. A save or load - // before llama_persona_reserve_tokens returns no_owner; a completed save stamps her blocks with the owner; a load - // of blocks stamped by another persona or another epoch of her returns wrong_owner before anything is written. - // Reserving twice returns already_reserved (it would drop her history); an allocation failure returns - // out_of_memory and changes nothing. llama_persona_owner reads the stamp (false before a completed save). + // Her blocks move only under her owner (the persona and epoch she was made for): a completed save stamps them; a + // load of blocks stamped by another persona or another epoch of her returns wrong_owner before anything is + // written. llama_persona_owner reads the stamp (false before a completed save). LLAMA_API bool llama_persona_owner(const struct llama_persona * persona, uint64_t * persona_id, uint64_t * epoch); // Her token history, held in the persona beside her blocks (so it moves with them by reference, never copied): // one buffer of her token ids and one of her append receipts, grown by her owner. A request appends only its new ids, in // one validated transaction (see llama_persona_append). Owned once by her admitted owner; 0 when done. - LLAMA_API int32_t llama_persona_reserve_tokens(struct llama_persona * persona, uint64_t persona_id, uint64_t epoch); - - // Grow her history by more_tokens ids and more_receipts appends, keeping what she holds. Her owner calls it ahead - // of need, between acts, never inside one: sized by nothing at creation. no_owner before a reserve; out_of_memory - // on allocation failure, with her history unchanged. + // Her history grows and shrinks with her, never inside an act: grow adds room for more_tokens ids and more_receipts + // appends ahead of need; shrink gives back the room she does not hold as she cools. Neither drops anything she + // holds; out_of_memory on allocation failure, with her history unchanged. LLAMA_API int32_t llama_persona_grow_tokens(struct llama_persona * persona, size_t more_tokens, size_t more_receipts); + LLAMA_API int32_t llama_persona_shrink_tokens(struct llama_persona * persona); // What an append asserts about her history: her persona, her epoch, her request sequence (1, 2, 3, ...), the // frontier it expects her history to end at, and the request's own 128-bit identity. @@ -991,7 +990,7 @@ extern "C" { const struct llama_persona_append_header * header, const llama_token * delta, size_t n); - // Her history as held: the ids and their count (her frontier). NULL before llama_persona_reserve_tokens. + // Her history as held: the ids and their count (her frontier). Empty until her first append. LLAMA_API const llama_token * llama_persona_token_ids(const struct llama_persona * persona, uint64_t * n); LLAMA_API const char * llama_persona_append_status_name(int32_t status); diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 7e657175fb44..fecb740129c8 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -4259,32 +4259,20 @@ struct llama_persona { std::unique_ptr tokens; // her token history, beside her blocks (llama-persona-tokens.h) }; -// Her token history is reserved once and owns her blocks from then on: a second reserve would drop her history, so -// it is refused; an allocation failure is a status, never an exception across the C boundary, and changes nothing. -int32_t llama_persona_reserve_tokens(llama_persona * persona, uint64_t persona_id, uint64_t epoch) { - if (persona->tokens != nullptr) { - return (int32_t) llama_persona_move::already_reserved; - } - try { - persona->tokens = std::make_unique(persona_id, epoch); - } catch (const std::bad_alloc &) { - return (int32_t) llama_persona_move::out_of_memory; - } - return (int32_t) llama_persona_move::done; -} - // Her owner grows her history ahead of need, between acts: an append on the hot path only writes into it. int32_t llama_persona_grow_tokens(llama_persona * persona, size_t more_tokens, size_t more_receipts) { - if (persona->tokens == nullptr) { - return (int32_t) llama_persona_move::no_owner; - } return (int32_t) (persona->tokens->grow(more_tokens, more_receipts) ? llama_persona_move::done : llama_persona_move::out_of_memory); } +// As she cools her owner gives back the room she does not hold; nothing she holds is dropped. +int32_t llama_persona_shrink_tokens(llama_persona * persona) { + return (int32_t) (persona->tokens->shrink() ? llama_persona_move::done : llama_persona_move::out_of_memory); +} + llama_persona_append_receipt llama_persona_append(llama_persona * persona, const llama_persona_append_header * header, const llama_token * delta, size_t n) { llama_persona_append_receipt out = { (int32_t) llama_persona_append_status::invalid, 0, 0, 0 }; - if (persona->tokens == nullptr || header == nullptr) { + if (header == nullptr) { return out; } llama_persona_append_request h; @@ -4303,10 +4291,6 @@ llama_persona_append_receipt llama_persona_append(llama_persona * persona, const } const llama_token * llama_persona_token_ids(const llama_persona * persona, uint64_t * n) { - if (persona->tokens == nullptr) { - *n = 0; - return nullptr; - } *n = persona->tokens->frontier(); return persona->tokens->data(); } @@ -4315,9 +4299,13 @@ const char * llama_persona_append_status_name(int32_t status) { return llama_persona_append_status_name((llama_persona_append_status) status); } -llama_persona * llama_persona_init(llama_context * ctx) { - auto * persona = new llama_persona(); - if (ctx->persona_prepare(persona->blocks) != llama_persona_move::done) { +llama_persona * llama_persona_init(llama_context * ctx, uint64_t persona_id, uint64_t epoch) { + auto * persona = new (std::nothrow) llama_persona(); + if (persona == nullptr) { + return nullptr; + } + persona->tokens.reset(new (std::nothrow) llama_persona_tokens(persona_id, epoch)); + if (persona->tokens == nullptr || ctx->persona_prepare(persona->blocks) != llama_persona_move::done) { delete persona; return nullptr; } @@ -4331,9 +4319,6 @@ void llama_persona_free(llama_persona * persona) { // Her blocks move only under an owner: the persona and epoch of her token history. A completed save stamps them // with it; a load refuses blocks stamped by another persona or another epoch of her before anything is written. int32_t llama_persona_save(llama_context * ctx, llama_seq_id seq_id, llama_persona * persona) { - if (persona->tokens == nullptr) { - return (int32_t) llama_persona_move::no_owner; - } const llama_persona_move m = ctx->persona_save(seq_id, persona->blocks); if (m == llama_persona_move::done) { persona->blocks.owned = true; @@ -4344,9 +4329,6 @@ int32_t llama_persona_save(llama_context * ctx, llama_seq_id seq_id, llama_perso } static llama_persona_move persona_owner_check(const llama_persona * persona) { - if (persona->tokens == nullptr) { - return llama_persona_move::no_owner; - } const llama_persona_blocks & b = persona->blocks; if (b.owned && (b.owner != persona->tokens->persona() || b.owner_epoch != persona->tokens->epoch())) { return llama_persona_move::wrong_owner; diff --git a/src/llama-memory.cpp b/src/llama-memory.cpp index 798eac3a47dc..646fb357bed0 100644 --- a/src/llama-memory.cpp +++ b/src/llama-memory.cpp @@ -73,9 +73,7 @@ const char * llama_persona_move_name(llama_persona_move m) { case llama_persona_move::no_free_cell: return "no_free_cell"; case llama_persona_move::wrong_persona: return "wrong_persona"; case llama_persona_move::invalid_rollback: return "invalid_rollback"; - case llama_persona_move::no_owner: return "no_owner"; case llama_persona_move::wrong_owner: return "wrong_owner"; - case llama_persona_move::already_reserved: return "already_reserved"; case llama_persona_move::out_of_memory: return "out_of_memory"; case llama_persona_move::no_empty_stream: return "no_empty_stream"; } diff --git a/src/llama-persona-blocks.h b/src/llama-persona-blocks.h index 5c99b2eddf5f..2e4e841d4600 100644 --- a/src/llama-persona-blocks.h +++ b/src/llama-persona-blocks.h @@ -69,10 +69,8 @@ enum class llama_persona_move { no_free_cell, // no free recurrent cell to load into wrong_persona, // her blocks belong to another sequence (her metadata is tagged with it; never retagged) invalid_rollback, // her rollback index exceeds this memory's snapshot groups - no_owner, // her token history is not reserved: blocks cannot be saved or loaded without an owner wrong_owner, // her blocks were saved by another persona or another epoch of her - already_reserved, // her token history is already reserved: a second reserve would drop it - out_of_memory, // reserving her token history failed to allocate; nothing changed + out_of_memory, // growing or shrinking her token history failed to allocate; nothing changed no_empty_stream, // a bind found no empty stream to place her in }; diff --git a/src/llama-persona-tokens.h b/src/llama-persona-tokens.h index 41cb73544a12..9039df4bd2dc 100644 --- a/src/llama-persona-tokens.h +++ b/src/llama-persona-tokens.h @@ -8,14 +8,14 @@ #include #include -// A persona's token history: one contiguous, reserved buffer of her token ids, owned with her blocks +// A persona's token history: one contiguous buffer of her token ids, grown and shrunk by her owner, owned with her blocks // (CONTINUUM-ENGINE 4.14, "the persona is one contiguous structure; a request appends token ids"). // // Her tokens are what her blocks hold, in order: what she was served and what she generated, exactly. // A request never re-sends them; it appends only its new ids, in one validated transaction: // - its header names her persona, her epoch, her request sequence (1, 2, 3, ... minted by her one // caller), the frontier it expects her history to end at, and the request's own 128-bit identity; -// - the owner validates all of it, then writes the delta into capacity already reserved: never an +// - the owner validates all of it, then writes the delta into room her owner already grew: never an // allocation or a copy of what she holds (growth is the admitted owner's, measured separately); // - every committed append keeps its receipt, indexed by its sequence: a retry of ANY committed // sequence, however delayed or reordered, gets its original receipt and writes nothing; the same @@ -48,7 +48,7 @@ enum class llama_persona_append_status { out_of_order, // not her next sequence: a gap, or a sequence she never committed moved, // her next sequence, but her history does not end where the request expects changed, // a committed sequence with another identity or delta: refused, never overwritten - no_room, // her reserved tokens or receipts cannot hold this append: her owner grows them first + no_room, // her grown tokens or receipts cannot hold this append: her owner grows them first invalid, // no identity, no sequence, or a null delta with a length }; @@ -80,6 +80,28 @@ class llama_persona_tokens { // need, off the hot path (grow). An accepted append only writes into what has been grown; it never allocates. llama_persona_tokens(uint64_t persona, uint64_t epoch) : persona_(persona), epoch_(epoch) {} + // Give back the room she does not hold (capacity down to her frontier, receipts down to her commits); nothing + // she holds is dropped. Her owner calls it as she cools; false on allocation failure, with her history unchanged. + bool shrink() { + const size_t keep_ids = (size_t) n_, keep_receipts = (size_t) n_committed_; + std::unique_ptr ids(keep_ids ? new (std::nothrow) llama_token[keep_ids] : nullptr); + std::unique_ptr committed(keep_receipts ? new (std::nothrow) commit_record[keep_receipts] : nullptr); + if ((keep_ids && !ids) || (keep_receipts && !committed)) { + return false; + } + if (keep_ids) { + std::memcpy(ids.get(), ids_.get(), keep_ids * sizeof(llama_token)); + } + for (size_t i = 0; i < keep_receipts; ++i) { + committed[i] = committed_[i]; + } + ids_.swap(ids); + committed_.swap(committed); + capacity_ = keep_ids; + receipt_capacity_ = keep_receipts; + return true; + } + // Add room for `more_tokens` ids and `more_receipts` appends, keeping everything she holds. Called by her owner // between acts, never inside one. False on allocation failure, with her history unchanged. bool grow(size_t more_tokens, size_t more_receipts) { @@ -111,7 +133,7 @@ class llama_persona_tokens { size_t capacity() const { return capacity_; } const llama_token * data() const { return ids_.get(); } - // Her generated tokens join her history as she samples them: the same reserved tail, one id at a time. + // Her generated tokens join her history as she samples them: the same grown tail, one id at a time. bool generated(llama_token id) { if (n_ >= capacity_) { return false; @@ -121,7 +143,7 @@ class llama_persona_tokens { } // One validated transaction: check her identity, epoch, sequence and frontier, then write the delta - // into the reserved tail. `delta` is read in place (the caller's buffer, valid for the call). + // into the grown tail. `delta` is read in place (the caller's buffer, valid for the call). llama_persona_receipt append(const llama_persona_append_request & h, const llama_token * delta, size_t n_delta) { llama_persona_receipt r; r.seq = h.seq; diff --git a/tests/test-persona-blocks.cpp b/tests/test-persona-blocks.cpp index 257924f3445a..4b703ad92a80 100644 --- a/tests/test-persona-blocks.cpp +++ b/tests/test-persona-blocks.cpp @@ -338,24 +338,20 @@ int main(int argc, char ** argv) { auto st = [](int32_t s) { return (llama_persona_move) s; }; llama_memory_clear(llama_get_memory(f.ctx), true); f.prompt(0, 1); - llama_persona * p = llama_persona_init(f.ctx); - require(p != nullptr, "a persona for this memory"); + llama_persona * p = llama_persona_init(f.ctx, 0xA11CE, 7); + require(p != nullptr, "a persona for this memory, owned from the start"); uint64_t who = 0, when = 0; - require(!llama_persona_owner(p, &who, &when), "no owner before a completed save"); - require_move(st(llama_persona_save(f.ctx, 0, p)), llama_persona_move::no_owner, "save before her history is reserved"); - require_move(st(llama_persona_reserve_tokens(p, 0xA11CE, 7)), llama_persona_move::done, "reserve her history"); - require_move(st(llama_persona_grow_tokens(p, 64, 8)), llama_persona_move::done, "her owner grows her history ahead"); - require_move(st(llama_persona_reserve_tokens(p, 0xB0B, 7)), llama_persona_move::already_reserved, - "a second reserve would drop her history"); + require(!llama_persona_owner(p, &who, &when), "no stamp before a completed save"); + require_move(st(llama_persona_grow_tokens(p, f.n_prompt, 1)), llama_persona_move::done, "her history grows with her"); + require_move(st(llama_persona_shrink_tokens(p)), llama_persona_move::done, "and shrinks as she cools, dropping nothing"); require_move(st(llama_persona_save(f.ctx, 0, p)), llama_persona_move::done, "save under her owner"); require(llama_persona_owner(p, &who, &when) && who == 0xA11CE && when == 7, "her blocks are stamped with her owner"); require_move(st(llama_persona_bind(f.ctx, 0, p)), llama_persona_move::done, "bound into a stream the memory chose"); f.require_continues("continues after an owned move through the public seam", 0, ref_a0); // every stream occupied: a bind places nobody and changes nothing - llama_persona * q = llama_persona_init(f.ctx); + llama_persona * q = llama_persona_init(f.ctx, 0xB0B, 1); require(q != nullptr, "a second persona"); - require_move(st(llama_persona_reserve_tokens(q, 0xB0B, 1)), llama_persona_move::done, "reserve q"); llama_memory_clear(llama_get_memory(f.ctx), true); f.prompt(0, 1); f.prompt(1, 2); From 57812cdb215b541071660367788e9d9f93f7c63c Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 00:37:31 -0600 Subject: [PATCH 26/28] test-persona-tokens: comments say grown, not reserved Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- tests/test-persona-tokens.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test-persona-tokens.cpp b/tests/test-persona-tokens.cpp index f24772def695..4f73b8046576 100644 --- a/tests/test-persona-tokens.cpp +++ b/tests/test-persona-tokens.cpp @@ -112,7 +112,7 @@ int main() { CHECK(her.append(header(7, 2, 1, 0, id(1)), nullptr, 1).status == status::invalid); CHECK(her.frontier() == 0 && her.committed() == 0); } - // what this catches: an append past her reserved capacity growing it in place (an allocation and a copy + // what this catches: an append past the room her owner grew growing it in place (an allocation and a copy // of what she holds on the hot path): refused, her owner grows first; a length that would overflow too. { llama_persona_tokens her(7, 1); @@ -137,7 +137,7 @@ int main() { CHECK(her.append(header(7, 1, 1, 0, id(1)), d, 2).status == status::replayed); } // what this catches: an accepted append allocating its receipt on the hot path, or a refused one leaving - // a half-written append. Receipts are reserved; when they are used up the append is refused before any + // a half-written append. Receipts are grown ahead by her owner; when they are used up the append is refused before any // write, an empty append included, and her tokens, frontier and commits are unchanged. { llama_persona_tokens her(7, 1); @@ -152,7 +152,7 @@ int main() { } // what this catches (Codex on #147 at f3eb): any allocation on the append path. At her // real size, after her owner grew her history ahead, accepted, refused (no room, wrong epoch, stale frontier) and replayed - // appends together allocate nothing: her capacity and receipts are fixed at reserve and the hot path only writes. + // appends together allocate nothing: her owner grew her room ahead; the hot path only writes. { llama_persona_tokens her(7, 1); CHECK(her.grow(1 << 17, 64)); From 37baf8c120e3455ec9ea9d81015b7c8bb60391d4 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 01:04:33 -0600 Subject: [PATCH 27/28] llama: ownership lives in the native save, load and bind; test history built token by token Codex on #147: the native llama_context::persona_load/persona_bind took bare blocks, so a native caller could bind another persona's state. Every move now names who it is for (llama_persona_identity): the native save stamps the owner, the native load and bind refuse blocks stamped by anyone else before anything is written. The public seam passes her token history's identity and no longer carries its own copy of the check. - test-persona-blocks: native calls carry each persona's identity; a's blocks under b's identity are refused (wrong_owner) on the native path. - test-persona-tokens: the expected history is built with push_back per token; GCC 14 (Ubuntu arm64) -Werror=stringop-overflow refused the 6-token range insert (Codex traced CI on 57812cdb2). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- src/llama-context.cpp | 48 +++++++++++++--------------------- src/llama-context.h | 6 ++--- src/llama-persona-blocks.h | 14 ++++++++-- tests/test-persona-blocks.cpp | 49 ++++++++++++++++++++--------------- tests/test-persona-tokens.cpp | 4 ++- 5 files changed, 64 insertions(+), 57 deletions(-) diff --git a/src/llama-context.cpp b/src/llama-context.cpp index fecb740129c8..872894d66a56 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -2574,7 +2574,7 @@ llama_persona_move llama_context::persona_prepare(llama_persona_blocks & blocks) return memory ? memory->persona_prepare(blocks) : llama_persona_move::unsupported; } -llama_persona_move llama_context::persona_save(llama_seq_id seq_id, llama_persona_blocks & out) { +llama_persona_move llama_context::persona_save(llama_seq_id seq_id, llama_persona_blocks & out, const llama_persona_identity & who) { if (!memory) { return llama_persona_move::unsupported; } @@ -2584,13 +2584,19 @@ llama_persona_move llama_context::persona_save(llama_seq_id seq_id, llama_person return checked; } memory->persona_commit_save(seq_id, out); + out.owned = true; // a completed save stamps her blocks with her owner + out.owner = who.persona; + out.owner_epoch = who.epoch; return llama_persona_move::done; } -llama_persona_move llama_context::persona_load(llama_seq_id seq_id, uint32_t stream, llama_persona_blocks & in) { +llama_persona_move llama_context::persona_load(llama_seq_id seq_id, uint32_t stream, llama_persona_blocks & in, const llama_persona_identity & who) { if (!memory) { return llama_persona_move::unsupported; } + if (!in.belongs_to(who)) { + return llama_persona_move::wrong_owner; // refused before anything is written + } synchronize(); llama_persona_slot slot; const llama_persona_move checked = memory->persona_check_load(seq_id, stream, in, slot); @@ -2601,7 +2607,7 @@ llama_persona_move llama_context::persona_load(llama_seq_id seq_id, uint32_t str return llama_persona_move::done; } -llama_persona_move llama_context::persona_bind(llama_seq_id seq_id, llama_persona_blocks & in) { +llama_persona_move llama_context::persona_bind(llama_seq_id seq_id, llama_persona_blocks & in, const llama_persona_identity & who) { if (!memory) { return llama_persona_move::unsupported; } @@ -2609,7 +2615,7 @@ llama_persona_move llama_context::persona_bind(llama_seq_id seq_id, llama_person if (stream < 0) { return llama_persona_move::no_empty_stream; } - return persona_load(seq_id, (uint32_t) stream, in); + return persona_load(seq_id, (uint32_t) stream, in, who); } llm_graph_params llama_context::graph_params( @@ -4316,40 +4322,22 @@ void llama_persona_free(llama_persona * persona) { delete persona; } -// Her blocks move only under an owner: the persona and epoch of her token history. A completed save stamps them -// with it; a load refuses blocks stamped by another persona or another epoch of her before anything is written. -int32_t llama_persona_save(llama_context * ctx, llama_seq_id seq_id, llama_persona * persona) { - const llama_persona_move m = ctx->persona_save(seq_id, persona->blocks); - if (m == llama_persona_move::done) { - persona->blocks.owned = true; - persona->blocks.owner = persona->tokens->persona(); - persona->blocks.owner_epoch = persona->tokens->epoch(); - } - return (int32_t) m; +// Her blocks move only under her owner (the persona and epoch of her token history): the native save stamps them, +// the native load and bind refuse blocks stamped by anyone else, so no path skips the check. +static llama_persona_identity identity_of(const llama_persona * persona) { + return { persona->tokens->persona(), persona->tokens->epoch() }; } -static llama_persona_move persona_owner_check(const llama_persona * persona) { - const llama_persona_blocks & b = persona->blocks; - if (b.owned && (b.owner != persona->tokens->persona() || b.owner_epoch != persona->tokens->epoch())) { - return llama_persona_move::wrong_owner; - } - return llama_persona_move::done; +int32_t llama_persona_save(llama_context * ctx, llama_seq_id seq_id, llama_persona * persona) { + return (int32_t) ctx->persona_save(seq_id, persona->blocks, identity_of(persona)); } int32_t llama_persona_load(llama_context * ctx, llama_seq_id seq_id, uint32_t stream, llama_persona * persona) { - const llama_persona_move owner = persona_owner_check(persona); - if (owner != llama_persona_move::done) { - return (int32_t) owner; - } - return (int32_t) ctx->persona_load(seq_id, stream, persona->blocks); + return (int32_t) ctx->persona_load(seq_id, stream, persona->blocks, identity_of(persona)); } int32_t llama_persona_bind(llama_context * ctx, llama_seq_id seq_id, llama_persona * persona) { - const llama_persona_move owner = persona_owner_check(persona); - if (owner != llama_persona_move::done) { - return (int32_t) owner; - } - return (int32_t) ctx->persona_bind(seq_id, persona->blocks); + return (int32_t) ctx->persona_bind(seq_id, persona->blocks, identity_of(persona)); } // Whose blocks these are, as stamped by the last completed save (false before any). diff --git a/src/llama-context.h b/src/llama-context.h index e705509f2202..2f591d621106 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -62,10 +62,10 @@ struct llama_context { // queued device work, checks every condition (reserving the destination), then commits raw copies; a refusal // changes nothing. llama_persona_move persona_prepare(llama_persona_blocks & blocks) const; - llama_persona_move persona_save(llama_seq_id seq_id, llama_persona_blocks & out); - llama_persona_move persona_load(llama_seq_id seq_id, uint32_t stream, llama_persona_blocks & in); + llama_persona_move persona_save(llama_seq_id seq_id, llama_persona_blocks & out, const llama_persona_identity & who); + llama_persona_move persona_load(llama_seq_id seq_id, uint32_t stream, llama_persona_blocks & in, const llama_persona_identity & who); // load her into an empty stream the memory chooses (no_empty_stream when none is) - llama_persona_move persona_bind(llama_seq_id seq_id, llama_persona_blocks & in); + llama_persona_move persona_bind(llama_seq_id seq_id, llama_persona_blocks & in, const llama_persona_identity & who); bool opt_state_write_initial(FILE * optimizer, const char * binding); bool opt_state_write(FILE * optimizer, const char * binding); bool opt_shadow_state_write(const llama_adapter_lora * shadow, FILE * optimizer, const char * binding); diff --git a/src/llama-persona-blocks.h b/src/llama-persona-blocks.h index 2e4e841d4600..24601fb4dce8 100644 --- a/src/llama-persona-blocks.h +++ b/src/llama-persona-blocks.h @@ -34,13 +34,23 @@ struct llama_rs_seq_blocks { // her identity travels with her blocks: the sequence her metadata is tagged with, and the layout of the memory they // were prepared for (a fingerprint of layer count, stream size, row types and sizes, snapshot groups) +// Who a move is for: the persona and epoch whose token history the blocks belong to. +struct llama_persona_identity { + uint64_t persona = 0; + uint64_t epoch = 0; +}; + struct llama_persona_blocks { llama_seq_id seq = -1; - // whose blocks these are: the owner of her token history when they were saved (persona + epoch), stamped by - // the public seam on a completed save and checked before any load; never retagged + // whose blocks these are: the owner of her token history when they were saved (persona + epoch), stamped by a + // completed save and checked by every load, native or public, before anything is written; never retagged bool owned = false; uint64_t owner = 0; uint64_t owner_epoch = 0; + + bool belongs_to(const llama_persona_identity & who) const { + return !owned || (owner == who.persona && owner_epoch == who.epoch); + } uint64_t kv_layout = 0; uint64_t rs_layout = 0; llama_kv_stream_blocks kv; diff --git a/tests/test-persona-blocks.cpp b/tests/test-persona-blocks.cpp index 4b703ad92a80..41f9e5b43286 100644 --- a/tests/test-persona-blocks.cpp +++ b/tests/test-persona-blocks.cpp @@ -68,6 +68,10 @@ static void require_identical(const char * what, const std::vector & want require(identical, what); } +// the owners in this test: each persona's blocks are saved and loaded under her identity +static const llama_persona_identity A { 0xA, 1 }; +static const llama_persona_identity B { 0xB, 1 }; + struct fixture { llama_context * ctx = nullptr; int n_vocab = 0; @@ -164,7 +168,7 @@ int main(int argc, char ** argv) { const int64_t t_prefill = ggml_time_us() - t0; const int64_t t1 = ggml_time_us(); - require_move(ctx.persona_save(0, a), llama_persona_move::done, "her state out"); + require_move(ctx.persona_save(0, a, A), llama_persona_move::done, "her state out"); const int64_t t_save = ggml_time_us() - t1; size_t bytes = 0; for (const auto & v : a.kv.k) { bytes += v.size(); } @@ -173,7 +177,7 @@ int main(int argc, char ** argv) { for (const auto & v : a.rs.s) { bytes += v.size(); } const uint32_t other = 1 - llama_get_memory(f.ctx)->seq_stream(0); const int64_t t2 = ggml_time_us(); - require_move(ctx.persona_load(0, other, a), llama_persona_move::done, "her state into the other stream"); + require_move(ctx.persona_load(0, other, a, A), llama_persona_move::done, "her state into the other stream"); const int64_t t_load = ggml_time_us() - t2; std::vector> moved; moved.push_back(f.decode_one(0, 3 % f.n_vocab, f.n_prompt)); @@ -197,12 +201,15 @@ int main(int argc, char ** argv) { // 1. out of stream 0, into stream 1 bound to her own sequence 0 llama_memory_clear(llama_get_memory(f.ctx), true); f.prompt(0, 1); - require_move(ctx.persona_save(0, a), llama_persona_move::done, "a out"); + require_move(ctx.persona_save(0, a, A), llama_persona_move::done, "a out"); require(f.pos_max(0) < 0, "nothing of a is left in the memory"); require(a.seq == 0, "her blocks carry her sequence"); - require_move(ctx.persona_load(1, 1, a), llama_persona_move::wrong_persona, "a refused as sequence 1 (never retagged)"); + require_move(ctx.persona_load(1, 1, a, A), llama_persona_move::wrong_persona, "a refused as sequence 1 (never retagged)"); + // what this catches: the native load trusting its caller. a's blocks under b's identity are refused before + // anything is written, on the native path itself, not only the public seam. + require_move(ctx.persona_load(0, 1, a, B), llama_persona_move::wrong_owner, "a's blocks refused under b's identity"); require(f.pos_max(1) < 0, "the refused load wrote nothing"); - require_move(ctx.persona_load(0, 1, a), llama_persona_move::done, "a into stream 1"); + require_move(ctx.persona_load(0, 1, a, A), llama_persona_move::done, "a into stream 1"); require(f.pos_max(0) == f.n_prompt - 1, "a's sequence holds her prompt"); f.require_continues("a moved to stream 1", 0, ref_a0); @@ -210,16 +217,16 @@ int main(int argc, char ** argv) { llama_memory_clear(llama_get_memory(f.ctx), true); f.prompt(1, 2); const uint32_t b_stream = llama_get_memory(f.ctx)->seq_stream(1); - require_move(ctx.persona_save(1, b), llama_persona_move::done, "b out"); - require_move(ctx.persona_load(1, 1 - b_stream, b), llama_persona_move::done, "b into the other stream"); + require_move(ctx.persona_save(1, b, B), llama_persona_move::done, "b out"); + require_move(ctx.persona_load(1, 1 - b_stream, b, B), llama_persona_move::done, "b into the other stream"); f.require_continues("b moved to the other stream", 1, ref_b1); // 3. same-stream round trip llama_memory_clear(llama_get_memory(f.ctx), true); f.prompt(0, 1); const uint32_t a_stream = llama_get_memory(f.ctx)->seq_stream(0); - require_move(ctx.persona_save(0, a), llama_persona_move::done, "a out (round trip)"); - require_move(ctx.persona_load(0, a_stream, a), llama_persona_move::done, "a back into her own stream"); + require_move(ctx.persona_save(0, a, A), llama_persona_move::done, "a out (round trip)"); + require_move(ctx.persona_load(0, a_stream, a, A), llama_persona_move::done, "a back into her own stream"); f.require_continues("a same-stream round trip", 0, ref_a0); // 4. refusals are typed and change nothing @@ -228,26 +235,26 @@ int main(int argc, char ** argv) { f.prompt(0, 1); f.prompt(1, 2); llama_persona_blocks unprepared; - require(ctx.persona_save(0, unprepared) != llama_persona_move::done, "an unprepared save is refused"); + require(ctx.persona_save(0, unprepared, A) != llama_persona_move::done, "an unprepared save is refused"); require(f.pos_max(0) == f.n_prompt - 1, "a refused save leaves her in place"); - require_move(ctx.persona_save(0, a), llama_persona_move::done, "a out (refusal setup)"); + require_move(ctx.persona_save(0, a, A), llama_persona_move::done, "a out (refusal setup)"); const uint32_t occupied = llama_get_memory(f.ctx)->seq_stream(1); - require_move(ctx.persona_load(0, occupied, a), llama_persona_move::stream_not_empty, "load over b's stream"); + require_move(ctx.persona_load(0, occupied, a, A), llama_persona_move::stream_not_empty, "load over b's stream"); require(f.pos_max(1) == f.n_prompt - 1, "b untouched by the refused load"); llama_persona_blocks bad = a; // the same persona with one layer's rows missing bad.kv.k.pop_back(); - require_move(ctx.persona_load(0, 1 - occupied, bad), llama_persona_move::layout_mismatch, "a layout mismatch"); + require_move(ctx.persona_load(0, 1 - occupied, bad, A), llama_persona_move::layout_mismatch, "a layout mismatch"); require(f.pos_max(0) < 0, "a refused load writes nothing"); if (a.rs.has_state) { // hybrid: a rollback index past the snapshot groups is refused before any write llama_persona_blocks far = a; far.rs.rs_idx = 1u << 20; - require_move(ctx.persona_load(0, 1 - occupied, far), llama_persona_move::invalid_rollback, "a rollback out of bounds"); + require_move(ctx.persona_load(0, 1 - occupied, far, A), llama_persona_move::invalid_rollback, "a rollback out of bounds"); require(f.pos_max(0) < 0, "a refused hybrid load writes neither half"); } - require_move(ctx.persona_load(0, 1 - occupied, a), llama_persona_move::done, "a back after the refusals"); + require_move(ctx.persona_load(0, 1 - occupied, a, A), llama_persona_move::done, "a back after the refusals"); f.require_continues("a after the refusals", 0, ref_a0); f.require_continues("b untouched by a's refusals", 1, ref_b1); } @@ -260,10 +267,10 @@ int main(int argc, char ** argv) { const uint32_t sa = llama_get_memory(f.ctx)->seq_stream(0); const uint32_t sb = llama_get_memory(f.ctx)->seq_stream(1); require(sa != sb, "two personas, two streams"); - require_move(ctx.persona_save(0, a), llama_persona_move::done, "a out (exchange)"); - require_move(ctx.persona_save(1, b), llama_persona_move::done, "b out (exchange)"); - require_move(ctx.persona_load(0, sb, a), llama_persona_move::done, "a into b's stream"); - require_move(ctx.persona_load(1, sa, b), llama_persona_move::done, "b into a's stream"); + require_move(ctx.persona_save(0, a, A), llama_persona_move::done, "a out (exchange)"); + require_move(ctx.persona_save(1, b, B), llama_persona_move::done, "b out (exchange)"); + require_move(ctx.persona_load(0, sb, a, A), llama_persona_move::done, "a into b's stream"); + require_move(ctx.persona_load(1, sa, b, B), llama_persona_move::done, "b into a's stream"); require(llama_get_memory(f.ctx)->seq_stream(0) == sb && llama_get_memory(f.ctx)->seq_stream(1) == sa, "the streams are exchanged"); f.require_continues("a after the exchange", 0, ref_a0); @@ -325,9 +332,9 @@ int main(int argc, char ** argv) { drafted_then_rolled_back(); llama_persona_blocks r; require_move(ctx.persona_prepare(r), llama_persona_move::done, "prepare persona r"); - require_move(ctx.persona_save(0, r), llama_persona_move::done, "r out with a rollback pending"); + require_move(ctx.persona_save(0, r, A), llama_persona_move::done, "r out with a rollback pending"); require(!r.rs.has_state || r.rs.rs_idx > 0, "her pending rollback travels with her"); - require_move(ctx.persona_load(0, 1 - llama_get_memory(f.ctx)->seq_stream(0), r), llama_persona_move::done, "r in"); + require_move(ctx.persona_load(0, 1 - llama_get_memory(f.ctx)->seq_stream(0), r, A), llama_persona_move::done, "r in"); require_identical("continues after a move with a rollback pending", in_place, f.decode_one(0, 7 % f.n_vocab, f.n_prompt + 1)); fprintf(stderr, "rollback groups exercised: n_rs_seq=%u, her rs_idx=%u\n", llama_n_rs_seq(f.ctx), r.rs.rs_idx); diff --git a/tests/test-persona-tokens.cpp b/tests/test-persona-tokens.cpp index 4f73b8046576..a43f8309cac2 100644 --- a/tests/test-persona-tokens.cpp +++ b/tests/test-persona-tokens.cpp @@ -57,7 +57,9 @@ int main() { const llama_token delta[] = { 9, 1, (llama_token) (70 + a), 9, 2, 7 }; const auto r = her.append(header(7, 1, a + 2, her.frontier(), id(a + 2)), delta, 6); CHECK(r.status == status::appended && r.from + 6 == r.to && r.to == her.frontier()); - expect.insert(expect.end(), delta, delta + 6); + for (const llama_token t : delta) { + expect.push_back(t); // one at a time: GCC 14 -Werror=stringop-overflow refuses the bulk range insert + } } CHECK(her.frontier() == expect.size() && her.committed() == 4); CHECK(std::equal(expect.begin(), expect.end(), her.data())); From a88f255cc7992589ff419f59b1ebc17e51ce4f1e Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 18 Nov 2026 01:32:03 -0600 Subject: [PATCH 28/28] llama: a persona binds as whichever sequence she is bound as; her cells are relabeled, never refused Two execution streams must serve any number of minds: the active one decodes in one while the next binds into the other, so a mind saved from sequence 0 has to come back as sequence 1. The bind refused that (wrong_persona, "never retagged"). - llama_kv_cells::seq_rename relabels every cell of one sequence as another, with its position index (a stream holds one persona, so nothing merges); the KV load calls it after taking her cells. - The recurrent load already builds her cell's sequence node as the bound sequence; its refusal goes too. - test-persona-blocks: saved as sequence 0, she binds as sequence 1, answers to 1 only, and continues byte-identically. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- src/llama-kv-cache.cpp | 4 +--- src/llama-kv-cells.h | 18 ++++++++++++++++++ src/llama-memory-recurrent.cpp | 3 --- tests/test-persona-blocks.cpp | 11 ++++++++++- 4 files changed, 29 insertions(+), 7 deletions(-) diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index 8b9ac5ad2cbf..41a49ed8b7c2 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -1359,9 +1359,6 @@ llama_persona_move llama_kv_cache::persona_check_load(llama_seq_id seq_id, uint3 if (in.kv_layout != persona_layout()) { return llama_persona_move::layout_mismatch; } - if (in.kv.n_rows > 0 && in.seq != seq_id) { - return llama_persona_move::wrong_persona; - } const auto & kv = in.kv; if (kv.cells.size() != get_size() || kv.n_rows > get_size() || kv.cells.used_max_p1() > kv.n_rows || kv.k.size() != layers.size() || kv.v.size() != layers.size()) { @@ -1391,6 +1388,7 @@ void llama_kv_cache::persona_commit_load(llama_seq_id seq_id, llama_persona_slot } } in.kv.cells.swap(v_cells[s]); // hers in; her blocks keep the stream's empty object for her next save + v_cells[s].seq_rename(in.seq, seq_id); // her cells answer to the sequence she is bound as now v_heads[s] = 0; // bind her own sequence id to stream s; the sequence that held s takes her old stream (both empty of others) const uint32_t old = seq_to_stream[seq_id]; diff --git a/src/llama-kv-cells.h b/src/llama-kv-cells.h index 531e8b938837..2196dbfb38e3 100644 --- a/src/llama-kv-cells.h +++ b/src/llama-kv-cells.h @@ -354,6 +354,24 @@ class llama_kv_cells { return seq[i].test(seq_id); } + // Relabel every cell of sequence `from` as `to`, with its position index: a persona's cells bound back as the + // sequence she is bound as now. `to` holds no cell here (a stream holds one persona), so nothing merges. + void seq_rename(llama_seq_id from, llama_seq_id to) { + if (from == to) { + return; + } + for (uint32_t i = used.min(); i < used.max_p1(); ++i) { + if (seq[i].test(from)) { + seq[i].reset(from); + seq[i].set(to); + } + } + seq_pos[to].swap(seq_pos[from]); + const bool was_stale = stale.test(from); + stale.set(from, stale.test(to)); + stale.set(to, was_stale); + } + // note: call only if the cell is not empty and the seq_id is not in the cell void seq_add(uint32_t i, llama_seq_id seq_id) { assert(i < pos.size()); diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp index f94c65df5962..aec9c96d5693 100644 --- a/src/llama-memory-recurrent.cpp +++ b/src/llama-memory-recurrent.cpp @@ -493,9 +493,6 @@ llama_persona_move llama_memory_recurrent::persona_check_load(llama_seq_id seq_i if (!rs.has_state) { return llama_persona_move::done; } - if (in.seq != seq_id) { - return llama_persona_move::wrong_persona; - } if (rs.rs_idx > n_rs_seq) { return llama_persona_move::invalid_rollback; } diff --git a/tests/test-persona-blocks.cpp b/tests/test-persona-blocks.cpp index 41f9e5b43286..16dbbfe63539 100644 --- a/tests/test-persona-blocks.cpp +++ b/tests/test-persona-blocks.cpp @@ -204,7 +204,6 @@ int main(int argc, char ** argv) { require_move(ctx.persona_save(0, a, A), llama_persona_move::done, "a out"); require(f.pos_max(0) < 0, "nothing of a is left in the memory"); require(a.seq == 0, "her blocks carry her sequence"); - require_move(ctx.persona_load(1, 1, a, A), llama_persona_move::wrong_persona, "a refused as sequence 1 (never retagged)"); // what this catches: the native load trusting its caller. a's blocks under b's identity are refused before // anything is written, on the native path itself, not only the public seam. require_move(ctx.persona_load(0, 1, a, B), llama_persona_move::wrong_owner, "a's blocks refused under b's identity"); @@ -213,6 +212,16 @@ int main(int argc, char ** argv) { require(f.pos_max(0) == f.n_prompt - 1, "a's sequence holds her prompt"); f.require_continues("a moved to stream 1", 0, ref_a0); + // 1b. what this catches: a mind bound only back as the sequence she was saved from, so two streams cannot serve + // any number of minds. Saved as sequence 0, she binds as sequence 1: her cells answer to 1, nothing is left on 0, + // and she continues byte-identically. + llama_memory_clear(llama_get_memory(f.ctx), true); + f.prompt(0, 1); + require_move(ctx.persona_save(0, a, A), llama_persona_move::done, "a out (to rebind as another sequence)"); + require_move(ctx.persona_load(1, 1, a, A), llama_persona_move::done, "a bound as sequence 1"); + require(f.pos_max(1) == f.n_prompt - 1 && f.pos_max(0) < 0, "her cells answer to sequence 1 only"); + f.require_continues("a continues as sequence 1", 1, ref_a0); + // 2. the mirror: b's sequence 1 out of its stream and into the other llama_memory_clear(llama_get_memory(f.ctx), true); f.prompt(1, 2);