diff --git a/include/llama.h b/include/llama.h index 6ff7b047fd40..11c03a6ae0a7 100644 --- a/include/llama.h +++ b/include/llama.h @@ -927,6 +927,74 @@ 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; + + // 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 + // 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); + + // 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 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. + // 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. + 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). 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); + // // State / sessions // diff --git a/src/llama-context.cpp b/src/llama-context.cpp index c2d348884ce9..872894d66a56 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -1,5 +1,8 @@ #include "llama-context.h" +#include +#include "llama-persona-tokens.h" + #include "ggml.h" #include "llama-arch.h" #include "llama-graph.h" @@ -2567,12 +2570,60 @@ 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, const llama_persona_identity & who) { + 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); + 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, 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); + if (checked != llama_persona_move::done) { + return checked; + } + memory->persona_commit_load(seq_id, slot, in); + return llama_persona_move::done; +} + +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; + } + 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, who); +} + llm_graph_params llama_context::graph_params( llm_graph_result * res, 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 +2642,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( @@ -4199,3 +4257,99 @@ 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; + std::unique_ptr tokens; // her token history, beside her blocks (llama-persona-tokens.h) +}; + +// 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) { + 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 (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) { + *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, 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; + } + return persona; +} + +void llama_persona_free(llama_persona * persona) { + delete persona; +} + +// 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() }; +} + +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) { + 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) { + 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). +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-context.h b/src/llama-context.h index 86bb220f765f..2f591d621106 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -57,6 +57,15 @@ 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, 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, 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-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..41a49ed8b7c2 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; } @@ -363,6 +374,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) { @@ -379,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; @@ -448,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; @@ -540,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; @@ -567,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; @@ -617,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; @@ -752,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 { @@ -1098,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; @@ -1231,6 +1251,156 @@ ggml_tensor * llama_kv_cache::get_k_storage(int32_t il) const { return layers[ikv].k; } +// 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(); +} + +// 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::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) { + 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, 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_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]; + for (size_t i = 0; i < layers.size(); ++i) { + const auto & layer = layers[i]; + 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()); + } + 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; + out.kv.cells.swap(cells); // hers out; the stream takes the prepared empty object + 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) { + 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_persona_move::transposed_v; + } + if (v_cells[stream].get_used() != 0) { + return llama_persona_move::stream_not_empty; + } + 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; + } + 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, 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.kv.k[i].empty()) { + ggml_backend_tensor_set(layer.k_stream[s], in.kv.k[i].data(), 0, in.kv.k[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()); + } + } + 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]; + 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 { GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size()); @@ -2061,6 +2231,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-cache.h b/src/llama-kv-cache.h index cba1f663b2e4..6e85ed9c25be 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -175,6 +175,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): 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; + 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; + void persona_commit_save(llama_seq_id seq_id, llama_persona_blocks & out) 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]; } + // // graph_build API // @@ -290,6 +304,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-kv-cell-index.h b/src/llama-kv-cell-index.h new file mode 100644 index 000000000000..c8666e10b516 --- /dev/null +++ b/src/llama-kv-cell-index.h @@ -0,0 +1,258 @@ +#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 +#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; +}; + +// 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 fddd31a0b219..2196dbfb38e3 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 { @@ -31,6 +30,23 @@ 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]); + } + std::swap(stale, other.stale); + } + void reset() { for (uint32_t i = 0; i < pos.size(); ++i) { pos[i] = -1; @@ -46,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() { @@ -65,6 +82,7 @@ class llama_kv_cells { ext.resize(n); shift.resize(n); seq.resize(n); + used.resize(n); reset(); } @@ -76,6 +94,37 @@ class llama_kv_cells { return pos[i] == -1; } + // 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) { + 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 + uint64_t settles() const { + 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(); } @@ -83,13 +132,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 { @@ -305,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()); @@ -335,13 +402,11 @@ class llama_kv_cells { assert(seq_id >= 0); assert(seq_id < LLAMA_MAX_SEQ); - if (seq_pos[seq_id].empty()) { - return -1; + const llama_kv_seq_pos & index = seq_pos[seq_id]; + if (index.is_stale()) { + return unsettled_extremum(seq_id, false); } - - assert(seq_pos[seq_id].begin()->second > 0); - - return seq_pos[seq_id].begin()->first; + return index.empty() ? -1 : index.min(); } // the maximum position of sequence seq_id currently present in any of the cells @@ -350,13 +415,11 @@ class llama_kv_cells { assert(seq_id >= 0); assert(seq_id < LLAMA_MAX_SEQ); - if (seq_pos[seq_id].empty()) { - return -1; + const llama_kv_seq_pos & index = seq_pos[seq_id]; + if (index.is_stale()) { + return unsettled_extremum(seq_id, true); } - - assert(seq_pos[seq_id].rbegin()->second > 0); - - return seq_pos[seq_id].rbegin()->first; + return index.empty() ? -1 : index.max(); } // note: call only if the cell is not empty @@ -458,8 +521,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; @@ -488,29 +551,65 @@ 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; 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) + 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); + } + + // 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]; + } + } + return found; + } // 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); + if (seq_pos[s].is_stale()) { + stale.set(s); } } void seq_pos_inc(llama_seq_id s, llama_pos p) { - seq_pos[s][p]++; + seq_pos[s].inc(p); + if (seq_pos[s].is_stale()) { + stale.set(s); + } } // remove cell i 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.cpp b/src/llama-memory-hybrid.cpp index 6cb6faee3cf9..db115ba6f3ae 100644 --- a/src/llama-memory-hybrid.cpp +++ b/src/llama-memory-hybrid.cpp @@ -211,6 +211,33 @@ void llama_memory_hybrid::state_read(llama_io_read_i & io, llama_seq_id seq_id, mem_recr->state_read(io, seq_id, flags); } +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); +} + +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); +} + +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, 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 { return mem_attn.get(); } diff --git a/src/llama-memory-hybrid.h b/src/llama-memory-hybrid.h index 8cd1dfc80982..8715212f1d78 100644 --- a/src/llama-memory-hybrid.h +++ b/src/llama-memory-hybrid.h @@ -86,6 +86,17 @@ class llama_memory_hybrid : public llama_memory_i { // llama_kv_cache * get_mem_attn() const; + + // 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; + 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; private: diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp index 208c9d0d557b..aec9c96d5693 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) { @@ -392,6 +394,163 @@ 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::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); + 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, 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; + } + const int32_t tail = cells[seq_id].tail; + 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; +} + +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; + out.seq = seq_id; + if (!rs.has_state) { + return; + } + const uint32_t n_groups = 1 + n_rs_seq; + // 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; + rs.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); +} + +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_persona_move::invalid_seq; + } + if (cells[seq_id].tail >= 0) { + return llama_persona_move::seq_holds_state; + } + 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 (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; + } + 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; + } + } + 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, 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; + // 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; + cell.src = cell_id; + cell.src0 = cell_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; +} + 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..13ac2127614b 100644 --- a/src/llama-memory-recurrent.h +++ b/src/llama-memory-recurrent.h @@ -85,6 +85,17 @@ 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 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; + 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; + void persona_commit_save(llama_seq_id seq_id, llama_persona_blocks & out) 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) bool rollback_pending(llama_seq_id seq_id) const { @@ -127,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/src/llama-memory.cpp b/src/llama-memory.cpp index ca6844c32a76..646fb357bed0 100644 --- a/src/llama-memory.cpp +++ b/src/llama-memory.cpp @@ -57,3 +57,25 @@ 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"; + case llama_persona_move::wrong_persona: return "wrong_persona"; + case llama_persona_move::invalid_rollback: return "invalid_rollback"; + case llama_persona_move::wrong_owner: return "wrong_owner"; + 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 ceb327db46f1..5fa23b155c92 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 @@ -147,6 +148,36 @@ 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; } + + // 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, 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, 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; + } + // 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; + } + 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..24601fb4dce8 --- /dev/null +++ b/src/llama-persona-blocks.h @@ -0,0 +1,87 @@ +#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: 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 +// 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 +}; + +// 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 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; + llama_rs_seq_blocks rs; +}; + +// 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; + std::set::node_type node; +}; + +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 + 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 + wrong_owner, // her blocks were saved by another persona or another epoch of her + 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 +}; + +const char * llama_persona_move_name(llama_persona_move m); diff --git a/src/llama-persona-tokens.h b/src/llama-persona-tokens.h new file mode 100644 index 000000000000..9039df4bd2dc --- /dev/null +++ b/src/llama-persona-tokens.h @@ -0,0 +1,214 @@ +#pragma once + +#include "llama.h" + +#include +#include +#include +#include +#include + +// 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 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 +// 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; + 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_request { + 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 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 + 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 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 +}; + +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::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::invalid: return "invalid"; + } + return "unknown"; +} + +struct llama_persona_receipt { + 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 +}; + +class llama_persona_tokens { +public: + // 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) {} + + // 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) { + 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_; } + uint64_t frontier() const { return n_; } + uint64_t committed() const { return n_committed_; } + 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 grown 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, sequence and frontier, then write the delta + // 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; + 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; + return r; + } + if (h.epoch != epoch_) { + r.status = llama_persona_append_status::wrong_epoch; + return r; + } + // A committed sequence: its own receipt for the same request and delta, refused for anything else. + 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); + 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 != n_committed_ + 1) { + r.status = llama_persona_append_status::out_of_order; + return r; + } + if (h.frontier != n_) { + r.status = llama_persona_append_status::moved; + r.to = n_; + return r; + } + // 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; + } + 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_[n_committed_++] = { h.request, h.frontier, r.from, r.to }; + n_ = r.to; + return r; + } + +private: + // 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; + uint64_t expected; + uint64_t from; + uint64_t to; + }; + + uint64_t persona_; + uint64_t epoch_; + size_t capacity_ = 0; + std::unique_ptr ids_; + uint64_t n_ = 0; + size_t receipt_capacity_ = 0; + std::unique_ptr committed_; + uint64_t n_committed_ = 0; +}; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index ca0592f3a725..253ed1c5c53d 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -194,6 +194,11 @@ 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) +# 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) @@ -268,6 +273,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 @@ -363,6 +387,12 @@ 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) +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}") set_tests_properties(test-save-load-state PROPERTIES FIXTURES_REQUIRED test-download-model) 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 new file mode 100644 index 000000000000..32f0db7543c1 --- /dev/null +++ b/tests/test-kv-cell-index.cpp @@ -0,0 +1,297 @@ +// 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 "kv-cells-previous.h" + +#include +#include +#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; + } + } + // 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 +// 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(); // 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 && 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). +std::atomic counting{ false }; +std::atomic allocations{ 0 }; + +struct measured { + double ms; + uint64_t allocations; +}; + +template +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 = [&] { 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(); + 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) { + // 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_allocs, now_ms, (unsigned long long) now_allocs); +} + +} // 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); + } + freeze_then_bind(); + queries_never_write(); + 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; +} diff --git a/tests/test-persona-blocks.cpp b/tests/test-persona-blocks.cpp new file mode 100644 index 000000000000..16dbbfe63539 --- /dev/null +++ b/tests/test-persona-blocks.cpp @@ -0,0 +1,382 @@ +// 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. +// +// 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" +#include "llama.h" + +#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); + std::exit(1); + } +} + +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 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 < std::min(want.size(), got.size()); ++i) { + max_diff = std::max(max_diff, std::fabs(want[i] - got[i])); + } + 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); + 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; + 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), 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_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"); + } + 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 + 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((int) args.size(), args.data(), params, LLAMA_EXAMPLE_COMMON)) { + return 1; + } + ggml_backend_load_all(); + common_init_result_ptr init = common_init_from_params(params); + 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; + + 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, 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, 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 + + // 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, 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"); + // 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, 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); + + // 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); + const uint32_t b_stream = llama_get_memory(f.ctx)->seq_stream(1); + 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, 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 + { + 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, 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, 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, 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, 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, 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, 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, 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); + 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, 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, 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); + } + + // 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, 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 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, 0xB0B, 1); + require(q != nullptr, "a second persona"); + 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); + } + + fprintf(stderr, "test-persona-blocks: ok (%zu attention layers, %zu recurrent layers)\n", a.kv.k.size(), a.rs.r.size()); + return 0; +} diff --git a/tests/test-persona-tokens.cpp b/tests/test-persona-tokens.cpp new file mode 100644 index 000000000000..a43f8309cac2 --- /dev/null +++ b/tests/test-persona-tokens.cpp @@ -0,0 +1,206 @@ +// 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 +#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) + +using status = llama_persona_append_status; + +static llama_persona_request_id id(uint64_t n) { return { 1, n }; } + +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; + 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); + 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); + 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(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()); + 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())); + } + // 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); + 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); + 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); + 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); + 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); + 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); + CHECK(her.append(header(7, 1, 2, 1, id(2)), d, 1).status == status::appended); + CHECK(her.frontier() == 2); + } + // what this catches: a stale, foreign or malformed request appended to her history. + { + 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); + 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 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); + 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 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); + 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); + 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); + } + // 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 owner grew her room ahead; the hot path only writes. + { + 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); + 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, "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); + 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); + 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(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); + 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; +} 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", [