diff --git a/include/llama.h b/include/llama.h index f053551529e9..8a10de472d9e 100644 --- a/include/llama.h +++ b/include/llama.h @@ -399,6 +399,7 @@ extern "C" { // Keep the booleans together and at the end of the struct to avoid misalignment during copy-by-value. bool embeddings; // if true, extract embeddings (together with logits) + bool embeddings_only; // pooled embeddings without vocabulary logits or sampling bool offload_kqv; // offload the KQV ops (including the KV cache) to GPU bool no_perf; // measure performance timings bool op_offload; // offload host tensor operations to device @@ -725,6 +726,13 @@ extern "C" { LLAMA_API const char * llama_model_weight_backend_name (const struct llama_model * model, size_t i); LLAMA_API size_t llama_model_weight_backend_bytes(const struct llama_model * model, size_t i); + // Account for the allocator's actual memory pool, including pinned host buffers. + struct llama_weight_allocation { + size_t host; + size_t device; + }; + LLAMA_API struct llama_weight_allocation llama_model_weight_allocation(const struct llama_model * model); + // Get the default chat template. Returns nullptr if not available // If name is NULL, returns the default chat template LLAMA_API const char * llama_model_chat_template(const struct llama_model * model, const char * name); @@ -950,6 +958,14 @@ extern "C" { // 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); + // Continuum fork (CONTINUUM-ENGINE 4.16): her saved blocks on disk and back, so a restart demotes her instead of + // dropping her. write_file writes blocks a completed save holds (file_mismatch when none) to `path` through + // `.tmp` and a rename. read_file fills a persona made by llama_persona_init on a context of the same memory + // layout, for the owner and epoch her file names; file_mismatch (another owner, epoch, layout or size) and io_error + // leave her as she was. Bind her afterwards as after a save. + LLAMA_API int32_t llama_persona_write_file(const struct llama_persona * persona, const char * path); + LLAMA_API int32_t llama_persona_read_file(struct llama_persona * persona, const char * path); + LLAMA_API const char * llama_persona_status_name(int32_t status); // A checkpoint of a BOUND sequence at its current position, taken without moving her: her recurrent rows (every diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 7dcd7a5a3e23..65565b5a1266 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -16,6 +16,7 @@ add_library(llama llama-batch.cpp llama-chat.cpp llama-context.cpp + llama-persona-file.cpp llama-context-opt.cpp llama-context-opt-measure.cpp llama-context-learn.cpp diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 05b83065cb36..7cd738acda03 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -1,7 +1,7 @@ #include "llama-context.h" #include -#include "llama-persona-tokens.h" +#include "llama-persona.h" #include "ggml.h" #include "llama-arch.h" @@ -113,6 +113,10 @@ llama_context::llama_context( cparams.yarn_attn_factor = params.yarn_attn_factor >= 0.0f ? params.yarn_attn_factor : hparams.yarn_attn_factor; cparams.yarn_beta_fast = params.yarn_beta_fast >= 0.0f ? params.yarn_beta_fast : hparams.yarn_beta_fast; cparams.yarn_beta_slow = params.yarn_beta_slow >= 0.0f ? params.yarn_beta_slow : hparams.yarn_beta_slow; + if (params.embeddings_only && (!params.embeddings || params.pooling_type == LLAMA_POOLING_TYPE_NONE || params.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED)) { + throw std::runtime_error("embeddings_only requires embeddings and explicit sequence pooling"); + } + cparams.embeddings_only = params.embeddings_only; cparams.embeddings = params.embeddings; cparams.embeddings_nextn = false; cparams.embeddings_nextn_masked = false; @@ -2140,7 +2144,7 @@ uint32_t llama_context::output_reserve(int32_t n_outputs) { const auto n_embd = hparams.n_embd; const auto n_embd_out = hparams.n_embd_out(); - bool has_logits = true; + bool has_logits = !cparams.embeddings_only; bool has_embd = cparams.embeddings; bool has_embd_nextn = cparams.embeddings_nextn; @@ -3593,6 +3597,7 @@ llama_context_params llama_context_default_params() { /*.abort_callback =*/ nullptr, /*.abort_callback_data =*/ nullptr, /*.embeddings =*/ false, + /*.embeddings_only =*/ false, /*.offload_kqv =*/ true, /*.no_perf =*/ true, /*.op_offload =*/ true, @@ -4293,12 +4298,8 @@ 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) -}; +// Continuum fork (CONTINUUM-ENGINE 4.14): the public seam of a persona's move (llama-persona-blocks.h); the persona +// object itself is in llama-persona.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) { diff --git a/src/llama-cparams.h b/src/llama-cparams.h index 9857c99f066d..2a20efd4c2d5 100644 --- a/src/llama-cparams.h +++ b/src/llama-cparams.h @@ -58,6 +58,7 @@ struct llama_cparams { float yarn_beta_slow; bool embeddings; + bool embeddings_only = false; bool embeddings_nextn; // also extract the hidden state before the final output norm bool embeddings_nextn_masked; // extract for only rows where batch.logits != 0 bool causal_attn; diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index d2d69e4b0d8a..7c58de300c7b 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -375,7 +375,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 + persona_layout_id = compute_persona_layout(true); // the allocation layout is immutable from here + persona_rows_id = compute_persona_layout(false); } void llama_kv_cache::clear(bool data) { @@ -1263,9 +1264,10 @@ static bool cells_prepared(const llama_kv_cells & cells, uint32_t size) { // this memory's attention layout: what her rows' sizes and meaning depend on static uint64_t kv_layout_mix(uint64_t h, uint64_t v) { return (h ^ v) * 0x100000001b3ull; } -uint64_t llama_kv_cache::compute_persona_layout() const { +uint64_t llama_kv_cache::compute_persona_layout(bool with_size) const { uint64_t h = kv_layout_mix(0xcbf29ce484222325ull, layers.size()); - h = kv_layout_mix(h, get_size()); + // the stream size is part of a live move's layout; a file restores into any stream her rows fit + h = with_size ? kv_layout_mix(h, get_size()) : h; 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); @@ -1281,9 +1283,18 @@ llama_persona_move llama_kv_cache::persona_prepare(llama_persona_blocks & blocks return llama_persona_move::no_such_stream; } blocks.kv_layout = persona_layout(); + blocks.kv_rows = persona_rows_id; blocks.kv.cells.resize(get_size()); // once per persona, at her creation blocks.kv.k.resize(layers.size()); blocks.kv.v.resize(layers.size()); + // the row sizes a save copies (persona_check_save), recorded for a file read to check before it allocates + blocks.geometry.k_row.resize(layers.size()); + blocks.geometry.v_row.resize(layers.size()); + for (size_t i = 0; i < layers.size(); ++i) { + const auto & layer = layers[i]; + blocks.geometry.k_row[i] = ggml_row_size(layer.k->type, layer.k->ne[0]); + blocks.geometry.v_row[i] = layer.v ? ggml_row_size(layer.v->type, layer.v->ne[0]) : 0; + } return llama_persona_move::done; } diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h index c9346b8b67dd..9b2555b0872d 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -310,7 +310,8 @@ class llama_kv_cache : public llama_memory_i { // 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; + uint64_t persona_rows_id = 0; // the layout without the stream size: what a persona file restores against + uint64_t compute_persona_layout(bool with_size) const; // pending stream copies that will be applied during the next update stream_copy_info sc_info; diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp index 07d8e3a63c00..6d594a450a53 100644 --- a/src/llama-memory-recurrent.cpp +++ b/src/llama-memory-recurrent.cpp @@ -413,6 +413,17 @@ llama_persona_move llama_memory_recurrent::persona_prepare(llama_persona_blocks blocks.rs_layout = persona_layout(); blocks.rs.r.resize(r_l.size()); blocks.rs.s.resize(s_l.size()); + // the bytes a save copies for a sequence that holds state (persona_check_save), recorded for a file read to check + // before it allocates + const uint32_t n_groups = 1 + n_rs_seq; + blocks.geometry.r_bytes.resize(r_l.size()); + blocks.geometry.s_bytes.resize(s_l.size()); + for (size_t il = 0; il < r_l.size(); ++il) { + blocks.geometry.r_bytes[il] = r_l[il] ? ggml_row_size(r_l[il]->type, r_l[il]->ne[0]) * n_groups : 0; + } + for (size_t il = 0; il < s_l.size(); ++il) { + blocks.geometry.s_bytes[il] = s_l[il] ? ggml_row_size(s_l[il]->type, s_l[il]->ne[0]) * n_groups : 0; + } return llama_persona_move::done; } diff --git a/src/llama-memory.cpp b/src/llama-memory.cpp index 5ccaab986de7..5dca5550cd21 100644 --- a/src/llama-memory.cpp +++ b/src/llama-memory.cpp @@ -79,6 +79,8 @@ const char * llama_persona_move_name(llama_persona_move m) { case llama_persona_move::no_checkpoint: return "no_checkpoint"; case llama_persona_move::checkpoint_ahead: return "checkpoint_ahead"; case llama_persona_move::checkpoint_stale: return "checkpoint_stale"; + case llama_persona_move::io_error: return "io_error"; + case llama_persona_move::file_mismatch: return "file_mismatch"; } return "unknown"; } diff --git a/src/llama-model.cpp b/src/llama-model.cpp index 63fa565e7843..4acda1716bd2 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -38,6 +38,7 @@ #include #include #include +#include #include static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params & params) { @@ -2663,6 +2664,45 @@ ggml_cgraph * llama_model::build_graph(const llm_graph_params & params) const { // TODO: move reranking logic here and generalize llm->build_dense_out(dense_2_out_layers, dense_2_out_layers_b, dense_3_out_layers); + if (params.cparams.embeddings_only) { + if (params.cparams.training || params.cparams.embeddings_nextn || !params.samplers.empty() || + std::any_of(params.cparams.embeddings_layer_inp.begin(), params.cparams.embeddings_layer_inp.end(), [](bool enabled) { return enabled; })) { + throw std::runtime_error("embeddings_only cannot train, sample, or extract auxiliary outputs"); + } + GGML_ASSERT(llm->res->t_embd_pooled != nullptr); + // Cache writes are explicit graph roots, not dependencies of cache reads. + // Preserve those roots and their original ordering when pruning logits. + const auto ancestors = [](ggml_tensor * root) { + std::unordered_set seen; + std::vector pending { root }; + while (!pending.empty()) { + auto * node = pending.back(); + pending.pop_back(); + if (!node || !seen.insert(node).second) { + continue; + } + for (auto * src : node->src) { + pending.push_back(src); + } + } + return seen; + }; + const auto logits = ancestors(llm->res->t_logits); + const auto pooled = ancestors(llm->res->t_embd_pooled); + auto * gf = llm->res->get_gf(); + std::vector roots; + for (int i = 0; i < ggml_graph_n_nodes(gf); ++i) { + auto * node = ggml_graph_node(gf, i); + if (!logits.count(node) || pooled.count(node)) { + roots.push_back(node); + } + } + llm->res->t_logits = nullptr; + ggml_graph_clear(gf); + for (auto * root : roots) { + ggml_build_forward_expand(gf, root); + } + } llm->res->set_outputs(params); return llm->res->get_gf(); @@ -3063,6 +3103,18 @@ size_t llama_model_n_weight_backends(const llama_model * model) { return llama_model_weight_backends(model).size(); } +llama_weight_allocation llama_model_weight_allocation(const llama_model * model) { + llama_weight_allocation allocation = {}; + for (const auto & [buft, bytes] : model->memory_breakdown()) { + if (ggml_backend_buft_is_host(buft)) { + allocation.host += bytes; + } else { + allocation.device += bytes; + } + } + return allocation; +} + const char * llama_model_weight_backend_name(const llama_model * model, size_t i) { const auto v = llama_model_weight_backends(model); return i < v.size() ? v[i].first : nullptr; diff --git a/src/llama-persona-blocks.h b/src/llama-persona-blocks.h index c80e8ca05900..81f921a3167a 100644 --- a/src/llama-persona-blocks.h +++ b/src/llama-persona-blocks.h @@ -32,6 +32,16 @@ struct llama_rs_seq_blocks { std::vector> s; // per layer: (1 + n_rs_seq) rows of s, group-major }; +// the byte geometry of this memory's rows, recorded once by persona_prepare from the memory's own tensors: a read of her +// file checks every length against it BEFORE allocating, so a truncated or foreign file is refused without sizing any +// buffer from what the file claims (Codex on CambrianTech/llama.cpp#155) +struct llama_persona_geometry { + std::vector k_row; // per KV layer: bytes of one K row + std::vector v_row; // per KV layer: bytes of one V row (0 for a layer without V) + std::vector r_bytes; // per recurrent layer: bytes of her r rows in every snapshot group (0 without r) + std::vector s_bytes; // per recurrent layer: bytes of her s rows in every snapshot group (0 without s) +}; + // 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. @@ -52,7 +62,11 @@ struct llama_persona_blocks { return !owned || (owner == who.persona && owner_epoch == who.epoch); } uint64_t kv_layout = 0; + // the attention layout without the stream size (layers, row types and widths): a file restores her into any stream of + // this memory that holds her rows, whatever window a restart's planner chose (CONTINUUM-ENGINE 4.16) + uint64_t kv_rows = 0; uint64_t rs_layout = 0; + llama_persona_geometry geometry; llama_kv_stream_blocks kv; llama_rs_seq_blocks rs; }; @@ -85,6 +99,8 @@ enum class llama_persona_move { no_checkpoint, // a rewind was asked of a checkpoint never taken checkpoint_ahead, // a rewind was asked to a position past what she holds: a rewind never moves forward checkpoint_stale, // her cells are not the lineage the checkpoint was taken from, or were cut at or below it since + io_error, // her blocks' file could not be written or read whole + file_mismatch, // her blocks' file is not hers or not this memory's (owner, epoch, layout, sizes): nothing was read }; // A copy of a bound persona at one of her positions, taken WITHOUT moving her: her recurrent rows (every snapshot diff --git a/src/llama-persona-file.cpp b/src/llama-persona-file.cpp new file mode 100644 index 000000000000..da03d9950e82 --- /dev/null +++ b/src/llama-persona-file.cpp @@ -0,0 +1,251 @@ +// Continuum fork (CONTINUUM-ENGINE 4.16, "restore is the norm"): a persona's saved blocks on disk and back, so a restart +// demotes her instead of dropping her. The file holds what a move already copies (her K/V rows per layer, her occupied +// cells, her recurrent rows) plus who she is and the memory layout they were taken from. Nothing is re-serialized or +// recomputed: rows are written and read as bytes. +// +// A write goes to `.tmp` and is renamed into place, so a crash mid-write never leaves a torn file that reads as +// hers; the rename replaces an existing file on every platform (POSIX rename, Windows MoveFileEx). A read checks every +// layer length against the geometry her preparation recorded before it allocates, fills temporaries, and commits them to +// her blocks only when every check passed (owner, epoch, both layout +// fingerprints, layer and cell counts, a complete read), so a refused read leaves her as she was. + +#include "llama.h" +#include "llama-persona.h" + +#include +#ifdef _WIN32 +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# ifndef NOMINMAX +# define NOMINMAX +# endif +# include +#endif +#include +#include + +namespace { + +constexpr uint32_t MAGIC = 0x31425043; // "CPB1" +constexpr uint32_t VERSION = 1; + +struct writer { + std::FILE * f; + bool ok = true; + template void put(const T & v) { ok = ok && std::fwrite(&v, sizeof(T), 1, f) == 1; } + void bytes(const std::vector & b) { + put(b.size()); + ok = ok && (b.empty() || std::fwrite(b.data(), 1, b.size(), f) == b.size()); + } + void rows(const std::vector> & layers) { + put((uint32_t) layers.size()); + for (const auto & layer : layers) { + bytes(layer); + } + } +}; + +struct reader { + std::FILE * f; + bool ok = true; + template T get() { + T v{}; + ok = ok && std::fread(&v, sizeof(T), 1, f) == 1; + return v; + } + // one layer's bytes, refused unless the file says exactly `expect` (from this memory's geometry): no buffer is ever + // sized from a length the file claims, so a truncated or foreign file allocates nothing (Codex on #155) + bool bytes(std::vector & out, size_t expect) { + const uint64_t n = get(); + if (!ok || n != expect) { + return false; + } + out.resize(n); + ok = n == 0 || std::fread(out.data(), 1, n, f) == n; + return ok; + } + // every layer, each the length `expect` names; a file with another layer count is not this memory's + bool rows(std::vector> & out, const std::vector & expect) { + const uint32_t n = get(); + if (!ok || n != expect.size()) { + return false; + } + out.resize(n); + for (uint32_t i = 0; i < n; ++i) { + if (!bytes(out[i], expect[i])) { + return false; + } + } + return ok; + } +}; + +// Replace `path` with the finished `tmp` in one step. POSIX rename replaces an existing destination; the Windows CRT's +// refuses one (Codex on #155, UCRT on BigMama: -1 with the old body intact), so a second save to her fixed path failed. +bool replace_file(const std::string & tmp, const char * path) { +#ifdef _WIN32 + return MoveFileExA(tmp.c_str(), path, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != 0; +#else + return std::rename(tmp.c_str(), path) == 0; +#endif +} + +struct closes { + std::FILE * f; + ~closes() { if (f) { std::fclose(f); } } +}; + +} // namespace + +int32_t llama_persona_write_file(const llama_persona * persona, const char * path) { + const auto & b = persona->blocks; + if (!b.owned) { + return (int32_t) llama_persona_move::file_mismatch; // never saved: these blocks hold nothing of hers to write + } + const std::string tmp = std::string(path) + ".tmp"; + std::FILE * f = std::fopen(tmp.c_str(), "wb"); + if (f == nullptr) { + return (int32_t) llama_persona_move::io_error; + } + writer w { f }; + w.put(MAGIC); + w.put(VERSION); + w.put(b.owner); + w.put(b.owner_epoch); + w.put(b.seq); + w.put(b.kv_rows); // not the stream size: a restart's window may differ + w.put(b.rs_layout); + // attention: her rows, then her occupied cells (position, 2D extension, whether her sequence holds it) + w.put(b.kv.n_rows); + w.rows(b.kv.k); + w.rows(b.kv.v); + const uint32_t n_cells = b.kv.cells.size(); + w.put(n_cells); + uint32_t occupied = 0; + for (uint32_t i = 0; i < n_cells; ++i) { + occupied += b.kv.cells.is_empty(i) ? 0 : 1; + } + w.put(occupied); + for (uint32_t i = 0; i < n_cells; ++i) { + if (b.kv.cells.is_empty(i)) { + continue; + } + const auto & ext = b.kv.cells.ext_get(i); + w.put(i); + w.put(b.kv.cells.pos_get(i)); + w.put(ext.x); + w.put(ext.y); + w.put(b.seq >= 0 && b.kv.cells.seq_has(i, b.seq) ? 1 : 0); + } + // recurrent: her rows in every snapshot group and her cell's record + w.put(b.rs.has_state ? 1 : 0); + w.put(b.rs.pos); + w.put(b.rs.rs_idx); + w.rows(b.rs.r); + w.rows(b.rs.s); + const bool flushed = w.ok && std::fflush(f) == 0; + const bool closed = std::fclose(f) == 0; + if (!flushed || !closed || !replace_file(tmp, path)) { + std::remove(tmp.c_str()); + return (int32_t) llama_persona_move::io_error; + } + return (int32_t) llama_persona_move::done; +} + +int32_t llama_persona_read_file(llama_persona * persona, const char * path) { + auto & b = persona->blocks; + std::FILE * f = std::fopen(path, "rb"); + if (f == nullptr) { + return (int32_t) llama_persona_move::io_error; + } + closes guard { f }; + reader r { f }; + const auto mismatch = (int32_t) llama_persona_move::file_mismatch; + if (r.get() != MAGIC || r.get() != VERSION || !r.ok) { + return r.ok ? mismatch : (int32_t) llama_persona_move::io_error; + } + const uint64_t owner = r.get(); + const uint64_t epoch = r.get(); + const int32_t seq = r.get(); + if (!r.ok) { + return (int32_t) llama_persona_move::io_error; + } + // hers only: the persona and epoch her token history names (the identity every move checks) + if (owner != persona->tokens->persona() || epoch != persona->tokens->epoch()) { + return mismatch; + } + // this memory's rows only: the row format (layers, types, widths) and the recurrent layout her prepared blocks carry; + // the stream size may differ, and she fits when her rows and every cell she occupies are inside this stream + if (r.get() != b.kv_rows || r.get() != b.rs_layout || !r.ok) { + return r.ok ? mismatch : (int32_t) llama_persona_move::io_error; + } + const uint32_t stream_cells = b.kv.cells.size(); + const uint32_t n_rows = r.get(); + if (r.ok && n_rows > stream_cells) { + return mismatch; // she holds more than this stream: it never fits her + } + // every length the file may hold, from this memory's geometry (persona_prepare), before anything is read into memory + const auto & g = b.geometry; + std::vector k_bytes(g.k_row.size()), v_bytes(g.v_row.size()); + for (size_t i = 0; i < g.k_row.size(); ++i) { + k_bytes[i] = g.k_row[i] * n_rows; + } + for (size_t i = 0; i < g.v_row.size(); ++i) { + v_bytes[i] = g.v_row[i] * n_rows; + } + std::vector> k, v, rs_r, rs_s; + if (!r.ok || !r.rows(k, k_bytes) || !r.rows(v, v_bytes)) { + return r.ok ? mismatch : (int32_t) llama_persona_move::io_error; + } + const uint32_t n_cells = r.get(); + const uint32_t occupied = r.get(); + if (!r.ok || occupied > n_cells || occupied > stream_cells) { + return r.ok ? mismatch : (int32_t) llama_persona_move::io_error; + } + struct cell { uint32_t i; llama_pos pos; llama_kv_cell_ext ext; bool hers; }; + std::vector cells(occupied); + for (auto & c : cells) { + c.i = r.get(); + c.pos = r.get(); + c.ext.x = r.get(); + c.ext.y = r.get(); + c.hers = r.get() != 0; + if (r.ok && c.i >= stream_cells) { + return mismatch; + } + } + const bool has_state = r.get() != 0; + const llama_pos rs_pos = r.get(); + const uint32_t rs_idx = r.get(); + // her recurrent rows are whole when she held state and absent when she did not (persona_check_save) + const std::vector r_bytes = has_state ? g.r_bytes : std::vector(g.r_bytes.size(), 0); + const std::vector s_bytes = has_state ? g.s_bytes : std::vector(g.s_bytes.size(), 0); + if (!r.ok || !r.rows(rs_r, r_bytes) || !r.rows(rs_s, s_bytes)) { + return r.ok ? mismatch : (int32_t) llama_persona_move::io_error; + } + // every check passed: commit. Her cells start from the empty, stream-sized object her preparation made. + llama_kv_cells restored; + restored.resize(stream_cells); + for (const auto & c : cells) { + restored.pos_set(c.i, c.pos); + restored.ext_set(c.i, c.ext); + if (c.hers) { + restored.seq_add(c.i, seq); + } + } + b.kv.n_rows = n_rows; + b.kv.k.swap(k); + b.kv.v.swap(v); + b.kv.cells.swap(restored); + b.rs.has_state = has_state; + b.rs.pos = rs_pos; + b.rs.rs_idx = rs_idx; + b.rs.r.swap(rs_r); + b.rs.s.swap(rs_s); + b.seq = seq; + b.owned = true; + b.owner = owner; + b.owner_epoch = epoch; + return (int32_t) llama_persona_move::done; +} diff --git a/src/llama-persona.h b/src/llama-persona.h new file mode 100644 index 000000000000..4b475219d721 --- /dev/null +++ b/src/llama-persona.h @@ -0,0 +1,15 @@ +#pragma once + +// Continuum fork (CONTINUUM-ENGINE 4.14): one persona, the object behind the public `llama_persona *`: her blocks (her +// execution state out of the memory pool) and her token history. Its moves are in llama-context.cpp; its files (her +// blocks on disk, for a restart that demotes instead of dropping her, 4.16) are in llama-persona-file.cpp. + +#include "llama-persona-blocks.h" +#include "llama-persona-tokens.h" + +#include + +struct llama_persona { + llama_persona_blocks blocks; + std::unique_ptr tokens; // her token history, beside her blocks (llama-persona-tokens.h) +}; diff --git a/tests/test-persona-blocks.cpp b/tests/test-persona-blocks.cpp index a59a46a8a191..f22e24f9ff2e 100644 --- a/tests/test-persona-blocks.cpp +++ b/tests/test-persona-blocks.cpp @@ -23,6 +23,9 @@ #include #include #include +#include +#include +#include #include // allocation fault injection: while armed, every allocation in this process throws std::bad_alloc @@ -436,15 +439,30 @@ int main(int argc, char ** argv) { // what this catches (Codex on #153 at 12a98779b): a newer take erasing the cut receipt an older checkpoint // needed. Take A, cut below it and refill a different suffix to the same length, take B: A is stale (by its // serial), B still rewinds. + // A hybrid memory cuts its recurrent half only by a checkpoint rewind (a plain seq_rm mid-sequence is refused), + // so the cut below A is a rewind to an earlier checkpoint taken at half her prompt. { llama_persona_checkpoint * newer = llama_persona_checkpoint_init(); - require(newer != nullptr, "a second checkpoint"); + llama_persona_checkpoint * early = llama_persona_checkpoint_init(); + require(newer != nullptr && early != nullptr, "two more checkpoints"); llama_memory_clear(llama_get_memory(f.ctx), true); + const int full = f.n_prompt; + const llama_pos half = full / 2; + f.n_prompt = half; f.prompt(0, 1); + f.n_prompt = full; + require_move(st(llama_persona_checkpoint_take(f.ctx, 0, 0xA, 1, early)), llama_persona_move::done, "checkpoint at half"); + for (llama_pos p = half; p < full; ++p) { + f.decode_one(0, 7 % f.n_vocab, p); + } require_move(st(llama_persona_checkpoint_take(f.ctx, 0, 0xA, 1, cp)), llama_persona_move::done, "checkpoint A"); - const llama_pos half = f.n_prompt / 2; - require(llama_memory_seq_rm(llama_get_memory(f.ctx), 0, half, -1), "cut below A"); - for (llama_pos p = half; p < f.n_prompt; ++p) { + require_move(st(llama_persona_checkpoint_rewind(f.ctx, 0, 0xA, 1, early)), llama_persona_move::checkpoint_stale, "the earlier checkpoint is older than A on her lineage"); + llama_persona_checkpoint_free(early); + f.n_prompt = half; + llama_memory_clear(llama_get_memory(f.ctx), true); + f.prompt(0, 1); + f.n_prompt = full; + for (llama_pos p = half; p < full; ++p) { f.decode_one(0, 11 % f.n_vocab, p); // a different suffix, to the same length } require_move(st(llama_persona_checkpoint_take(f.ctx, 0, 0xA, 1, newer)), llama_persona_move::done, "checkpoint B"); @@ -465,6 +483,55 @@ int main(int argc, char ** argv) { llama_persona_checkpoint_free(cp); } + // 9. what this catches (CONTINUUM-ENGINE 4.16, restore is the norm): a restart that drops a mind. Her saved blocks + // written to a file and read into a fresh persona bind and continue byte-identically; a file read under another + // owner or another epoch of her is refused and leaves that persona as it was (it still binds nothing). + { + auto st = [](int32_t s) { return (llama_persona_move) s; }; + const std::string path = (std::filesystem::temp_directory_path() / "test-persona-blocks-a.cpb").string(); + llama_persona * saved = llama_persona_init(f.ctx, 0xA, 1); + require(saved != nullptr, "a persona to save"); + llama_memory_clear(llama_get_memory(f.ctx), true); + f.prompt(0, 1); + require_move(st(llama_persona_save(f.ctx, 0, saved)), llama_persona_move::done, "a saved"); + require_move(st(llama_persona_write_file(saved, path.c_str())), llama_persona_move::done, "a written to her file"); + // a second save to her fixed path replaces the first (Windows CRT rename refuses an existing destination) + require_move(st(llama_persona_write_file(saved, path.c_str())), llama_persona_move::done, "a written again over her file"); + llama_persona_free(saved); + + llama_persona * other = llama_persona_init(f.ctx, 0xB, 1); + llama_persona * stale = llama_persona_init(f.ctx, 0xA, 2); + llama_persona * back = llama_persona_init(f.ctx, 0xA, 1); + require(other != nullptr && stale != nullptr && back != nullptr, "fresh personas to read into"); + require_move(st(llama_persona_read_file(other, path.c_str())), llama_persona_move::file_mismatch, "another owner's file is refused"); + require_move(st(llama_persona_read_file(stale, path.c_str())), llama_persona_move::file_mismatch, "another epoch of her is refused"); + require_move(st(llama_persona_read_file(back, path.c_str())), llama_persona_move::done, "a read back from her file"); + // a truncated file is refused before anything is sized from it, and leaves the blocks she holds as they were + const std::string cut = path + ".cut"; + std::filesystem::copy_file(path, cut, std::filesystem::copy_options::overwrite_existing); + std::filesystem::resize_file(cut, std::filesystem::file_size(cut) / 2); + const auto refused = st(llama_persona_read_file(back, cut.c_str())); + require(refused == llama_persona_move::io_error || refused == llama_persona_move::file_mismatch, "a truncated file is refused"); + // a length the file claims beyond this memory's geometry (here, its first K layer's, at byte 52: magic, version, + // owner, epoch, seq, row id, recurrent layout, row and layer counts) is refused before any buffer is sized from it + std::filesystem::copy_file(path, cut, std::filesystem::copy_options::overwrite_existing); + { + std::fstream patch(cut, std::ios::in | std::ios::out | std::ios::binary); + const uint64_t huge = UINT64_C(1) << 62; + patch.seekp(52); + patch.write(reinterpret_cast(&huge), sizeof(huge)); + } + require_move(st(llama_persona_read_file(back, cut.c_str())), llama_persona_move::file_mismatch, "a length past the geometry is refused"); + std::remove(cut.c_str()); + llama_memory_clear(llama_get_memory(f.ctx), true); + require_move(st(llama_persona_bind(f.ctx, 0, back)), llama_persona_move::done, "a bound from her file"); + f.require_continues("a continues after a restart from her file", 0, ref_a0); + llama_persona_free(other); + llama_persona_free(stale); + llama_persona_free(back); + std::remove(path.c_str()); + } + fprintf(stderr, "test-persona-blocks: ok (%zu attention layers, %zu recurrent layers)\n", a.kv.k.size(), a.rs.r.size()); return 0; }