diff --git a/common/arg.cpp b/common/arg.cpp index 4353464d2847..95cfa4bfaf06 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -2544,6 +2544,17 @@ common_params_context common_params_parser_init(common_params & params, llama_ex params.n_parallel = value; } ).set_env("LLAMA_ARG_N_PARALLEL").set_examples({LLAMA_EXAMPLE_SERVER})); + add_opt(common_arg( + {"--minds"}, "N", + "continuum: minds the engine keeps resident beside its lanes, each as its own parked sequence of the unified " + "KV pool (a mind switch is a sequence move, never a serialization); the core's resident count, 0 = off", + [](common_params & params, int value) { + if (value < 0) { + throw std::invalid_argument("error: --minds must be >= 0\n"); + } + params.n_minds = value; + } + ).set_env("LLAMA_ARG_MINDS").set_examples({LLAMA_EXAMPLE_SERVER})); } else { add_opt(common_arg( {"-np", "--parallel"}, "N", diff --git a/common/common.cpp b/common/common.cpp index 09fe1b77e3d7..eccd8f0506b8 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -1726,7 +1726,8 @@ struct llama_context_params common_context_params_to_llama(const common_params & auto cparams = llama_context_default_params(); cparams.n_ctx = params.n_ctx; - cparams.n_seq_max = params.n_parallel; + // continuum: every resident mind keeps its own sequence (lanes + parked minds) in the unified pool + cparams.n_seq_max = params.n_parallel + std::max(0, params.n_minds); cparams.n_rs_seq = params.speculative.need_n_rs_seq(); cparams.n_outputs_max = std::max(params.n_outputs_max, 0); cparams.n_outputs_max_per_seq = std::max(params.n_outputs_max_per_seq, 0); diff --git a/common/common.h b/common/common.h index f57bafb83295..495ab6d1a4e7 100644 --- a/common/common.h +++ b/common/common.h @@ -446,6 +446,7 @@ struct common_params { int32_t n_keep = 0; // number of tokens to keep from initial prompt int32_t n_chunks = -1; // max number of chunks to process (-1 = unlimited) int32_t n_parallel = 1; // number of parallel sequences to decode + int32_t n_minds = 0; // continuum: minds kept resident beside the lanes (parked sequences); the core's count int32_t n_sequences = 1; // number of sequences to decode int32_t n_outputs_max = 0; // max outputs in a batch (0 = n_batch) int32_t n_outputs_max_per_seq = 1; // max outputs per sequence @@ -1155,6 +1156,10 @@ enum ggml_opt_optimizer_type common_opt_get_optimizer(const char *); struct common_prompt_checkpoint { int64_t n_tokens; + // continuum: held for a turn the core will learn (its served prompt's end, n_prefix - 1): never evicted or + // superseded until that turn is learned on a side sequence or abandoned + uint64_t pin = 0; // continuum: the learn pin holding it (unique per engine process; 0: not pinned) + // (optional) id of the task that created the checkpoint int id_task = -1; diff --git a/common/speculative.cpp b/common/speculative.cpp index 4b67bbb88599..5de770c9c3a5 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -2343,7 +2343,7 @@ common_params common_base_params_to_speculative(const common_params & params) { result.cache_type_k = params_spec.cache_type_k; result.cache_type_v = params_spec.cache_type_v; - result.n_outputs_max = params.n_parallel; + result.n_outputs_max = params.n_parallel + std::max(0, params.n_minds); // one row per sequence, parked minds included result.n_outputs_max_per_seq = 1; // dflash/dspark decode the whole noise block in a single pass and sample every block position on the backend diff --git a/tests/test-server-checkpoint-policy.cpp b/tests/test-server-checkpoint-policy.cpp index 5943b236654a..73d230d41002 100644 --- a/tests/test-server-checkpoint-policy.cpp +++ b/tests/test-server-checkpoint-policy.cpp @@ -22,6 +22,7 @@ struct ckpt { int64_t n_tokens; int id_task; int serial; // identity: a checkpoint is the same one only if its serial matches + uint64_t pin = 0; // nonzero: held for learning (common.h server_prompt_checkpoint::pin) }; using store = std::list; @@ -51,6 +52,23 @@ static void head_survives_a_full_store_across_many_acts() { } } +// regression for the pin added on #139: a checkpoint pinned for learning is never the victim, and a store whose +// every candidate is pinned yields end() so the caller defers instead of erasing a learner's checkpoint +static void a_pinned_checkpoint_is_never_evicted() { + store s; + for (int i = 0; i < 4; ++i) { + s.push_back({ 9655 + i * 1000, i, i }); + } + s.front().pin = 0; + std::next(s.begin(), 1)->pin = 7; + auto victim = checkpoint_to_evict(s, /*view_end=*/100000); + require(victim != s.end() && victim->pin == 0, "the victim is unpinned"); + for (auto & c : s) { + c.pin = 1 + (uint64_t) c.serial; + } + require(checkpoint_to_evict(s, 100000) == s.end(), "all pinned: no victim"); +} + static void the_pre_fix_rule_loses_the_head() { const size_t capacity = 4; store s; @@ -142,6 +160,7 @@ static void a_cold_prompt_with_view_spans_makes_her_head() { int main() { a_cold_prompt_with_view_spans_makes_her_head(); + a_pinned_checkpoint_is_never_evicted(); head_survives_a_full_store_across_many_acts(); the_pre_fix_rule_loses_the_head(); capacity_one_keeps_only_what_fits(); diff --git a/tools/server/CMakeLists.txt b/tools/server/CMakeLists.txt index 67fb03964d7c..3a409e4f09f9 100644 --- a/tools/server/CMakeLists.txt +++ b/tools/server/CMakeLists.txt @@ -14,6 +14,9 @@ add_library(${TARGET} STATIC server-common.cpp server-common.h server-context.cpp + server-mapped-file.cpp + server-mapped-file.h + server-mind.h server-train.cpp server-context.h server-stream.cpp diff --git a/tools/server/server-checkpoint-policy.h b/tools/server/server-checkpoint-policy.h index df2337bd9514..6b5ccaeec3b7 100644 --- a/tools/server/server-checkpoint-policy.h +++ b/tools/server/server-checkpoint-policy.h @@ -27,12 +27,19 @@ inline bool checkpoint_at_user_start(bool view_spans, bool store_empty, int64_t // The checkpoint to erase to make room for one more. With view spans (view_end >= 0) her head (the // oldest) is her restore point when her next prompt diverges before her view end, so the oldest AFTER // it goes first; the head goes only when it is all there is. Without view spans, the oldest goes. +// A checkpoint pinned for learning is never the victim; end() when every candidate is pinned. template typename List::iterator checkpoint_to_evict(List & checkpoints, int32_t view_end) { auto victim = checkpoints.begin(); if (view_end >= 0 && checkpoints.size() >= 2) { ++victim; } + while (victim != checkpoints.end() && victim->pin != 0) { + ++victim; + } + if (victim == checkpoints.end() && !checkpoints.empty() && checkpoints.front().pin == 0) { + return checkpoints.begin(); // only her head is left unpinned + } return victim; } @@ -48,7 +55,7 @@ size_t erase_superseded_checkpoints(List & checkpoints, const Checkpoint & kept, const auto * head = &checkpoints.front(); size_t erased = 0; for (auto it = checkpoints.begin(); it != checkpoints.end();) { - if (&*it != head && it->id_task != id_task) { + if (&*it != head && it->id_task != id_task && it->pin == 0) { on_erase(*it); it = checkpoints.erase(it); ++erased; diff --git a/tools/server/server-common.cpp b/tools/server/server-common.cpp index eadc271dc706..5c1cd50d1e51 100644 --- a/tools/server/server-common.cpp +++ b/tools/server/server-common.cpp @@ -84,6 +84,22 @@ json server_slot_stats::to_json() const { base["draft_n_accepted"] = n_draft_accepted; } + if (mind_hi != 0 || mind_lo != 0) { + static const char * names[] = { "none", "lane", "parked", "flash", "ram", "new", "adopted", "flash_pool_full" }; + char page[33]; + std::snprintf(page, sizeof(page), "%016llx%016llx", (unsigned long long) mind_hi, (unsigned long long) mind_lo); + base["mind"] = { + {"page", page}, + {"from", names[(size_t) mind_came_from]}, + {"switch_ms", mind_switch_us / 1000.0}, + {"generation", mind_generation}, + }; + if (mind_pin != 0) { + base["mind"]["pin"] = mind_pin; + base["mind"]["pinned_at"] = mind_pinned_at; + } + } + return base; } diff --git a/tools/server/server-common.h b/tools/server/server-common.h index 24bbb7a0bd57..6ea33aa2441c 100644 --- a/tools/server/server-common.h +++ b/tools/server/server-common.h @@ -362,7 +362,19 @@ json format_response_rerank( // // shared between server_slot and server_task_result_* +// Continuum fork: where the mind a request named came from when she took the lane (server-context-minds.inc) +enum class mind_from : uint8_t { none, lane, parked, flash, ram, fresh, adopted, flash_pool_full }; + struct server_slot_stats { + // the switch receipt (a request that named its mind): her page, where her state came from, how long the + // switch took and her state's generation (it advances each time her state moves) + uint64_t mind_hi = 0, mind_lo = 0; + mind_from mind_came_from = mind_from::none; + int64_t mind_switch_us = 0; + uint64_t mind_generation = 0; + uint64_t mind_pin = 0; // learn_pin: the pin's id (what /learn/release takes; unique per engine process) + int64_t mind_pinned_at = -1; // learn_pin: the pinned checkpoint's position (information only) + uint64_t n_prompt_cached = 0; uint64_t n_prompt_processed = 0; uint64_t n_gen = 0; diff --git a/tools/server/server-context-learn.inc b/tools/server/server-context-learn.inc index b39a0789c92d..bb92ec76bd9e 100644 --- a/tools/server/server-context-learn.inc +++ b/tools/server/server-context-learn.inc @@ -308,6 +308,7 @@ if (learning) { learn_outcome out; out.deferred = true; + out.refusal = "busy"; out.failure = "the lane optimizer is restoring an admitted reply; retain this experience for retry"; return out; } @@ -370,8 +371,10 @@ } learn_outcome learn_on_slot_admitted(server_slot & slot, const learn_request & L, int64_t t0) { - auto refused = [&](const std::string & why) { + // `kind` is the typed refusal a caller matches (frozen: see learn_outcome::refusal); `why` is detail only + auto refused = [&](const char * kind, const std::string & why) { learn_outcome out; + out.refusal = kind; out.failure = why; SRV_WRN("learn refused: %s\n", why.c_str()); return out; @@ -379,52 +382,81 @@ // the same refusal /train gives: repacked CPU weights fail the backward (x86) or crash // the copy to Metal (an M5 at -ngl 0), card 5b497852 if (const std::string why = train_repack_refusal(model_tgt, params_base); !why.empty()) { - return refused(why); + return refused("unsupported", why); } auto & loras = params_base.lora_adapters; if (L.lora_id < 0 || (size_t) L.lora_id >= loras.size() || loras[L.lora_id].ptr == nullptr) { - return refused("no loaded adapter " + std::to_string(L.lora_id) + " to train (POST /lora-adapters/load it first)"); + return refused("no_adapter", "no loaded adapter " + std::to_string(L.lora_id) + " to train (POST /lora-adapters/load it first)"); } const int32_t n0 = L.n_prefix - 1; // the last prompt token is re-decoded with the reply's first token as its label if (n0 < 0 || L.n_prefix > slot.prompt.n_tokens() || L.reply.empty()) { - return refused("slot " + std::to_string(slot.id) + " holds " + std::to_string(slot.prompt.n_tokens()) + return refused("prefix_mismatch", "slot " + std::to_string(slot.id) + " holds " + std::to_string(slot.prompt.n_tokens()) + " prompt tokens; the served prefix is " + std::to_string(L.n_prefix) + " and the reply must not be empty"); } // the served prompt, when the request carries it: her slot must still hold exactly it (a // slot that has served other turns since, or compacted, would teach the wrong context) - if (!L.prompt.empty()) { + if (!L.prompt.empty() && !L.side) { // a side sequence builds the served prompt itself (below) int32_t i = 0; while (i < L.n_prefix && slot.prompt.tokens[i] == L.prompt[i]) { ++i; } if (i < L.n_prefix) { - return refused("slot " + std::to_string(slot.id) + " no longer holds this turn's prompt (it differs at token " + return refused("prefix_mismatch", "slot " + std::to_string(slot.id) + " no longer holds this turn's prompt (it differs at token " + std::to_string(i) + " of " + std::to_string(L.n_prefix) + "): serve the prompt again, then learn"); } } // the recurrent part cannot be cut back: her state one token before the prompt's end const common_prompt_checkpoint * cp = nullptr; const bool needs_cp = ctx_tgt_seq_rm_type == COMMON_CONTEXT_SEQ_RM_TYPE_FULL || ctx_tgt_seq_rm_type == COMMON_CONTEXT_SEQ_RM_TYPE_RS; - if (needs_cp) { + // a side sequence: from the longest prefix her slot shares with the served prompt, back to the latest + // checkpoint at or before it; the served prompt's own tokens from there to n0 are decoded on the side + int32_t side_from = n0; + if (L.side) { + if (L.prompt.size() < (size_t) L.n_prefix) { + return refused("no_messages", "a side-sequence learn needs the served prompt's tokens (messages)"); + } + int32_t lcp = 0; + while (lcp < n0 && lcp < (int32_t) slot.prompt.n_tokens() && slot.prompt.tokens[lcp] == L.prompt[lcp]) { + ++lcp; + } + side_from = needs_cp ? -1 : lcp; + if (needs_cp) { + for (const auto & c : slot.prompt.checkpoints) { + if (c.n_tokens <= lcp && (cp == nullptr || c.n_tokens > cp->n_tokens)) { + cp = &c; + } + } + if (cp == nullptr) { + return refused("no_checkpoint", "slot " + std::to_string(slot.id) + " has no checkpoint at or before the " + std::to_string(lcp) + + " tokens it shares with this turn's prompt: no side sequence can be built"); + } + side_from = (int32_t) cp->n_tokens; + } + } + if (needs_cp && !L.side) { for (const auto & c : slot.prompt.checkpoints) { if (c.n_tokens == n0) { cp = &c; } } if (cp == nullptr) { - return refused("slot " + std::to_string(slot.id) + " has no checkpoint one token before its prompt's end (" + return refused("no_checkpoint", "slot " + std::to_string(slot.id) + " has no checkpoint one token before its prompt's end (" + std::to_string(n0) + "): the lane learns only with --train-dir, which keeps one"); } } + // a side sequence: her own sequence is never touched (refused, typed, before anything is changed) + if (L.side && park_free.empty()) { + return refused("no_side_sequence", "no side sequence is free to learn on (launch with --minds; every parked id holds a mind)"); + } // the tokens from the last prompt token on, each labelled with the next std::vector toks; - toks.push_back(slot.prompt.tokens[n0]); + toks.push_back(L.side ? L.prompt[n0] : slot.prompt.tokens[n0]); // the served prompt's last token toks.insert(toks.end(), L.reply.begin(), L.reply.end()); std::vector labels(toks.size(), -1); for (size_t i = 0; i + 1 < toks.size(); ++i) { labels[i] = toks[i + 1]; } - if (const auto why = admit_learning_residency(L); !why.empty()) { return refused(why); } + if (const auto why = admit_learning_residency(L); !why.empty()) { return refused("residency", why); } // her stable set plus the shadow: the shadow applies to labelled rows only std::vector set = slot.lora.empty() ? construct_lora_list({}) : slot.lora; if ((size_t) L.lora_id >= set.size()) { @@ -436,20 +468,57 @@ if (!select_learning_shadow(L.lora_id)) { common_set_adapter_lora(ctx_tgt, slot.lora); settle_learning_residency(L.lora_id); - return refused("adapter " + std::to_string(L.lora_id) + " cannot be trained: " + llama_opt_failure(ctx_tgt)); - } - // drop what follows n0 (attention) and put her recurrent state back at n0 - if (cp != nullptr) { - cp->load_tgt(ctx_tgt, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); + return refused("unsupported", "adapter " + std::to_string(L.lora_id) + " cannot be trained: " + llama_opt_failure(ctx_tgt)); } const auto & served_tokens = slot.prompt.tokens.get_tokens(); ggml_opt_result_t result = ggml_opt_result_init(); - const bool begun = llama_opt_learn_begin(ctx_tgt, slot.id, n0, toks.data(), labels.data(), (int32_t) toks.size(), - served_tokens.data() + n0, (int32_t) served_tokens.size() - n0, result); + llama_seq_id learn_seq = slot.id; + int32_t n_restore = (int32_t) served_tokens.size() - n0; + if (L.side) { + // her shared prefix [0, side_from) re-tagged onto a side sequence (attention cells, nothing copied), + // the checkpoint's recurrent state loaded there, then the served prompt's own tokens [side_from, n0) + // decoded on it; the learn's own restore re-decodes one token there. Her sequence is never touched. + learn_seq = park_free.back(); + park_free.pop_back(); + llama_memory_seq_rm(llama_get_memory(ctx_tgt), learn_seq, -1, -1); + llama_memory_seq_cp(llama_get_memory(ctx_tgt), slot.id, learn_seq, 0, side_from); + if (cp != nullptr) { + cp->load_tgt(ctx_tgt, learn_seq, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); + } + // the served prompt's own tokens [side_from, n0), decoded in batches the context accepts + const int32_t chunk = (int32_t) llama_n_batch(ctx_tgt); + int rc = 0; + for (int32_t at = side_from; at < n0 && rc == 0; at += chunk) { + const int32_t n = std::min(chunk, n0 - at); + llama_batch b = llama_batch_init(n, 0, 1); + for (int32_t i = at; i < at + n; ++i) { + common_batch_add(b, L.prompt[i], i, { learn_seq }, false); + } + rc = llama_decode(ctx_tgt, b); + llama_batch_free(b); + } + if (rc != 0) { + llama_memory_seq_rm(llama_get_memory(ctx_tgt), learn_seq, -1, -1); + park_free.push_back(learn_seq); + ggml_opt_result_free(result); + common_set_adapter_lora(ctx_tgt, slot.lora); + settle_learning_residency(L.lora_id); + return refused("replay_failed", "the served prompt's last " + std::to_string(n0 - side_from) + + " tokens could not be decoded on the side sequence"); + } + n_restore = 1; + } else if (cp != nullptr) { + // drop what follows n0 (attention) and put her recurrent state back at n0 + cp->load_tgt(ctx_tgt, learn_seq, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); + } + const llama_token * restore = L.side ? L.prompt.data() + n0 : served_tokens.data() + n0; + const bool begun = llama_opt_learn_begin(ctx_tgt, learn_seq, n0, toks.data(), labels.data(), (int32_t) toks.size(), + restore, n_restore, result); common_set_adapter_lora(ctx_tgt, slot.lora); learning = std::make_unique(&slot, cp, std::move(set), result, toks[0], L.n_prefix, (int32_t) toks.size() - 1, loras[L.lora_id].ptr, t0); learning->began = begun; + learning->side = L.side ? learn_seq : -1; learning->grant = L.grant; learning->lora_id = L.lora_id; if (!begun) { @@ -538,7 +607,10 @@ } if (status != LLAMA_OPT_LEARN_MORE) { pending.finished = status == LLAMA_OPT_LEARN_DONE; - if (status != LLAMA_OPT_LEARN_DONE) { pending.failure = llama_opt_failure(ctx_tgt); } + if (status != LLAMA_OPT_LEARN_DONE) { + pending.refusal = "optimizer_failed"; + pending.failure = llama_opt_failure(ctx_tgt); + } } // Even the final chunk yields before the last prompt token is restored below. return; @@ -556,7 +628,19 @@ // The native owner restored the exact served tail once (not the supplied correction). // Target KV, token metadata and the untouched draft therefore still name the same tail. // If begin refused after loading the recurrent prefix, retain only that proven prefix. - if (!pending.began || !ok) { + if (pending.side >= 0) { + // learned on a side sequence: it goes, her own sequence was never touched. The pin is released only + // when the learn committed; an abandoned or failed one keeps it, so a retry still finds it. + llama_memory_seq_rm(llama_get_memory(ctx_tgt), pending.side, -1, -1); + park_free.push_back(pending.side); + if (pending.began && ok && !pending.drained) { + for (auto & c : slot.prompt.checkpoints) { + if (c.pin != 0 && c.n_tokens == n0) { + c.pin = 0; + } + } + } + } else if (!pending.began || !ok) { llama_memory_seq_rm(llama_get_memory(ctx_tgt), slot.id, n0, -1); if (cp) { cp->load_tgt(ctx_tgt, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); } if (ctx_dft) { @@ -567,6 +651,8 @@ slot.prompt.checkpoints.remove_if([&](const common_prompt_checkpoint & c) { return c.n_tokens > n0; }); } learn_outcome out; + out.learned_on = pending.side >= 0 ? learn_outcome::learned_on_kind::side_sequence : learn_outcome::learned_on_kind::slot; + out.live_sequence_preserved = pending.side >= 0; // the slot path cut her sequence back to the learned prefix out.ok = ok && !pending.drained; out.refusal = pending.refusal; out.deferred = pending.drained; diff --git a/tools/server/server-context-minds.inc b/tools/server/server-context-minds.inc new file mode 100644 index 000000000000..925687c0aab2 --- /dev/null +++ b/tools/server/server-context-minds.inc @@ -0,0 +1,470 @@ +// Methods of server_context_impl: resident minds and the switch between them (server-mind.h). +// +// Every mind the core names has exactly one home: +// lane her sequence is a slot's (she decodes); +// parked her sequence is one of the pool's parked ids (unified memory: on an M5 the same physical memory the +// GPU reads; nothing copied, her attention cells re-tagged and her recurrent state moved by id); +// flash her sequence was copied out of the pool (a memcpy inside unified memory), its cells freed at once, +// and the bytes written to her page file by the page-IO worker, off the decode thread. +// A switch moves her between homes; it never serializes her into a cache, never drops her, never truncates her. +// The pool runs out of CELLS, not of minds: when a decode finds no room, the coldest parked mind goes to flash +// (was: the idle slot's mind was purged). A mind on flash comes back by mapping her file and inserting it. + + struct resident_mind { + mind_page page; + server_prompt prompt; // her tokens, checkpoints and view end (host bookkeeping) + std::vector lora; + uint64_t last_use = 0; + uint64_t generation = 0; // advances each time her state moves + int32_t seq = -1; // parked: the pool sequence id; flash: -1 + std::string file; // flash: her page file + // her bytes in RAM, held by this record (never by the worker alone) until her file has landed: while the + // write is in flight, or after it failed, she lives here and is inserted from here, never lost + std::shared_ptr> ram; + std::shared_ptr> written; // 0 pending, 1 landed, -1 failed + std::vector released; // pins released while she was on flash + }; + + // release learn pin `pin` in `cks`; true when a checkpoint held it + static bool unpin(std::list & cks, uint64_t pin) { + for (auto & c : cks) { + if (c.pin == pin) { + c.pin = 0; + return true; + } + } + return false; + } + + // An abandoned turn's learn pin, released wherever she is: on a lane, parked, or on flash (applied when her + // checkpoints come back). The checkpoint stays as an ordinary one: the budget may now evict it. + pin_release learn_release(mind_page page, uint64_t pin) { + for (auto & s : slots) { + if (s.page == page) { + return unpin(s.prompt.checkpoints, pin) ? pin_release::released : pin_release::not_pinned; + } + } + resident_mind * m = find_mind(page); + if (m == nullptr) { + return pin_release::unknown_mind; + } + if (!m->file.empty() || m->ram) { + m->released.push_back(pin); // her checkpoints are in her flash bytes + return pin_release::released_on_flash; + } + return unpin(m->prompt.checkpoints, pin) ? pin_release::released : pin_release::not_pinned; + } + + // her checkpoints as bytes beside her state: count, then per checkpoint its position fields, three sizes and + // the three blobs (target, draft, speculative state) + static constexpr size_t ckpt_header_bytes = sizeof(int64_t) + 3 * sizeof(int32_t) + 4 * sizeof(uint64_t); + + static void ckpt_write(const std::list & cks, uint8_t * w) { + auto put = [&](const void * p, size_t n) { std::memcpy(w, p, n); w += n; }; + const uint64_t count = cks.size(); + put(&count, sizeof(count)); + for (const auto & c : cks) { + const int32_t id = c.id_task, mn = c.pos_min, mx = c.pos_max; + const uint64_t pin = c.pin; + const uint64_t a = c.data_tgt.size(), b = c.data_dft.size(), d = c.data_spec.size(); + put(&c.n_tokens, sizeof(c.n_tokens)); put(&id, 4); put(&mn, 4); put(&mx, 4); put(&pin, 8); + put(&a, 8); put(&b, 8); put(&d, 8); + put(c.data_tgt.data(), a); put(c.data_dft.data(), b); put(c.data_spec.data(), d); + } + } + + // whether lengths `lens`, taken in order, fit within `room` bytes: each is checked against what is left, so no + // sum is formed and a corrupt or crafted length cannot wrap past 2^64 into a "fitting" total (Codex on #139) + static bool lengths_fit(uint64_t room, std::initializer_list lens) { + for (const uint64_t n : lens) { + if (n > room) { + return false; + } + room -= n; + } + return true; + } + + static bool ckpt_read(const uint8_t * r, uint64_t n, std::list & out) { + const uint8_t * end = r + n; + auto get = [&](void * p, size_t k) { if ((size_t) (end - r) < k) { return false; } std::memcpy(p, r, k); r += k; return true; }; + uint64_t count = 0; + if (!get(&count, sizeof(count))) { + return false; + } + for (uint64_t i = 0; i < count; ++i) { + common_prompt_checkpoint c; + int32_t id, mn, mx; uint64_t pin, a, b, d; + if (!get(&c.n_tokens, sizeof(c.n_tokens)) || !get(&id, 4) || !get(&mn, 4) || !get(&mx, 4) || !get(&pin, 8) || + !get(&a, 8) || !get(&b, 8) || !get(&d, 8) || !lengths_fit((uint64_t) (end - r), { a, b, d })) { + return false; + } + c.id_task = id; c.pos_min = mn; c.pos_max = mx; c.pin = pin; + c.data_tgt.assign(r, r + a); r += a; + c.data_dft.assign(r, r + b); r += b; + c.data_spec.assign(r, r + d); r += d; + out.push_back(std::move(c)); + } + return r == end; + } + + std::vector park_free; // free parked sequence ids (sized once at load) + std::vector minds; // parked and flashed minds (reserved once at load) + uint64_t mind_clock = 0; + uint64_t learn_pin_clock = 0; // learn pins issued by this process (a pin's id; 0 is none) + + // At load: the parked ids are what the context reports beyond the lanes (llama_n_seq_max), never assumed. + bool minds_init() { + const int32_t n_seq = (int32_t) llama_n_seq_max(ctx_tgt); + const int32_t n_lane = params_base.n_parallel; + if (params_base.n_minds <= 0) { + return true; + } + if (!params_base.kv_unified) { + SRV_ERR("%s", "--minds needs --kv-unified: a parked mind shares the pool's cells by sequence id\n"); + return false; + } + if (params_base.slot_save_path.empty()) { + SRV_ERR("%s", "--minds needs --slot-save-path: a mind the pool cannot hold goes to flash, never dropped\n"); + return false; + } + for (int32_t s = n_seq - 1; s >= n_lane; --s) { + park_free.push_back(s); + } + minds.reserve((size_t) params_base.n_minds * 2); + SRV_INF("resident minds: %d lanes, %zu parked sequence ids (context reports %d), flash at %s\n", + n_lane, park_free.size(), n_seq, params_base.slot_save_path.c_str()); + return true; + } + + bool minds_on() const { return !park_free.empty() || !minds.empty(); } + + resident_mind * find_mind(mind_page page) { + for (auto & m : minds) { + if (m.page == page) { + return &m; + } + } + return nullptr; + } + + void seq_move(llama_seq_id from, llama_seq_id to) { + llama_memory_seq_rm(llama_get_memory(ctx_tgt), to, -1, -1); + llama_memory_seq_cp(llama_get_memory(ctx_tgt), from, to, -1, -1); + llama_memory_seq_rm(llama_get_memory(ctx_tgt), from, -1, -1); + if (ctx_dft) { + llama_memory_seq_rm(llama_get_memory(ctx_dft), to, -1, -1); + llama_memory_seq_cp(llama_get_memory(ctx_dft), from, to, -1, -1); + llama_memory_seq_rm(llama_get_memory(ctx_dft), from, -1, -1); + } + } + + std::string mind_file(mind_page page) const { + char name[64]; + std::snprintf(name, sizeof(name), "mind-%016llx%016llx.bin", (unsigned long long) page.hi, (unsigned long long) page.lo); + return params_base.slot_save_path + name; + } + + // The coldest parked mind leaves the pool for flash. False: nothing is parked. + bool flash_coldest() { + resident_mind * cold = nullptr; + for (auto & m : minds) { + if (m.seq >= 0 && (cold == nullptr || m.last_use < cold->last_use)) { + cold = &m; + } + } + if (cold == nullptr) { + return false; + } + const llama_seq_id seq = cold->seq; + if (!flash_out(*cold, seq)) { + return false; + } + park_free.push_back(seq); + return true; + } + + // Mind `m`'s state in sequence `seq` leaves the pool for flash: copied out (unified memory, a memcpy), the + // sequence's cells freed now, the bytes written by the page-IO worker off the decode thread. + bool flash_out(resident_mind & m, llama_seq_id seq) { + resident_mind * cold = &m; + const int64_t t0 = ggml_time_us(); + auto bytes = std::make_shared>(); + const size_t n_tgt = llama_state_seq_get_size_ext(ctx_tgt, seq, LLAMA_STATE_SEQ_FLAGS_NONE); + const size_t n_dft = ctx_dft ? llama_state_seq_get_size_ext(ctx_dft, seq, LLAMA_STATE_SEQ_FLAGS_NONE) : 0; + // her checkpoints go down with her (they are host bytes too: ~100 MB each on a 35B hybrid) + size_t n_ck = sizeof(uint64_t); + for (const auto & c : cold->prompt.checkpoints) { + n_ck += ckpt_header_bytes + c.data_tgt.size() + c.data_dft.size() + c.data_spec.size(); + } + // admitted before it is allocated: her checkpoints are host bytes already counted, so what this copy adds is + // her state and the header; over the host budget she is not copied out and stays where she is (Codex on #139) + const size_t adds = 3 * sizeof(uint64_t) + n_tgt + n_dft; + if (host_budget > 0 && checkpoint_bytes(true) + adds > host_budget) { + SRV_WRN("mind %016llx: copying her out would exceed the host budget (%zu + %zu > %zu); she stays where she is\n", + (unsigned long long) cold->page.hi, checkpoint_bytes(true), adds, host_budget); + return false; + } + bytes->resize(3 * sizeof(uint64_t) + n_tgt + n_dft + n_ck); + uint8_t * w = bytes->data(); + const uint64_t h[3] = { n_tgt, n_dft, n_ck }; + std::memcpy(w, h, sizeof(h)); + w += sizeof(h); + ckpt_write(cold->prompt.checkpoints, w + n_tgt + n_dft); + if (llama_state_seq_get_data_ext(ctx_tgt, w, n_tgt, seq, LLAMA_STATE_SEQ_FLAGS_NONE) != n_tgt || + (ctx_dft && llama_state_seq_get_data_ext(ctx_dft, w + n_tgt, n_dft, seq, LLAMA_STATE_SEQ_FLAGS_NONE) != n_dft)) { + SRV_ERR("mind %016llx: her state could not be copied out of the pool; she stays where she is\n", (unsigned long long) cold->page.hi); + return false; + } + const int64_t t_copy = ggml_time_us() - t0; + std::list().swap(cold->prompt.checkpoints); // their bytes are in hers now + llama_memory_seq_rm(llama_get_memory(ctx_tgt), seq, -1, -1); + if (ctx_dft) { + llama_memory_seq_rm(llama_get_memory(ctx_dft), seq, -1, -1); + } + cold->seq = -1; + cold->file = mind_file(cold->page); + cold->ram = bytes; // the record holds her bytes until her file has landed + cold->written = std::make_shared>(0); + flash_write(*cold); + SRV_INF("mind %016llx%016llx out of the pool: %.1f MiB copied out in %.2f ms, cells freed; held in RAM until written\n", + (unsigned long long) cold->page.hi, (unsigned long long) cold->page.lo, + bytes->size() / (1024.0 * 1024.0), t_copy / 1000.0); + return true; + } + + // Her bytes to her file on the page-IO worker; the worker shares them, the record keeps them. + void flash_write(resident_mind & m) { + const std::string path = m.file; + auto bytes = m.ram; + auto done = m.written; + done->store(0, std::memory_order_release); + page_io->submit(path, [path, bytes, done] { + FILE * f = std::fopen(path.c_str(), "wb"); + bool ok = f != nullptr && std::fwrite(bytes->data(), 1, bytes->size(), f) == bytes->size(); + ok = (f != nullptr && std::fclose(f) == 0) && ok; + done->store(ok ? 1 : -1, std::memory_order_release); + }); + } + + // Between steps: a landed file releases her RAM copy; a failed write keeps it (she lives in RAM) and is + // written again. Never waits. + void minds_reap() { + for (auto & m : minds) { + if (!m.ram || !m.written) { + continue; + } + const int st = m.written->load(std::memory_order_acquire); + if (st == 1) { + m.ram.reset(); + } else if (st == -1) { + // she lives in RAM (never lost); the write is not retried every step against a failing disk: her + // next trip out of a lane writes her again + SRV_WRN("mind %016llx%016llx: her flash write failed; she stays in RAM\n", + (unsigned long long) m.page.hi, (unsigned long long) m.page.lo); + m.written.reset(); + } + } + } + + // Her bytes back into `seq`, from where they are: RAM while her write is in flight or failed (never a wait on + // the disk), else her file mapped and inserted directly (no read into a buffer first). + bool flash_insert(resident_mind & m, llama_seq_id seq) { + const int64_t t0 = ggml_time_us(); + std::unique_ptr map; + auto ram = m.ram; // held for the insert even if the write lands meanwhile + const uint8_t * base = nullptr; + size_t size = 0; + if (ram) { + base = ram->data(); + size = ram->size(); + } else { + map = std::make_unique(m.file); + if (!map->ok()) { + return false; + } + base = map->data(); + size = map->size(); + } + if (size < 3 * sizeof(uint64_t)) { + return false; + } + uint64_t h[3]; + std::memcpy(h, base, sizeof(h)); + // exact: the three parts fill the rest of her bytes, checked part by part (no overflowing sum) + const uint64_t body = size - 3 * sizeof(uint64_t); + if (!lengths_fit(body, { h[0], h[1], h[2] }) || h[0] + h[1] + h[2] != body) { + return false; + } + const uint8_t * r = base + sizeof(h); + std::list checkpoints; + if (!ckpt_read(r + h[0] + h[1], h[2], checkpoints)) { + return false; + } + // her cells come from the pool: when it is full, the coldest parked mind goes down to flash first, and the + // insert is tried again (a level above makes room for the level below, never a drop) + bool ok = false; + while (true) { + llama_memory_seq_rm(llama_get_memory(ctx_tgt), seq, -1, -1); + ok = llama_state_seq_set_data_ext(ctx_tgt, r, h[0], seq, LLAMA_STATE_SEQ_FLAGS_NONE) == h[0]; + if (ok || !flash_coldest()) { + break; + } + } + while (ok && ctx_dft && h[1] > 0) { + llama_memory_seq_rm(llama_get_memory(ctx_dft), seq, -1, -1); + ok = llama_state_seq_set_data_ext(ctx_dft, r + h[0], h[1], seq, LLAMA_STATE_SEQ_FLAGS_NONE) == h[1]; + if (ok || !flash_coldest()) { + break; + } + } + if (!ok) { + llama_memory_seq_rm(llama_get_memory(ctx_tgt), seq, -1, -1); + if (ctx_dft) { + llama_memory_seq_rm(llama_get_memory(ctx_dft), seq, -1, -1); + } + SRV_WRN("mind %016llx%016llx: the pool cannot hold her even with every other mind on flash; she stays on flash\n", + (unsigned long long) m.page.hi, (unsigned long long) m.page.lo); + return false; // her file and record are kept: she is still on flash, never lost + } + SRV_INF("mind %016llx%016llx back from %s: %.1f MiB inserted in %.2f ms\n", (unsigned long long) m.page.hi, + (unsigned long long) m.page.lo, ram ? "RAM" : "flash", size / (1024.0 * 1024.0), (ggml_time_us() - t0) / 1000.0); + m.prompt.checkpoints = std::move(checkpoints); + for (const uint64_t pin : m.released) { + unpin(m.prompt.checkpoints, pin); // released while she was on flash + } + m.released.clear(); + // her file is removed on the page-IO worker, ordered after its own write (it may still be landing) + const std::string path = m.file; + page_io->submit(path, [path] { std::error_code ec; std::filesystem::remove(path, ec); }); + m.file.clear(); + m.ram.reset(); + return true; + } + + // Ahead of her turn (the core names who is next): a mind on flash is inserted into a free parked sequence + // now, while the others decode, so her switch is the sequence move. Returns where she is afterwards. + mind_place mind_prefetch(mind_page page) { + for (const auto & s : slots) { + if (s.page == page) { + return mind_place::lane; + } + } + resident_mind * m = find_mind(page); + if (m == nullptr) { + return mind_place::unknown; + } + if (m->seq >= 0) { + m->last_use = ++mind_clock; // she is next: the last to be sent down + return mind_place::parked; + } + if (park_free.empty()) { + flash_coldest(); + } + if (park_free.empty()) { + return mind_place::deferred_no_parked_id; + } + const llama_seq_id seq = park_free.back(); + park_free.pop_back(); + // flash_coldest() may run inside the insert and move records: hold her by page, not by pointer + if (!flash_insert(*find_mind(page), seq)) { + park_free.push_back(seq); + return mind_place::deferred_pool_full; + } + resident_mind * back = find_mind(page); + back->seq = seq; + back->last_use = ++mind_clock; + return mind_place::parked; + } + + // `slot` serves `page` next. The mind it holds (if any) is parked; hers comes back from where she is. + // false: the switch could not complete (the leaving mind could not leave intact, or the arriving mind's state + // could not be inserted): the request waits for a lane, never runs cold beside a stored version of her. + bool mind_switch(server_slot & slot, mind_page page) { + slot.stats.mind_hi = page.hi; + slot.stats.mind_lo = page.lo; + if (slot.page == page) { + slot.stats.mind_came_from = mind_from::lane; + slot.stats.mind_switch_us = 0; + slot.stats.mind_generation = slot.page_generation; + return true; + } + const int64_t t0 = ggml_time_us(); + // the lane's mind leaves, whole + if (slot.page.valid() && slot.prompt.n_tokens() > 0) { + resident_mind m; + m.page = slot.page; + m.lora = slot.lora; + m.last_use = ++mind_clock; + m.generation = slot.page_generation + 1; + if (park_free.empty()) { + flash_coldest(); // the pool's coldest parked mind makes room, if one is parked + } + m.prompt = std::move(slot.prompt); + slot.prompt.clear(); + if (!park_free.empty()) { + m.seq = park_free.back(); + park_free.pop_back(); + seq_move(slot.id, m.seq); + } else if (!flash_out(m, slot.id)) { + slot.prompt = std::move(m.prompt); // she stays whole on her lane + SLT_ERR(slot, "%s", "the leaving mind could be neither parked nor copied out; she is kept on this lane\n"); + return false; // her state is intact on the lane; the arriving request waits for another lane + } + minds.push_back(std::move(m)); + } else if (!slot.page.valid()) { + // content no named mind owns (a core page restore, or scratch): adopted, never cleared; the prompt's + // prefix match keeps what is hers and re-prefills only what diverges + } + const int64_t t_out = ggml_time_us() - t0; + // hers comes in from where she is + const char * from = "new"; + mind_from kind = slot.page.valid() || slot.prompt.n_tokens() == 0 ? mind_from::fresh : mind_from::adopted; + uint64_t generation = 1; + for (size_t i = 0; i < minds.size(); ++i) { + if (minds[i].page != page) { + continue; + } + resident_mind & m = minds[i]; + bool ok; + if (m.seq >= 0) { + seq_move(m.seq, slot.id); + park_free.push_back(m.seq); + from = "parked"; + kind = mind_from::parked; + ok = true; + } else { + const bool in_ram = (bool) m.ram; + from = in_ram ? "RAM" : "flash"; + kind = in_ram ? mind_from::ram : mind_from::flash; + ok = flash_insert(m, slot.id); + } + generation = m.generation + 1; + if (!ok) { + // she stays where she is (record and bytes intact: one version of her); the request waits for + // cells, never runs cold beside her stored state + slot.prompt_clear(); + slot.page = mind_page{}; + SLT_WRN(slot, "%s", "the arriving mind could not be inserted (the pool is full even with every other mind out); her request waits\n"); + return false; + } + slot.prompt = std::move(m.prompt); + slot.lora = std::move(m.lora); + // the record may move under flash_coldest() above: find her again by page before erasing + for (size_t j = 0; j < minds.size(); ++j) { + if (minds[j].page == page) { + minds.erase(minds.begin() + (long) j); + break; + } + } + break; + } + slot.page = page; + slot.page_generation = generation; + slot.stats.mind_came_from = kind; + slot.stats.mind_switch_us = ggml_time_us() - t0; + slot.stats.mind_generation = generation; + SLT_INF(slot, "mind switch: out %.3f ms, in (%s) %.3f ms, she holds %d tokens\n", t_out / 1000.0, from, + (ggml_time_us() - t0 - t_out) / 1000.0, slot.prompt.n_tokens()); + return true; + } diff --git a/tools/server/server-context-page.inc b/tools/server/server-context-page.inc index 85de81265f67..5672a599217d 100644 --- a/tools/server/server-context-page.inc +++ b/tools/server/server-context-page.inc @@ -681,6 +681,7 @@ return; } std::vector().swap(job.body); + slot->page = mind_page{}; // a core page restore: the arriving request's mind adopts it (server-context-minds.inc) // The draft's KV comes back with the page (#79) when it covers exactly these tokens; otherwise the // draft sequence is cleared, never left holding another occupant's KV at these positions: it then diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 15831cececbc..570c047a5465 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -2,6 +2,9 @@ #include "server-context.h" #include "server-checkpoint-policy.h" #include "server-view-end.h" +#include "server-mapped-file.h" +#include +#include #include "../../src/llama-ext.h" #include "server-train.h" #include "server-adapter-file.h" @@ -319,6 +322,10 @@ struct server_slot { server_prompt prompt; + // Continuum fork: the mind whose sequence this lane holds (server-context-minds.inc); invalid: anonymous + mind_page page; + uint64_t page_generation = 0; // her state's generation on this lane + bool prompt_save(server_prompt_cache & prompt_cache) const { if (prompt.tokens.size() == 0) { return false; @@ -1058,6 +1065,7 @@ struct server_context_impl { bool began = false; std::string grant; int32_t lora_id = -1; + llama_seq_id side = -1; // learning on a side sequence: her own sequence is never touched std::string refusal = "none"; bool drained = false; uint64_t restoration_reservation = 0; @@ -1244,7 +1252,9 @@ struct server_context_impl { params_base = params; const auto output_limits = server_output_limits(params_base); - params_base.n_outputs_max = output_limits.total; + // the context reserves at least one output row per sequence: parked minds are sequences (they produce no + // outputs, but the reserve counts them) + params_base.n_outputs_max = std::max(output_limits.total, params_base.n_parallel + std::max(0, params_base.n_minds)); params_base.n_outputs_max_per_seq = output_limits.per_seq; const bool has_mmproj = !params.mmproj.path.empty(); @@ -1463,6 +1473,9 @@ struct server_context_impl { if (!page_io) { page_io = std::make_unique((size_t) params_base.n_parallel); } + if (!minds_init()) { + return false; + } // try speculative decoding if (ctx_tgt_seq_rm_type != COMMON_CONTEXT_SEQ_RM_TYPE_NO) { @@ -1567,6 +1580,14 @@ struct server_context_impl { SRV_TRC("%s", "use `--cache-ram 0` to disable the prompt cache\n"); prompt_cache = std::make_unique(params_base.cache_ram_mib, n_ctx); + // Continuum fork (CONTINUUM-ENGINE 4.7.6, step 1): --cache-ram is the ONE host budget of the prompt + // cache AND every slot's checkpoints. They were sized apart and nothing held their sum: on the M5 + // (2026-11-16) a 9.5 GB cache plus up to 32 x ~100 MB checkpoints x 5 slots swapped 16 GB out of the + // engine and decode fell to 1.3 tok/s (par ~56). + if (params_base.cache_ram_mib > 0) { + host_budget = 1024ull * 1024ull * (size_t) params_base.cache_ram_mib; + SRV_INF("host budget (prompt cache + checkpoints, all slots): %d MiB\n", params_base.cache_ram_mib); + } } else { SRV_TRC("%s", "prompt cache is disabled - use `--cache-ram N` to enable it\n"); } @@ -1850,6 +1871,14 @@ struct server_context_impl { } } + // a named mind switches by sequence moves (server-context-minds.inc), never through the prompt cache + if (ret && minds_on() && task.params.page.valid()) { + if (!mind_switch(*ret, task.params.page)) { + return nullptr; // the switch could not complete intact: this request waits (never runs cold) + } + update_cache = false; + } + if (ret) { update_cache = update_cache && prompt_cache; @@ -1861,6 +1890,7 @@ struct server_context_impl { const int64_t t_start = ggml_time_us(); + fit_prompt_cache_to_budget(); // its share of the one host budget, before it takes a new entry ret->prompt_save(*prompt_cache); const auto task_lora = task.params.lora.empty() ? params_base.lora_adapters @@ -1890,10 +1920,40 @@ struct server_context_impl { return res; } + // resident minds: the pool's coldest parked mind goes to flash, whole; an idle lane's mind is never purged + if (minds_on()) { + if (flash_coldest()) { + return true; + } + for (auto & slot : slots) { + if (!slot.is_processing() && slot.page.valid() && slot.prompt.n_tokens() > 0) { + resident_mind m; + m.page = slot.page; + m.lora = slot.lora; + m.last_use = ++mind_clock; + m.generation = slot.page_generation + 1; + m.prompt = std::move(slot.prompt); + slot.prompt.clear(); + if (flash_out(m, slot.id)) { + slot.page = mind_page{}; + minds.push_back(std::move(m)); + return true; + } + slot.prompt = std::move(m.prompt); // she stays whole on her lane + } + } + } + for (auto & slot : slots) { if (slot.is_processing()) { continue; } + // a mind is never purged: when neither a parked mind nor an idle lane's mind could go to flash above, + // there is no legal move for her and this returns false (Codex on #139); an anonymous slot's cached + // prompt (no mind) may still be cleared + if (minds_on() && slot.page.valid()) { + continue; + } if (slot.prompt.n_tokens() > 0) { SRV_WRN("purging slot %d with %zu tokens\n", slot.id, slot.prompt.tokens.size()); @@ -2309,6 +2369,7 @@ struct server_context_impl { #include "server-context-learn.inc" #include "server-context-learn-checkpoint.inc" #include "server-context-page.inc" +#include "server-context-minds.inc" void send_final_response(server_slot & slot) { if (slot.task->params.learn_only) { @@ -2601,6 +2662,107 @@ struct server_context_impl { } } + // ---- the one host budget (CONTINUUM-ENGINE 4.7.6, step 1) ------------------------------------------ + // 0: no budget (--cache-ram -1 or 0). Checkpoints are charged first (they serve the minds in the slots); + // the prompt cache holds what is left and evicts down to it. + size_t host_budget = 0; + + // every host byte the engine holds beside the prompt cache: the lanes' checkpoints, the parked minds' + // checkpoints, and a flashed mind's RAM copy until her file has landed (server-context-minds.inc) + // `in_flight`: also a flashed mind's RAM copy (freed within ms of its write landing). The make-room decision + // counts only what stays resident, so sending one mind down is seen to free her checkpoints. + size_t checkpoint_bytes(bool in_flight = true) const { + size_t b = 0; + for (const auto & s : slots) { + for (const auto & c : s.prompt.checkpoints) { + b += c.size(); + } + } + for (const auto & m : minds) { + for (const auto & c : m.prompt.checkpoints) { + b += c.size(); + } + // a RAM copy whose flash write FAILED is where she lives now (minds_reap dropped `written`): resident, + // counted always; one whose write is still in flight is transient, counted with `in_flight` (Codex on #139) + const bool failed_write = m.ram && !m.written; + if (m.ram && (in_flight || failed_write)) { + b += m.ram->size(); + } + } + return b; + } + + // The prompt cache's share: the budget less every checkpoint (1 byte, not 0, when none is left: the + // cache reads 0 as "no limit"). + void fit_prompt_cache_to_budget() { + if (!prompt_cache || host_budget == 0) { + return; + } + const size_t ck = checkpoint_bytes(); + prompt_cache->limit_size = host_budget > ck ? host_budget - ck : 1; + prompt_cache->update(); + } + + // Room for a checkpoint of `bytes` under the budget: the slot holding the most checkpoint bytes gives up its + // least valuable one (checkpoint_to_evict keeps her head while anything else is left), until it fits. False: + // it cannot fit even with every checkpoint gone (larger than the budget); the caller makes none. + bool make_room_for_checkpoint(size_t bytes) { + if (host_budget == 0) { + return true; + } + if (bytes > host_budget) { + return false; + } + // the coldest parked mind goes down to flash first (her checkpoints with her): the minds acting keep theirs + while (checkpoint_bytes(false) + bytes > host_budget && minds_on() && flash_coldest()) { + } + size_t held = checkpoint_bytes(false); // what stays resident: copies on their way to flash are leaving + while (held + bytes > host_budget) { + server_slot * from = nullptr; + size_t most = 0; + for (auto & s : slots) { + size_t b = 0; + for (const auto & c : s.prompt.checkpoints) { + b += c.size(); + } + if (b > most) { + most = b; + from = &s; + } + } + if (from == nullptr) { + return false; + } + // her newest checkpoint is where her next act resumes (her context only appends): it goes last. + // Otherwise the store's own order (her head kept while anything else is left), never a pinned one. + auto & cks = from->prompt.checkpoints; + auto newest = cks.end(); + for (auto it = cks.begin(); it != cks.end(); ++it) { + if (newest == cks.end() || it->n_tokens > newest->n_tokens) { + newest = it; + } + } + auto victim = cks.end(); + for (auto it = cks.begin(); it != cks.end(); ++it) { + if (it != newest && it->pin == 0) { + victim = it; + break; + } + } + if (victim == cks.end() && newest != cks.end() && newest->pin == 0) { + victim = newest; // all that is left + } + if (victim == cks.end()) { + return false; // every checkpoint left is pinned for learning + } + SLT_WRN(*from, "host budget: erasing a checkpoint (n_tokens = %" PRId64 ", %.3f MiB) for a new one of %.3f MiB\n", + victim->n_tokens, (float) victim->size() / 1024 / 1024, (float) bytes / 1024 / 1024); + held -= victim->size(); + from->prompt.checkpoints.erase(victim); + } + return true; + } + // n_tokens_cur: the number of tokens added to the batch for the current slot void create_checkpoint(server_slot & slot, const int64_t n_tokens_cur, llama_pos pos_min, llama_pos pos_max) { const int id_task = slot.task->id; @@ -2610,7 +2772,8 @@ struct server_context_impl { const int64_t step = checkpoint_step(slot); int64_t last = -1; for (auto it = slot.prompt.checkpoints.begin(); it != slot.prompt.checkpoints.end(); ) { - if (it->id_task != id_task && last >= 0 && it->n_tokens <= last + step) { + // a checkpoint pinned for learning stays until learned or released, however close (/learn/release) + if (it->id_task != id_task && it->pin == 0 && last >= 0 && it->n_tokens <= last + step) { SLT_TRC(slot, "erasing context checkpoint too close to an earlier one (pos_min = %d, pos_max = %d, n_tokens = %" PRId64 ", size = %.3f MiB)\n", it->pos_min, it->pos_max, it->n_tokens, (float) it->size() / 1024 / 1024); @@ -2626,6 +2789,9 @@ struct server_context_impl { // make room for the new checkpoint, if needed: her head stays while there is anything else // to evict (server-checkpoint-policy.h) auto victim = checkpoint_to_evict(slot.prompt.checkpoints, slot.prompt.view_end); + if (victim == slot.prompt.checkpoints.end()) { + break; // every checkpoint is pinned for learning: the store holds one more until they are learned + } SLT_WRN(slot, "erasing old context checkpoint (pos_min = %d, pos_max = %d, n_tokens = %" PRId64 ", size = %.3f MiB)\n", victim->pos_min, victim->pos_max, victim->n_tokens, (float) victim->size() / 1024 / 1024); @@ -2633,6 +2799,19 @@ struct server_context_impl { slot.prompt.checkpoints.erase(victim); } + // under the one host budget: quote the copy before making it (its peak), and make room first + { + size_t quote = llama_state_seq_get_size_ext(ctx_tgt, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); + if (ctx_dft && ctx_dft_seq_rm_type != COMMON_CONTEXT_SEQ_RM_TYPE_PART) { + quote += llama_state_seq_get_size_ext(ctx_dft, slot.id, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); + } + if (!make_room_for_checkpoint(quote)) { + SLT_WRN(slot, "host budget: a checkpoint of %.3f MiB does not fit beside what stays resident (budget %.3f MiB); none is made\n", + (float) quote / 1024 / 1024, (float) host_budget / 1024 / 1024); + return; + } + } + // the copy is made aside and kept only once complete common_prompt_checkpoint cur; @@ -2648,7 +2827,12 @@ struct server_context_impl { return; } - const auto & kept = slot.prompt.checkpoints.emplace_back(std::move(cur)); + auto & kept = slot.prompt.checkpoints.emplace_back(std::move(cur)); + if (slot.task->params.learn_pin && kept.n_tokens == (int64_t) slot.task->n_tokens() - 1) { + kept.pin = ++learn_pin_clock; // the core will learn this turn: kept until learned or released (/learn/release) + slot.stats.mind_pin = kept.pin; + slot.stats.mind_pinned_at = kept.n_tokens; + } // Continuum fork (CONTINUUM-ENGINE 4.7.3, placed checkpoints): her new view-end checkpoint // supersedes every checkpoint an earlier act left on this prefix except her head's (the oldest, @@ -2660,6 +2844,8 @@ struct server_context_impl { it.n_tokens, (float) it.size() / 1024 / 1024); }); + fit_prompt_cache_to_budget(); // the cache yields what the checkpoints now hold + SLT_TRC(slot, "created context checkpoint %d of %d (pos_min = %d, pos_max = %d, n_tokens = %" PRId64 ", size = %.3f MiB)\n", (int) slot.prompt.checkpoints.size(), params_base.n_ctx_checkpoints, kept.pos_min, @@ -2883,6 +3069,22 @@ struct server_context_impl { { page_io_done(std::move(task)); } break; + case SERVER_TASK_TYPE_LEARN_RELEASE: + { + auto res = std::make_unique(); + res->id = task.id; + res->outcome = learn_release(task.params.page, task.params.learn_release_pin); + queue_results.send(std::move(res)); + } break; + case SERVER_TASK_TYPE_MIND_PREFETCH: + { + const int64_t t0 = ggml_time_us(); + auto res = std::make_unique(); + res->id = task.id; + res->place = minds_on() ? mind_prefetch(task.params.page) : mind_place::minds_off; + res->elapsed_ms = (ggml_time_us() - t0) / 1000.0; + queue_results.send(std::move(res)); + } break; case SERVER_TASK_TYPE_SLOT_ERASE: { const int id_slot = task.slot_action.id_slot; @@ -2902,6 +3104,7 @@ struct server_context_impl { const size_t n_erased = slot->prompt.tokens.size(); slot->prompt_clear(); + slot->page = mind_page{}; // erased: no mind's sequence is here now page_slot_reassigned(*slot); // a restore buffered for this slot is dropped, never applied over it auto res = std::make_unique(); @@ -3265,6 +3468,9 @@ struct server_context_impl { #endif void update_slots() { + if (minds_on()) { + minds_reap(); // a landed flash write frees her RAM copy; a failed one is written again + } const bool learning_at_start = bool(learning); publish_busy_slots(); struct publish_on_exit { server_context_impl * s; ~publish_on_exit() { s->publish_busy_slots(); } } publish_guard{this}; @@ -4874,6 +5080,19 @@ server_context_meta server_context::get_meta() const { { "allocated_tokens", llama_n_ctx(impl->ctx_tgt) }, { "max_tokens_per_sequence", impl->n_ctx_slot }, { "sequence_capacity", llama_n_seq_max(impl->ctx_tgt) }, + // the engine owns mind switches (server-context-minds.inc): a request naming its "page" is switched by + // sequence moves; the core reads this BEFORE dispatch to skip its own page save/restore (Codex on #139) + { "resident_minds", json { + { "enabled", impl->minds_on() }, + { "lanes", impl->params_base.n_parallel }, + // fixed capacity (the context's sequences beyond the lanes, while minds are on): the core compares it + // across discoveries, so it must not move when a mind parks (Codex on #139/#6087); the free count is + // its own field + { "parked_ids", (int64_t) (impl->params_base.n_minds > 0 + ? llama_n_seq_max(impl->ctx_tgt) - impl->params_base.n_parallel : 0) }, + { "parked_free", (int64_t) impl->park_free.size() }, + { "incarnation", mind_incarnation() }, + } }, }, }; } @@ -4993,6 +5212,8 @@ std::unique_ptr server_routes::handle_completions_impl( } task.id_slot = json_value(data, "id_slot", -1); + task.params.page = mind_page_parse(json_value(data, "page", std::string())); // text only at this edge + task.params.learn_pin = json_value(data, "learn_pin", false); sse_ping_interval = task.params.sse_ping_interval; // OAI-compat @@ -6459,6 +6680,8 @@ void server_routes::init_routes() { res->ok(page_io_snapshot()); return res; }; + this->post_minds_prefetch = [this](const server_http_req & req) { return handle_minds_prefetch(req); }; + this->post_learn_release = [this](const server_http_req & req) { return handle_learn_release(req); }; this->post_learn_grants = [grant_route](const server_http_req & req) { return grant_route(req, "register"); }; this->revoke_learn_grant = [grant_route](const server_http_req & req) { return grant_route(req, "revoke"); }; @@ -6482,6 +6705,7 @@ void server_routes::init_routes() { task.learn.n_prefix = json_value(body, "n_prefix", 0); task.learn.lora_id = json_value(body, "lora_id", -1); task.learn.lr = json_value(body, "lr", 1e-4f); + task.learn.side = json_value(body, "side_sequence", false); if (body.contains("messages")) { try { const auto example = render_learn_example(body); @@ -6512,6 +6736,25 @@ void server_routes::init_routes() { if (result) { res->ok(result->to_json()); } return res; } + // A side-sequence learn never serves the example on her slot (that would cut her context back to the + // example's prompt): her slot must already hold the prompt as a prefix of what she has now, and the + // learn runs on a side sequence (server-context-learn.inc), refused typed otherwise + if (task.learn.side) { + auto & rd = res->rd; + task.id = rd.get_new_id(); + rd.post_task(std::move(task)); + auto result = rd.next(req.should_stop); + if (!result) { + GGML_ASSERT(req.should_stop()); + return res; + } + if (result->is_error()) { + res->error(result->to_json()); + return res; + } + res->ok(result->to_json()); + return res; + } // A past example (S4 (f); fork #89): her slot may no longer hold this prompt. Serve it // first through the ordinary completion path (prompt cache, checkpoints, the slot's // own admission and the grant), one token, and learn as it finishes: when the slot @@ -6813,6 +7056,75 @@ std::unique_ptr server_routes::handle_slots_restore(const return res; } +// Continuum fork: POST /minds/prefetch {"page": ""}: her state comes from flash into a parked sequence now, +// ahead of her turn (server-context-minds.inc). The reply names where she is. +// an abandoned turn's learn pin, released (the core sends the turn receipt's mind.page and mind.pin) +std::unique_ptr server_routes::handle_learn_release(const server_http_req & req) { + auto res = create_response(); + auto & rd = res->rd; + const json body = req.body.empty() ? json::object() : json::parse(req.body); + { + server_task task(SERVER_TASK_TYPE_LEARN_RELEASE); + task.id = rd.get_new_id(); + task.params.page = mind_page_parse(json_value(body, "page", std::string())); + task.params.learn_release_pin = json_value(body, "pin", (uint64_t) 0); + if (json_value(body, "incarnation", (uint64_t) 0) != mind_incarnation()) { + res->error(format_error_response("incarnation names another engine: this release was for a replaced engine", ERROR_TYPE_INVALID_REQUEST)); + return res; + } + if (!task.params.page.valid() || task.params.learn_release_pin == 0) { + res->error(format_error_response("page must name a mind and pin the turn receipt's mind.pin", ERROR_TYPE_INVALID_REQUEST)); + return res; + } + rd.post_task(std::move(task)); + } + auto result = rd.next(req.should_stop); + if (!result) { + GGML_ASSERT(req.should_stop()); + return res; + } + if (result->is_error()) { + res->error(result->to_json()); + return res; + } + GGML_ASSERT(dynamic_cast(result.get()) != nullptr); + res->ok(result->to_json()); + return res; +} + +std::unique_ptr server_routes::handle_minds_prefetch(const server_http_req & req) { + auto res = create_response(); + auto & rd = res->rd; + const json body = req.body.empty() ? json::object() : json::parse(req.body); + { + server_task task(SERVER_TASK_TYPE_MIND_PREFETCH); + task.id = rd.get_new_id(); + task.params.page = mind_page_parse(json_value(body, "page", std::string())); + // a stream meant for another incarnation of this engine (a replacement after a restart) is refused, typed + if (json_value(body, "incarnation", (uint64_t) 0) != mind_incarnation()) { + res->error(format_error_response("incarnation names another engine: this prefetch was for a replaced engine", ERROR_TYPE_INVALID_REQUEST)); + return res; + } + if (!task.params.page.valid()) { + res->error(format_error_response("page must name a mind (32 hexadecimal digits, a UUID)", ERROR_TYPE_INVALID_REQUEST)); + return res; + } + rd.post_task(std::move(task)); + } + auto result = rd.next(req.should_stop); + if (!result) { + GGML_ASSERT(req.should_stop()); + return res; + } + if (result->is_error()) { + res->error(result->to_json()); + return res; + } + GGML_ASSERT(dynamic_cast(result.get()) != nullptr); + res->ok(result->to_json()); + return res; +} + std::unique_ptr server_routes::handle_slots_erase(const server_http_req & req, int id_slot) { auto res = create_response(); auto & rd = res->rd; diff --git a/tools/server/server-context.h b/tools/server/server-context.h index 78d544aba9e1..c2dee6cd8edf 100644 --- a/tools/server/server-context.h +++ b/tools/server/server-context.h @@ -180,6 +180,8 @@ struct server_routes { server_http_context::handler_t get_learn_events; server_http_context::handler_t post_prompt_cache_limit; server_http_context::handler_t get_page_io, post_page_io_budget; // the KV page IO budget (server-page-io.h) + server_http_context::handler_t post_learn_release; // an abandoned turn's learn pin, released + server_http_context::handler_t post_minds_prefetch; // the next mind, from flash into the pool (server-context-minds.inc) server_http_context::handler_t get_train; server_http_context::handler_t post_train; server_http_context::handler_t post_train_cancel; @@ -200,6 +202,8 @@ struct server_routes { std::unique_ptr handle_slots_save(const server_http_req & req, int id_slot, bool size_only); std::unique_ptr handle_slots_restore(const server_http_req & req, int id_slot); std::unique_ptr handle_slots_erase(const server_http_req &, int id_slot); + std::unique_ptr handle_minds_prefetch(const server_http_req &); + std::unique_ptr handle_learn_release(const server_http_req &); std::unique_ptr handle_embeddings_impl(const server_http_req & req, task_response_type res_type); std::unique_ptr handle_count_tokens(const llama_vocab * vocab, mtmd_context * mctx, const server_http_req & req, task_response_type res_type); diff --git a/tools/server/server-mapped-file.cpp b/tools/server/server-mapped-file.cpp new file mode 100644 index 000000000000..19ca94eaca4e --- /dev/null +++ b/tools/server/server-mapped-file.cpp @@ -0,0 +1,80 @@ +#include "server-mapped-file.h" + +#if defined(_WIN32) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +server_mapped_file::server_mapped_file(const std::string & path) { + HANDLE f = CreateFileA(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr); + if (f == INVALID_HANDLE_VALUE) { + return; + } + LARGE_INTEGER sz; + if (!GetFileSizeEx(f, &sz) || sz.QuadPart == 0) { + CloseHandle(f); + return; + } + HANDLE m = CreateFileMappingA(f, nullptr, PAGE_READONLY, 0, 0, nullptr); + if (m == nullptr) { + CloseHandle(f); + return; + } + void * p = MapViewOfFile(m, FILE_MAP_READ, 0, 0, 0); + if (p == nullptr) { + CloseHandle(m); + CloseHandle(f); + return; + } + data_ = static_cast(p); + size_ = (size_t) sz.QuadPart; + file_ = (intptr_t) f; + map_ = (intptr_t) m; +} + +server_mapped_file::~server_mapped_file() { + if (data_ != nullptr) { + UnmapViewOfFile(data_); + CloseHandle((HANDLE) map_); + CloseHandle((HANDLE) file_); + } +} + +#else +#include +#include +#include +#include + +server_mapped_file::server_mapped_file(const std::string & path) { + const int fd = ::open(path.c_str(), O_RDONLY); + if (fd < 0) { + return; + } + struct stat st; + if (::fstat(fd, &st) != 0 || st.st_size <= 0) { + ::close(fd); + return; + } + void * p = ::mmap(nullptr, (size_t) st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); + if (p == MAP_FAILED) { + ::close(fd); + return; + } + ::madvise(p, (size_t) st.st_size, MADV_SEQUENTIAL | MADV_WILLNEED); + data_ = static_cast(p); + size_ = (size_t) st.st_size; + file_ = fd; +} + +server_mapped_file::~server_mapped_file() { + if (data_ != nullptr) { + ::munmap(const_cast(data_), size_); + ::close((int) file_); + } +} +#endif diff --git a/tools/server/server-mapped-file.h b/tools/server/server-mapped-file.h new file mode 100644 index 000000000000..44f721662f13 --- /dev/null +++ b/tools/server/server-mapped-file.h @@ -0,0 +1,28 @@ +#pragma once + +// Continuum fork: a file mapped read-only, so its bytes are inserted straight into a sequence (flash -> unified +// memory at the drive's speed, no read into a buffer first). The OS calls live in server-mapped-file.cpp. + +#include +#include +#include + +class server_mapped_file { +public: + explicit server_mapped_file(const std::string & path); + ~server_mapped_file(); + server_mapped_file(const server_mapped_file &) = delete; + server_mapped_file & operator=(const server_mapped_file &) = delete; + + bool ok() const { return data_ != nullptr; } + const uint8_t * data() const { return data_; } + size_t size() const { return size_; } + +private: + const uint8_t * data_ = nullptr; + size_t size_ = 0; + intptr_t file_ = -1; // a POSIX descriptor or a Windows file HANDLE +#if defined(_WIN32) + intptr_t map_ = -1; // the mapping HANDLE (Windows maps through a second handle) +#endif +}; diff --git a/tools/server/server-mind.h b/tools/server/server-mind.h new file mode 100644 index 000000000000..c6570edfe12d --- /dev/null +++ b/tools/server/server-mind.h @@ -0,0 +1,86 @@ +#pragma once + +// Continuum fork: a MIND, named by the request (the core's PageKey::Mind, a 128-bit id), never guessed from her +// tokens. Text exists only at the JSON edge: a request's "page" is parsed here once, into two integers. +// +// Switching minds costs almost nothing (Joel, 2026-11-16: "This is the entire difference between a multi mind +// system and a POS"): a mind leaving a lane is PARKED as a sequence of the unified KV pool (seq_cp + seq_rm: +// attention cells re-tagged, the recurrent state moved by id, nothing serialized), and a mind arriving is moved +// back the same way, continuing at her own end. server-context.cpp holds the parked table (sized once at load +// from the context's sequence capacity) and performs the moves. + +#include +#include +#include + +// This engine incarnation's token, drawn once per process and reported on /props (resident_minds.incarnation). +// The core sends it back with a prefetch, so a stream meant for a replaced engine is refused: issued by the engine +// itself, never inferred from an OS pid (which the OS reuses). +inline uint64_t mind_incarnation() { + static const uint64_t token = [] { + std::random_device rd; + const uint64_t t = ((uint64_t) rd() << 32) ^ (uint64_t) rd(); + return t != 0 ? t : 1; + }(); + return token; +} + +struct mind_page { + uint64_t hi = 0, lo = 0; + bool valid() const { return hi != 0 || lo != 0; } + bool operator==(const mind_page & o) const { return hi == o.hi && lo == o.lo; } + bool operator!=(const mind_page & o) const { return !(*this == o); } +}; + +// Where a prefetch left her (POST /minds/prefetch's "mind"; frozen spellings in mind_place_name). lane / parked: she +// is in the pool and her switch is a sequence move. unknown: the engine has never served her (her first turn builds +// her). deferred_no_parked_id / deferred_pool_full: she stays on flash and her turn switches through it. +// minds_off: the engine was launched without --minds. +enum class mind_place : uint8_t { lane, parked, unknown, deferred_no_parked_id, deferred_pool_full, minds_off }; + +inline const char * mind_place_name(mind_place p) { + static const char * names[] = { "lane", "parked", "unknown", "deferred_no_parked_id", "deferred_pool_full", "minds_off" }; + return names[(size_t) p]; +} + +// What POST /learn/release did with a learn pin (frozen spellings): released: the checkpoint is unpinned now; +// released_on_flash: she is on flash, and it is unpinned when her checkpoints come back; not_pinned: no checkpoint +// of hers holds that pin (already learned, released, or invalidated by a prompt that diverged before it); +// unknown_mind: the engine holds no mind by that page. A pin is its id (mind.pin on the turn receipt), never a +// position: two turns of the same length never share one. +enum class pin_release : uint8_t { released, released_on_flash, not_pinned, unknown_mind }; + +inline const char * pin_release_name(pin_release r) { + static const char * names[] = { "released", "released_on_flash", "not_pinned", "unknown_mind" }; + return names[(size_t) r]; +} + +// "page": 32 hexadecimal digits, dashes allowed (a UUID). Anything else is no page (the request is anonymous). +inline mind_page mind_page_parse(const std::string & s) { + mind_page p; + int n = 0; + for (char c : s) { + if (c == '-') { + continue; + } + int v; + if (c >= '0' && c <= '9') { + v = c - '0'; + } else if (c >= 'a' && c <= 'f') { + v = c - 'a' + 10; + } else if (c >= 'A' && c <= 'F') { + v = c - 'A' + 10; + } else { + return mind_page{}; + } + if (n < 16) { + p.hi = (p.hi << 4) | (uint64_t) v; + } else if (n < 32) { + p.lo = (p.lo << 4) | (uint64_t) v; + } else { + return mind_page{}; + } + ++n; + } + return n == 32 ? p : mind_page{}; +} diff --git a/tools/server/server-task.cpp b/tools/server/server-task.cpp index e502d728cda1..673bcf778824 100644 --- a/tools/server/server-task.cpp +++ b/tools/server/server-task.cpp @@ -1740,6 +1740,9 @@ json learn_outcome::to_json() const { if (!ok) { res["failure"] = failure; } + static const char * learned_on_names[] = { "none", "slot", "side_sequence" }; + res["learned_on"] = learned_on_names[(size_t) learned_on]; + res["live_sequence_preserved"] = live_sequence_preserved; return res; } diff --git a/tools/server/server-task.h b/tools/server/server-task.h index c757135afcc0..e7ae1eeff1f6 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -1,5 +1,6 @@ #pragma once +#include "server-mind.h" #include "common.h" #include "llama.h" @@ -59,6 +60,8 @@ enum server_task_type { SERVER_TASK_TYPE_SLOT_SAVE, SERVER_TASK_TYPE_SLOT_RESTORE, SERVER_TASK_TYPE_SLOT_ERASE, + SERVER_TASK_TYPE_MIND_PREFETCH, + SERVER_TASK_TYPE_LEARN_RELEASE, // Continuum fork: an abandoned turn's learn pin, released (server-context-minds.inc) // Continuum fork: the next mind, from flash into a parked sequence, ahead of her turn SERVER_TASK_TYPE_SLOT_PAGE_IO_DONE, // Continuum fork: a save's or restore's file IO finished on its worker SERVER_TASK_TYPE_SET_LORA, SERVER_TASK_TYPE_LOAD_LORA, @@ -100,6 +103,10 @@ struct learn_request { std::vector prompt; // the served prompt, when known: her slot must hold exactly it int32_t lora_id = -1; // the trainable adapter (the shadow), loaded dormant float lr = 1e-4f; + // continuum: learn on a side sequence (her prefix re-tagged, the pinned checkpoint's recurrent state loaded): + // her own sequence is never cut, reloaded or truncated; refused, typed, when no side sequence or no pinned + // checkpoint at n_prefix - 1 exists (never a fallback to her slot) + bool side = false; }; struct learn_outcome { @@ -107,6 +114,12 @@ struct learn_outcome { bool effects_uncertain = false; std::string refusal = "none"; bool ok = false; + // continuum: where it learned, typed. none: no learning ran (a refusal or deferral before custody); + // side_sequence: on a side sequence; slot: on her own sequence (cut back to the learned turn's prefix). + enum class learned_on_kind : uint8_t { none, slot, side_sequence } learned_on = learned_on_kind::none; + // whether her live sequence is exactly as it was: stated by the path that ran, never inferred from success + // (true for every refusal before custody and every side-sequence learn; false only when the slot path cut it) + bool live_sequence_preserved = true; bool deferred = false; int64_t retry_after_ms = 0; std::string failure; @@ -174,6 +187,11 @@ struct task_params { // append-only part of the prompt the caller's next request sends again unchanged. The prompt // is checkpointed exactly there and a saved page keeps that checkpoint. -1 = not given. int32_t view_end_pos = -1; + // Continuum fork: the mind this request is (the core's PageKey::Mind; server-mind.h). Invalid: anonymous. + mind_page page; + // Continuum fork: the core will learn this turn later: pin the checkpoint at its prompt's end - 1 + bool learn_pin = false; + uint64_t learn_release_pin = 0; // /learn/release: the pin to release (the turn receipt's mind.pin) // Embeddings int32_t embd_normalize = 2; // (-1=none, 0=max absolute int16, 1=taxicab, 2=Euclidean/L2, >2=p-norm) @@ -707,6 +725,25 @@ struct server_task_result_control : server_task_result { } }; +// continuum: POST /learn/release's reply, typed (`release`: a pin_release_name spelling) +struct server_task_result_learn_release : server_task_result { + pin_release outcome = pin_release::unknown_mind; + + virtual json to_json() override { + return json { { "release", pin_release_name(outcome) } }; + } +}; + +// continuum: POST /minds/prefetch's reply, typed (`mind`: a mind_place_name spelling) +struct server_task_result_mind_prefetch : server_task_result { + mind_place place = mind_place::minds_off; + double elapsed_ms = 0.0; + + virtual json to_json() override { + return json { { "mind", mind_place_name(place) }, { "elapsed_ms", elapsed_ms } }; + } +}; + struct server_task_result_apply_lora : server_task_result { virtual json to_json() override; }; diff --git a/tools/server/server.cpp b/tools/server/server.cpp index 7724d41bfa04..bfabf52427b2 100644 --- a/tools/server/server.cpp +++ b/tools/server/server.cpp @@ -230,6 +230,8 @@ int llama_server(common_params & params, int argc, char ** argv) { routes.post_prompt_cache_limit = models_routes->proxy_post; routes.get_page_io = models_routes->proxy_get; routes.post_page_io_budget = models_routes->proxy_post; + routes.post_minds_prefetch = models_routes->proxy_post; + routes.post_learn_release = models_routes->proxy_post; routes.post_learn_residency = models_routes->proxy_post; routes.release_learn_residency = models_routes->proxy_post; routes.revoke_learn_residency = models_routes->proxy_post; @@ -303,6 +305,8 @@ int llama_server(common_params & params, int argc, char ** argv) { ctx_http.post("/prompt-cache/limit", ex_wrapper(routes.post_prompt_cache_limit)); ctx_http.get ("/page-io", ex_wrapper(routes.get_page_io)); ctx_http.post("/page-io/budget", ex_wrapper(routes.post_page_io_budget)); + ctx_http.post("/minds/prefetch", ex_wrapper(routes.post_minds_prefetch)); + ctx_http.post("/learn/release", ex_wrapper(routes.post_learn_release)); ctx_http.post("/learn/grants/revoke", ex_wrapper(routes.revoke_learn_grant)); ctx_http.get ("/train", ex_wrapper(routes.get_train)); ctx_http.post("/train", ex_wrapper(routes.post_train)); diff --git a/tools/server/tests/unit/test_minds.py b/tools/server/tests/unit/test_minds.py new file mode 100644 index 000000000000..c06ab1ecfe07 --- /dev/null +++ b/tools/server/tests/unit/test_minds.py @@ -0,0 +1,65 @@ +import tempfile +import pytest +from utils import * + +# Resident minds (the fast single lane): one decode lane serves several minds, each parked in the pool by sequence +# id while another decodes, and switched back without re-prefill. These run a real tiny model. + +server: ServerProcess + +PROMPT = "Once upon a time in a land far away, there lived a brave knight who traveled across mountains and rivers. " * 3 +MIND_A = "0" * 31 + "a" +MIND_B = "0" * 31 + "b" + + +@pytest.fixture(autouse=True) +def create_server(): + global server + server = ServerPreset.tinyllama2() + server.n_slots = 1 # one decode lane + server.kv_unified = True # parked minds share the pool's cells by sequence id + server.n_minds = 2 + server.n_ctx = 2048 + server.slot_save_path = tempfile.mkdtemp() + "/" + + +def complete(page: str): + res = server.make_request("POST", "/completion", data={ + "prompt": PROMPT, "n_predict": 4, "temperature": 0.0, "cache_prompt": True, "page": page, + }) + assert res.status_code == 200, res.body + return res.body + + +def resident_minds(): + res = server.make_request("GET", "/props") + assert res.status_code == 200 + return res.body["context_geometry"]["resident_minds"] + + +# what this catches: /props reported the parked ids as the CURRENT free count, so the first mind that parked +# changed the descriptor and the core's next discovery of the same engine failed (MindsMismatch). The capacity +# must hold across park and unpark; the free count is its own field. +def test_the_parked_capacity_holds_across_park_and_unpark(): + server.start() + complete(MIND_A) + before = resident_minds() + assert before["enabled"] is True and before["parked_ids"] > 0 + complete(MIND_B) # A leaves the one lane for a parked sequence + parked = resident_minds() + assert parked["parked_ids"] == before["parked_ids"] + assert parked["parked_free"] == before["parked_free"] - 1 + complete(MIND_A) # A back onto the lane, B parked + after = resident_minds() + assert after["parked_ids"] == before["parked_ids"] + + +# what this catches: a switch that re-prefills. A mind returning from her parked sequence is inserted whole: the +# receipt says parked and her prompt is served from cache. +def test_a_returning_mind_comes_back_from_her_parked_sequence_without_prefill(): + server.start() + complete(MIND_A) + complete(MIND_B) + back = complete(MIND_A) + assert back["timings"]["mind"]["from"] == "parked", back["timings"] + assert back["timings"]["cache_n"] > 0, back["timings"] diff --git a/tools/server/tests/utils.py b/tools/server/tests/utils.py index cb66d76874f4..b5722e14a3db 100644 --- a/tools/server/tests/utils.py +++ b/tools/server/tests/utils.py @@ -75,6 +75,7 @@ class ServerProcess: n_predict: int | None = None n_prompts: int | None = 0 slot_save_path: str | None = None + n_minds: int | None = None id_slot: int | None = None cache_prompt: bool | None = None n_slots: int | None = None @@ -225,6 +226,8 @@ def start(self, timeout_seconds: int = DEFAULT_HTTP_TIMEOUT) -> None: server_args.extend(["-fa", self.fa]) if self.n_predict: server_args.extend(["--n-predict", self.n_predict]) + if self.n_minds: + server_args.extend(["--minds", self.n_minds]) if self.slot_save_path: server_args.extend(["--slot-save-path", self.slot_save_path]) if self.n_ga: