diff --git a/engine/src/poly/conversations.hpp b/engine/src/poly/conversations.hpp index 6187d30ae..323397923 100644 --- a/engine/src/poly/conversations.hpp +++ b/engine/src/poly/conversations.hpp @@ -19,9 +19,11 @@ #include #include #include +#include #include #include #include +#include #include #include @@ -36,6 +38,7 @@ struct CacheOptions { int64_t park_mib = 0; ///< host memory for parked conversations; 0: none is parked int park_slots = 4; ///< parked conversations at most int64_t park_min = 1024; ///< a conversation with fewer tokens before its last checkpoint is not parked + int64_t pin_mib = 0; ///< host memory limit for pinned prefixes; 0: unlimited std::function admit; ///< whether the host can spare this many bytes; unset: it can FILE* log = nullptr; ///< where parking is reported; the server reads these lines }; @@ -60,8 +63,29 @@ class Conversations { if (r > at || (r == at && i == cur_)) best = i, at = r, same = c; } ++clock_; - // The pinned conversation (pin()) gets the prompt further than any kept one: the engine takes a copy of it. - if (const int64_t far = marked(pinned_, common(pinned_.seq, ids), n); far > at) return from_pinned(far); + // Pinned prefixes get the prompt further than any kept one (longest matching prefix wins). + size_t best_pin = pinned_.size(); + int64_t best_far = at, best_same = 0; + for (size_t i = 0; i < pinned_.size(); ++i) { + const int64_t c = common(pinned_[i].slot.seq, ids); + const int64_t f = marked(pinned_[i].slot, c, n); + if (f > best_far || + (f == best_far && best_pin < pinned_.size() && + (c > best_same || (c == best_same && pinned_[i].stamp > pinned_[best_pin].stamp)))) { + best_pin = i; + best_far = f; + best_same = c; + } else if (f == at && at > 0 && best_pin == pinned_.size() && + (f > 0)) { + best_pin = i; + best_same = c; + } + } + if (best_pin < pinned_.size() && best_far > at) { + pinned_[best_pin].stamp = clock_; + return from_pinned(pinned_[best_pin].slot, best_far); + } + if (best_pin < pinned_.size() && best_far == at && at > 0) pinned_[best_pin].stamp = clock_; if (at == 0) { // nothing kept starts like this if (!cur().seq.empty() && park(slots_.size())) cur_ = take(cur_); @@ -202,11 +226,7 @@ class Conversations { uint64_t row_bytes, state_bytes, tokens, prompt, marks, piece_rows; }; /// What save() writes for the conversation as it stands; 0: the engine holds none. - uint64_t save_bytes() const { - const Slot& s = cur(); - const uint64_t n = (uint64_t) len(s); - return n == 0 ? 0 : sizeof(Saved) + n * 4 + marks_saved(s) * (8 + e_.state_bytes()) + n * e_.row_bytes(); - } + uint64_t save_bytes() const { return slot_save_bytes(cur()); } /// put(data, bytes) gets save_bytes() bytes, the rows in pieces of `piece` bytes at most, and returns false /// to stop. The engine must be at the conversation's end. The conversation stays as it is. False: put /// stopped, or there was no memory for a piece. @@ -276,18 +296,26 @@ class Conversations { return Restored::ok; } - /// What save() wrote becomes the pinned conversation, in place of one pinned before: a system prompt that every - /// chat starts with, read once. It is kept beside the others with its rows in memory, as a parked one's, but - /// outside the budget and the slots, and nothing pushes it out. A prompt that starts with it goes on from a - /// copy of it (resume()), so it stays as it was read. The engine is not touched. The result is restore()'s; - /// cut: get() ended inside the rows, and nothing is pinned. The caller that then finds the bytes were not the - /// saved ones calls unpin(). + struct PinInfo { + std::string name; + int64_t tokens = 0; + size_t bytes = 0; + bool resident = true; + }; + + /// What save() wrote becomes the anonymous pinned conversation (`""`), in place of one pinned before: a system + /// prompt that every chat starts with, read once. template Restored pin(uint64_t bytes, int64_t most, size_t piece, Get&& get) { + return pin_named("", true, bytes, most, piece, std::forward(get)); + } + /// Pin what save() wrote under `name` beside the conversation cache (resident in RAM when `resident` is true). + template + Restored pin_named(const std::string& name, bool resident, uint64_t bytes, int64_t most, size_t piece, Get&& get) { + unpin_named(name); const size_t row = e_.row_bytes(); Saved head; Slot in; - pinned_ = Slot{}; if (const Restored r = read_start(bytes, most, piece, get, head, in); r != Restored::ok) return r; const int64_t n = (int64_t) head.tokens, per = (int64_t) head.piece_rows; for (int64_t first = 0; first < n; first += per) { @@ -298,31 +326,122 @@ class Conversations { in.rows.push_back({b, first, m, m}); } in.prompt = n; - pinned_ = std::move(in); + if (!fit_pins(name, slot_bytes(in))) return Restored::memory; + if (resident) { + for (const Checkpoint& m : in.marks) + if (!m.state->pin_ram()) return Restored::memory; + for (const Rows& r : in.rows) + if (!r.blob->pin_ram()) return Restored::memory; + } + pinned_.push_back({name, resident, ++clock_, std::move(in)}); return Restored::ok; } - void unpin() { pinned_ = Slot{}; } - /// The pinned conversation's tokens (0: none), and the bytes its rows and states take. - int64_t pinned_tokens() const { return len(pinned_); } - size_t pinned_bytes() const { - size_t bytes = 0; - for (const Checkpoint& m : pinned_.marks) bytes += m.state->bytes(); - for (const Rows& r : pinned_.rows) bytes += r.blob->bytes(); - return bytes; + /// Capture the current conversation in the engine into a named pinned slot (`name` must be non-empty). + Restored pin_current(const std::string& name, bool resident = true) { + if (name.empty()) return Restored::other; + Slot& s = cur(); + const int64_t n = len(s); + if (n < 1) return Restored::other; + const size_t row = e_.row_bytes(), state = e_.state_bytes(); + const int64_t from = saved(s); + const bool need_end = !at_end(s); + size_t need = 0; + for (const Checkpoint& m : s.marks) + if (!is_pinned_excluding(m.state.get(), name)) need += m.state->bytes(); + if (need_end) need += state; + for (const Rows& r : s.rows) + if (!is_pinned_excluding(r.blob.get(), name)) need += r.blob->bytes(); + if (from < n) need += (size_t) (n - from) * row; + if (!fit_pins(name, need)) return Restored::memory; + + const BlobPtr end_mark = need_end ? blob(state) : nullptr; + if (need_end && !end_mark) return Restored::memory; + const BlobPtr tail = from < n ? blob((size_t) (n - from) * row) : nullptr; + if (from < n && !tail) return Restored::memory; + + if (end_mark) e_.save_state(end_mark->data()); + if (tail) { + e_.save_rows(from, n - from, tail->data()); + s.rows.push_back({tail, from, n - from, n - from}); + } + Slot in; + in.seq = s.seq; + in.prompt = n; + in.marks = s.marks; + if (end_mark) in.marks.push_back({n, end_mark}); + in.rows = s.rows; + if (resident) { + for (const Checkpoint& m : in.marks) + if (!m.state->pin_ram()) return Restored::memory; + for (const Rows& r : in.rows) + if (!r.blob->pin_ram()) return Restored::memory; + } + unpin_named(name); + pinned_.push_back({name, resident, ++clock_, std::move(in)}); + return Restored::ok; + } + void unpin() { unpin_named(""); } + bool unpin_named(const std::string& name) { + for (size_t i = 0; i < pinned_.size(); ++i) { + if (pinned_[i].name != name) continue; + PinnedEntry old = std::move(pinned_[i]); + pinned_.erase(pinned_.begin() + (std::ptrdiff_t) i); + release_unpinned_blobs(old); + return true; + } + return false; + } + void unpin_all() { + auto old = std::move(pinned_); + pinned_.clear(); + for (const PinnedEntry& p : old) release_unpinned_blobs(p); + } + size_t pinned_count() const { return pinned_.size(); } + /// Total tokens across all pinned slots (0: none), or one slot's tokens when named. + int64_t pinned_tokens() const { + int64_t total = 0; + for (const PinnedEntry& p : pinned_) total += len(p.slot); + return total; + } + int64_t pinned_tokens(const std::string& name) const { + for (const PinnedEntry& p : pinned_) + if (p.name == name) return len(p.slot); + return 0; + } + size_t pinned_bytes() const { return pinned_bytes_excluding(nullptr); } + size_t pinned_bytes(const std::string& name) const { + for (const PinnedEntry& p : pinned_) + if (p.name == name) return slot_bytes(p.slot); + return 0; + } + std::vector pinned_info() const { + std::vector out; + out.reserve(pinned_.size()); + for (const PinnedEntry& p : pinned_) + out.push_back({p.name, len(p.slot), slot_bytes(p.slot), p.resident}); + return out; } /// Between requests: what the parked conversations hold leaves the process. On the laptop four parked /// conversations of Qwen3.6 held 1.1 to 1.7 GB, one of 29K tokens 1.05 GB. The one in the engine keeps its /// states in memory: every request saves one (63 MB of Qwen3.6's), and the next request most likely goes on - /// from it, so written to the disk it would mostly be read back at once. + /// from it, so written to the disk it would mostly be read back at once. Resident pinned prefixes stay hot in + /// Host RAM. void release() const { for (size_t i = 0; i < slots_.size(); ++i) { if (i == cur_) continue; - for (const Checkpoint& m : slots_[i].marks) m.state->release(); - for (const Rows& r : slots_[i].rows) r.blob->release(); + for (const Checkpoint& m : slots_[i].marks) + if (!is_resident_pinned(m.state.get())) m.state->release(); + for (const Rows& r : slots_[i].rows) + if (!is_resident_pinned(r.blob.get())) r.blob->release(); + } + for (const PinnedEntry& p : pinned_) { + if (p.resident) continue; + for (const Checkpoint& m : p.slot.marks) + if (!is_resident_pinned(m.state.get())) m.state->release(); + for (const Rows& r : p.slot.rows) + if (!is_resident_pinned(r.blob.get())) r.blob->release(); } - for (const Checkpoint& m : pinned_.marks) m.state->release(); - for (const Rows& r : pinned_.rows) r.blob->release(); } /// The parked conversations, the bytes they hold, and how many were pushed out so far. @@ -351,10 +470,85 @@ class Conversations { std::vector rows; // back to back from row 0; a parked conversation has all of its rows uint64_t stamp = 0; }; + struct PinnedEntry { + std::string name; + bool resident = true; + uint64_t stamp = 0; + Slot slot; + }; struct Held { size_t count = 0, bytes = 0; }; + uint64_t slot_save_bytes(const Slot& s) const { + const uint64_t n = (uint64_t) len(s); + return n == 0 ? 0 : sizeof(Saved) + n * 4 + marks_saved(s) * (8 + e_.state_bytes()) + n * e_.row_bytes(); + } + static size_t slot_bytes(const Slot& s) { + size_t bytes = 0; + for (const Checkpoint& m : s.marks) bytes += m.state->bytes(); + for (const Rows& r : s.rows) bytes += r.blob->bytes(); + return bytes; + } + bool is_pinned_excluding(const Blob* b, const std::string& exclude) const { + for (const PinnedEntry& p : pinned_) { + if (p.name == exclude) continue; + for (const Checkpoint& m : p.slot.marks) + if (m.state.get() == b) return true; + for (const Rows& r : p.slot.rows) + if (r.blob.get() == b) return true; + } + return false; + } + bool is_resident_pinned(const Blob* b) const { + for (const PinnedEntry& p : pinned_) { + if (!p.resident) continue; + for (const Checkpoint& m : p.slot.marks) + if (m.state.get() == b) return true; + for (const Rows& r : p.slot.rows) + if (r.blob.get() == b) return true; + } + return false; + } + void release_unpinned_blobs(const PinnedEntry& dropped) const { + if (!dropped.resident) return; + for (const Checkpoint& m : dropped.slot.marks) + if (!is_resident_pinned(m.state.get())) m.state->unpin_ram(); + for (const Rows& r : dropped.slot.rows) + if (!is_resident_pinned(r.blob.get())) r.blob->unpin_ram(); + } + size_t pinned_bytes_excluding(const std::string* exclude) const { + std::vector seen; + for (const PinnedEntry& p : pinned_) { + if (exclude && p.name == *exclude) continue; + for (const Checkpoint& m : p.slot.marks) seen.push_back(m.state.get()); + for (const Rows& r : p.slot.rows) seen.push_back(r.blob.get()); + } + std::sort(seen.begin(), seen.end()); + seen.erase(std::unique(seen.begin(), seen.end()), seen.end()); + size_t total = 0; + for (const Blob* b : seen) total += b->bytes(); + return total; + } + bool fit_pins(const std::string& keep_name, size_t need) { + if (o_.pin_mib < 1) return true; + const size_t budget = (size_t) o_.pin_mib << 20; + while (pinned_bytes_excluding(&keep_name) + need > budget) { + size_t victim = pinned_.size(); + for (size_t i = 0; i < pinned_.size(); ++i) + if (pinned_[i].name != keep_name && (victim == pinned_.size() || pinned_[i].stamp < pinned_[victim].stamp)) + victim = i; + if (victim == pinned_.size()) return false; + PinnedEntry gone = std::move(pinned_[victim]); + pinned_.erase(pinned_.begin() + (std::ptrdiff_t) victim); + release_unpinned_blobs(gone); + if (o_.log) + std::fprintf(o_.log, "strata-poly: pinned prefix '%s' evicted (%lld tokens) to stay within %lld MiB\n", + gone.name.c_str(), (long long) len(gone.slot), (long long) o_.pin_mib); + } + return true; + } + Slot& cur() { return slots_[cur_]; } const Slot& cur() const { return slots_[cur_]; } static int64_t len(const Slot& s) { return (int64_t) s.seq.size(); } @@ -423,9 +617,8 @@ class Conversations { // The engine takes a copy of the pinned conversation's first `at` tokens, a checkpoint of it, and the pinned one // stays as it is. The conversation that leaves is parked if it can be. The rows it has from the pinned one's // blobs are in the caches already: a chat that began as such a copy gives way to the next one without a copy. - int64_t from_pinned(int64_t at) { + int64_t from_pinned(const Slot& p, int64_t at) { const Clock::time_point t0 = Clock::now(); - const Slot& p = pinned_; int64_t have = 0; for (size_t k = 0; k < p.rows.size() && k < cur().rows.size() && p.rows[k].blob == cur().rows[k].blob; ++k) { have = p.rows[k].first + std::min(p.rows[k].keep, cur().rows[k].keep); @@ -513,12 +706,14 @@ class Conversations { } std::sort(seen.begin(), seen.end()); seen.erase(std::unique(seen.begin(), seen.end()), seen.end()); - // what a conversation shares with the pinned one is the pinned one's, outside the budget + // what a conversation shares with any pinned one is the pinned one's, outside the budget const auto pinned = [this](const Blob* b) { - for (const Checkpoint& m : pinned_.marks) - if (m.state.get() == b) return true; - for (const Rows& r : pinned_.rows) - if (r.blob.get() == b) return true; + for (const PinnedEntry& p : pinned_) { + for (const Checkpoint& m : p.slot.marks) + if (m.state.get() == b) return true; + for (const Rows& r : p.slot.rows) + if (r.blob.get() == b) return true; + } return false; }; for (const Blob* b : seen) @@ -634,8 +829,8 @@ class Conversations { E& e_; CacheOptions o_; - std::vector slots_; // the current conversation and the parked ones - Slot pinned_; // pin()'s: beside them, never the engine's own, never pushed out + std::vector slots_; // the current conversation and the parked ones + std::vector pinned_; // named & anonymous pinned prefixes beside them, never pushed out by chats size_t cur_ = 0; uint64_t clock_ = 0; size_t evictions_ = 0; diff --git a/engine/src/poly/conversations_test.cpp b/engine/src/poly/conversations_test.cpp index 2260d96ea..a967e44ba 100644 --- a/engine/src/poly/conversations_test.cpp +++ b/engine/src/poly/conversations_test.cpp @@ -395,6 +395,95 @@ void pinned_prompt() { check(d.ask(q) == 0, "and the prompt is read from its start"); } +void multi_slot_host_ram_pins() { + const std::vector common = text(100, 1200); + const std::vector meta = common + text(200, 1800); // 3000 tokens + const std::vector alter_ego = common + text(300, 600); // 1800 tokens + + Chat c(options(64, 2)); + std::vector m = meta; + c.ask(m, 0); + check(c.kept.pin_current("meta", true) == Restored::ok, "pin_current captures meta"); + check(c.kept.pinned_count() == 1 && c.kept.pinned_tokens("meta") == 3000, "meta tokens recorded"); + const std::vector meta_bin = saved(c); + + std::vector a = alter_ego; + c.ask(a, 0); + check(c.kept.pin_current("alter_ego", true) == Restored::ok, "pin_current captures alter_ego"); + check(c.kept.pinned_count() == 2 && c.kept.pinned_tokens("alter_ego") == 1800, "both pins coexist"); + const std::vector alter_bin = saved(c); + + // Longer match vs shorter match, alternating slots with parallel=1 + std::vector qm1 = meta + text(400, 40); + int64_t read_before = c.e.read; + check(c.ask(qm1) == 3000 && (c.e.read - read_before) == 40 + 3, "meta pin hit restores all 3000 tokens"); + std::vector qa1 = alter_ego + text(500, 35); + read_before = c.e.read; + check(c.ask(qa1) == 1800 && (c.e.read - read_before) == 35 + 3, "alternating to alter_ego hits 1800 tokens"); + for (int k = 0; k < 4; ++k) { + std::vector noise = text(600 + k, 4000); + c.ask(noise); + c.kept.release(); + } + std::vector qm2 = meta + text(700, 25); + check(c.ask(qm2) == 3000, "meta remains pinned after unrelated traffic and release() cycles"); + std::vector qa2 = alter_ego + text(800, 20); + check(c.ask(qa2) == 1800, "alter_ego remains pinned too"); + + Chat restarted(options(0, 1)); + auto load = [&](const std::string& name, const std::vector& bytes) { + size_t at = 0; + return restarted.kept.pin_named(name, true, bytes.size(), Fake::ctx, 1000, [&](void* p, size_t n) { + if (n > bytes.size() - at) return false; + std::memcpy(p, bytes.data() + at, n); + at += n; + return true; + }); + }; + check(load("meta", meta_bin) == Restored::ok && load("alter_ego", alter_bin) == Restored::ok, + "restarted engine reloads persisted multi-slot .bin pins"); + check(restarted.kept.pinned_count() == 2 && restarted.e.at == 0 && restarted.e.read == 0, + "reload touches neither engine KV nor position"); + std::vector qr1 = meta + text(900, 15); + check(restarted.ask(qr1) == 3000, "reloaded meta resumes at 3000"); + std::vector qr2 = alter_ego + text(901, 15); + check(restarted.ask(qr2) == 1800, "reloaded alter_ego resumes at 1800"); + + // Unpinning one slot keeps the other intact + check(restarted.kept.unpin_named("meta") && !restarted.kept.unpin_named("meta"), "unpin_named removes target only"); + check(restarted.kept.pinned_count() == 1 && restarted.kept.pinned_tokens("alter_ego") == 1800, + "remaining pin survives unpin_named"); +} + +void resident_pin_skips_spill_and_respects_budget() { + // Verify resident Spill blob stays in heap across release(), whereas normal Spill leaves heap. + const size_t n = (size_t(3) << 20) + 64; + auto resident = std::make_shared(n); + check(resident->pin_ram() && resident->is_pinned_ram(), "pin_ram marks blob resident"); + for (int i = 0; i < 20; ++i) { + resident->release(); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + check(resident->has_heap(), "resident pinned blob never leaves heap RAM"); + resident->unpin_ram(); + check(!resident->is_pinned_ram(), "unpin_ram clears residency lock"); + + // pin_mib LRU eviction + CacheOptions o = options(0, 1); + o.pin_mib = 2; // each 500-token pin with marks at 499 & 500 takes ~1.18 MiB; 2 pins (~2.36 MiB) exceed 2 MiB + Chat bounded(o); + bounded.e.state = 600 << 10; + std::vector p1 = text(10, 500); + bounded.ask(p1, 0); + check(bounded.kept.pin_current("first", true) == Restored::ok, "first pin fits 2 MiB budget"); + std::vector p2 = text(20, 500); + bounded.ask(p2, 0); + check(bounded.kept.pin_current("second", true) == Restored::ok, "second pin evicts LRU first pin to fit"); + check(bounded.kept.pinned_count() == 1 && bounded.kept.pinned_tokens("first") == 0 && + bounded.kept.pinned_tokens("second") == 500, + "LRU pin evicted cleanly while newest pin kept"); +} + // Any order of prompts over conversations that share starts, under any options: the engine always ends up // holding the prompt. Now and then the conversation is saved as a session file, and one saved earlier comes back. // Half the rounds have a pinned conversation, which some prompts start with. @@ -510,6 +599,8 @@ int main() { far = 0; session_files(); pinned_prompt(); + multi_slot_host_ram_pins(); + resident_pin_skips_spill_and_respects_budget(); quits = 3; // with reads given up, the places a prompt is taken up from are others: any order, any options for (const int64_t f : {6000, 700}) { far = f; diff --git a/engine/src/poly/main.cpp b/engine/src/poly/main.cpp index e7eff913c..a84bac131 100644 --- a/engine/src/poly/main.cpp +++ b/engine/src/poly/main.cpp @@ -385,6 +385,7 @@ struct Session { Guesses guesses; // whether the block is asked in a round, and for how many (guesses.hpp) int piece_calls = kPiece; // generate()'s pieces when it is given `between` std::string pinned; // --pinned-session: the file serve() pins before its first request + std::string pin_dir; // --pin-dir: folder of persisted .bin named prefix pins std::vector co_read; // BCO: prompts for generate()'s first read() to take along bool co_done = false; // and that read took them @@ -420,7 +421,8 @@ struct Session { template Result generate(const std::vector& ids, const Pictures& pictures, int32_t pad, int64_t turn_at, int64_t max_new, const Sampling& s, const std::atomic& stop, OnToken on_token, - OnProgress on_progress, const std::function* between = nullptr) { + OnProgress on_progress, const std::function* between = nullptr, + bool prefill_only = false) { Result r; const int64_t n = (int64_t) ids.size(); Clock::time_point t0 = Clock::now(), shown = t0; // bringing a parked conversation back is prompt time @@ -502,7 +504,7 @@ struct Session { co_read.clear(); } if (last) engine.end_read(); // the last token, as the answer's, with the whole expert cache - engine.eval(ids.data() + i, (int) m, last); + engine.eval(ids.data() + i, (int) m, last && !prefill_only); } kept.read(ids.data() + i, m); i += m; @@ -521,6 +523,10 @@ struct Session { kept.prompt_was(n); r.prompt_ms = ms_since(t0); if (std::strcmp(r.finish, "cancel") == 0) return r; + if (prefill_only) { + r.finish = "stop"; + return r; + } t0 = Clock::now(); std::vector history = kept.seq(); @@ -616,11 +622,11 @@ struct Session { // the key image_pad, the token whose runs in the ids are the pictures' places. turn_at is the place in the ids // where the prompt's last turn begins (the server knows the template's turn tokens): a checkpoint goes there. bool parse_gen(const std::string& line, long long& max_new, Sampling& s, int32_t& pad, int64_t& turn_at, - std::string& pictures, std::vector& ids) { + std::string& pictures, std::vector& ids, bool& prefill_only) { const bool geni = line.rfind("GENI ", 0) == 0; + prefill_only = false; char* p = nullptr; max_new = std::strtoll(line.c_str() + (geni ? 5 : 4), &p, 10); - if (max_new < 1) return false; pad = -1; turn_at = -1; for (;;) { // key=value tokens, then the file and the ids @@ -646,8 +652,10 @@ bool parse_gen(const std::string& line, long long& max_new, Sampling& s, int32_t else if (key == "seed") s.seed = std::strtoull(v, nullptr, 10); else if (key == "image_pad") pad = (int32_t) std::atoi(v); else if (key == "turn_at") turn_at = std::strtoll(v, nullptr, 10); + else if (key == "prefill") prefill_only = std::atoi(v) != 0; // other keys belong to the other engine and are skipped } + if (prefill_only ? (max_new != 0 || geni) : max_new < 1) return false; pictures.clear(); if (geni) { const char* end = std::strchr(p, ' '); @@ -709,20 +717,27 @@ std::string session_starts(uint64_t total, uint64_t binds, Get&& get) { return {}; } -// --pinned-session FILE before the first request, and PIN between requests: the file's conversation becomes -// the pinned one (Conversations::pin()), a system prompt that was read once and saved, in place of one pinned -// before. Returns what is wrong with the file, or nothing; then nothing is pinned. `io`: it could not be read. -std::string pin_session(Session& ss, const std::string& name, bool& io) { +bool is_valid_pin_name(const std::string& name) { + if (name.empty() || name.size() > 64 || name == "." || name == "..") return false; + return std::all_of(name.begin(), name.end(), [](unsigned char c) { + return std::isalnum(c) || c == '-' || c == '_' || c == '.'; + }); +} + +// --pinned-session FILE before the first request, PIN , and named PIN_LOAD / --pin-dir: +// pins a saved session beside the conversation cache. Returns what is wrong with the file, or nothing. +std::string pin_session_named(Session& ss, const std::string& slot_name, bool resident, const std::string& file_name, + bool& io) { namespace fs = std::filesystem; using Restored = Conversations::Restored; const Clock::time_point t0 = Clock::now(); io = false; const auto no = [&](const std::string& why) { - ss.kept.unpin(); + ss.kept.unpin_named(slot_name); return why; }; std::error_code ec; - const fs::path path = session_path(name); + const fs::path path = session_path(file_name); const uint64_t total = fs::file_size(path, ec); io = true; if (ec) return no("the file cannot be read: " + ec.message()); @@ -737,18 +752,121 @@ std::string pin_session(Session& ss, const std::string& name, bool& io) { return true; }; if (const std::string why = session_starts(total, session_binds(ss.engine), get); !why.empty()) return no(why); - const Restored r = ss.kept.pin(total - kSessionFrame, ss.engine.max_context(), kSessionPiece, get); + const Restored r = + ss.kept.pin_named(slot_name, resident, total - kSessionFrame, ss.engine.max_context(), kSessionPiece, get); if (r == Restored::other) return no("the file is not a whole session of this model within --max-context"); if (r == Restored::memory) return no("no memory for it"); uint64_t want = 0; if (r == Restored::ok) in.read((char*) &want, 8); if (r != Restored::ok || in.gcount() != 8 || want != hash.digest()) return no("the file is damaged"); - std::fprintf(stderr, "strata-poly: pinned session: %lld tokens, %zu MiB of rows and states beside the conversation " - "cache, read in %.0f ms; a prompt that starts with them goes on from there\n", - (long long) ss.kept.pinned_tokens(), ss.kept.pinned_bytes() >> 20, ms_since(t0)); + const long long tok = ss.kept.pinned_tokens(slot_name); + const size_t bytes = ss.kept.pinned_bytes(slot_name); + std::fprintf(stderr, "strata-poly: pinned session%s%s: %lld tokens, %zu MiB (%s) beside the conversation cache, " + "read in %.0f ms; a prompt that starts with them goes on from there\n", + slot_name.empty() ? "" : " ", slot_name.c_str(), tok, bytes >> 20, + resident ? "ram" : "spill", ms_since(t0)); return {}; } +std::string pin_session(Session& ss, const std::string& name, bool& io) { + return pin_session_named(ss, "", true, name, io); +} + +bool save_pin_file(Session& ss, const std::filesystem::path& path, + strata::core::SessionError& kind, std::string& why) { + namespace fs = std::filesystem; + using strata::core::SessionError; + const uint64_t body = ss.kept.save_bytes(); + if (body == 0 || ss.engine.pos() != (int64_t) ss.kept.seq().size()) { + kind = SessionError::invalid; + why = "pinned slot has no active conversation to save"; + return false; + } + const uint64_t total = kSessionFrame + body; + std::error_code ec; + const fs::path dir = path.has_parent_path() ? path.parent_path() : fs::path("."); + fs::create_directories(dir, ec); + const fs::space_info room = fs::space(dir, ec); + if (ec) { + kind = SessionError::io; + why = "the folder of the file: " + ec.message(); + return false; + } + if (room.available < total + (kSessionFreeMib << 20)) { + kind = SessionError::storage; + why = "the file takes " + std::to_string(total >> 20) + " MiB and has to leave " + + std::to_string(kSessionFreeMib) + " MiB free; the disk has " + + std::to_string(room.available >> 20) + " MiB"; + return false; + } + const uint64_t binds = session_binds(ss.engine); + strata::core::SessionHasher hash; + fs::path part = path; + part += ".part"; + std::ofstream out(part, std::ios::binary | std::ios::trunc); + fs::permissions(part, fs::perms::owner_read | fs::perms::owner_write, ec); + const auto put = [&](const void* p, size_t n) { + out.write((const char*) p, (std::streamsize) n); + hash.update(p, n); + return out.good(); + }; + bool ok = out.is_open() && put(kSessionMagic, sizeof kSessionMagic) && put(&binds, 8), no_memory = false; + try { + if (ok && !ss.kept.save(kSessionPiece, put)) ok = false, no_memory = out.good(); + } catch (const std::exception& e) { + ok = false; + why = e.what(); + } + const uint64_t h = hash.digest(); + if (ok) out.write((const char*) &h, 8); + out.close(); + ok = ok && !out.fail(); + if (ok) { + fs::rename(part, path, ec); + if (ec) ok = false, why = ec.message(); + } + if (!ok) { + fs::remove(part, ec); + if (no_memory) { + kind = SessionError::memory; + why = "no memory to move the pinned rows"; + } else { + const fs::space_info left = fs::space(dir, ec); + kind = !ec && left.available < total ? SessionError::storage : SessionError::io; + if (why.empty()) why = "the file cannot be written"; + } + return false; + } + return true; +} + +void load_pin_dir(Session& ss) { + namespace fs = std::filesystem; + if (ss.pin_dir.empty()) return; + std::error_code ec; + const fs::path dir = session_path(ss.pin_dir); + if (!fs::is_directory(dir, ec)) return; + std::vector bins; + for (const fs::directory_entry& ent : fs::directory_iterator(dir, ec)) { + if (!ent.is_regular_file(ec)) continue; + const fs::path& p = ent.path(); + if (p.extension() == ".bin") bins.push_back(p); + } + std::sort(bins.begin(), bins.end()); + for (const fs::path& p : bins) { + const auto u8stem = p.stem().u8string(); + const std::string name(reinterpret_cast(u8stem.data()), u8stem.size()); + if (!is_valid_pin_name(name)) { + std::fprintf(stderr, "strata-poly: --pin-dir skipping %s: invalid pin name\n", p.string().c_str()); + continue; + } + bool io = false; + if (const std::string why = pin_session_named(ss, name, true, p.string(), io); !why.empty()) { + std::fprintf(stderr, "strata-poly: --pin-dir %s: %s; skipped\n", p.string().c_str(), why.c_str()); + } + } +} + // SAVE | RESTORE between requests, answered as the Strata project's engine answers them // (docs/DETAILS.md, Session files): SAVED / RESTORED , SESSION on the way, and // SERR 0 for a file that is refused or fails, after which the engine goes on. @@ -902,14 +1020,15 @@ int serve(Session& ss) { std::fprintf(stderr, "strata-poly: --pinned-session %s: %s; the engine starts without it\n", ss.pinned.c_str(), why.c_str()); } + if (!ss.pin_dir.empty()) load_pin_dir(ss); engine.trim(); std::printf("INFO context=%d expert_slots=%d expert_cache_mib=%lld pool_workers=%d conversation_cache_mib=%lld " "conversation_cache_slots=%d conversation_cache_min_free_mib=%lld vram_free_mib=%lld vram_elastic=1 " - "batch_slots=%d co_read=%d sessions=1 pinned_tokens=%lld engine=" STRATA_VERSION "\n", + "batch_slots=%d co_read=%d sessions=1 pinned_tokens=%lld pinned_slots=%zu engine=" STRATA_VERSION "\n", engine.max_context(), engine.cached_experts(), (long long) (engine.cached_gib() * 1024.0), engine.threads(), (long long) ss.flags.o.park_mib, ss.flags.o.park_slots, ss.flags.min_free_mib, (long long) engine.vram_free_mib(), (int) slots.size(), !slots.empty() && engine.co_reads() ? 1 : 0, - (long long) ss.kept.pinned_tokens()); + (long long) ss.kept.pinned_tokens(), ss.kept.pinned_count()); std::printf("READY %d stop\n", engine.max_context()); std::fflush(stdout); // READY goes to the server alone: without this line the log of an engine that waits for its first request ends @@ -1232,7 +1351,7 @@ int serve(Session& ss) { const std::string why = slots.empty() ? pin_session(ss, line.substr(4), io) : "session files do not support --batch (parallel requests)"; if (why.empty()) { - std::printf("PINNED %lld %zu %.1f\n", (long long) ss.kept.pinned_tokens(), ss.kept.pinned_bytes(), + std::printf("PINNED %lld %zu %.1f\n", (long long) ss.kept.pinned_tokens(""), ss.kept.pinned_bytes(""), ms_since(t0)); } else { std::fprintf(stderr, "strata-poly: session pin %s: %s\n", line.c_str() + 4, why.c_str()); @@ -1241,16 +1360,176 @@ int serve(Session& ss) { std::fflush(stdout); continue; } + // PIN_CUR [resident=ram|spill] [save=0|1] [path=]: capture the current KV prefix into a named + // host-RAM slot, optionally persisting /.bin (or ). + if (line.rfind("PIN_CUR ", 0) == 0) { + const Clock::time_point t0 = Clock::now(); + const auto refuse = [&](strata::core::SessionError kind, const std::string& why) { + std::fprintf(stderr, "strata-poly: pin_cur: %s\n", why.c_str()); + std::printf("SERR %s 0 %s\n", strata::core::session_error_name(kind), why.c_str()); + std::fflush(stdout); + }; + if (!slots.empty()) { + refuse(strata::core::SessionError::invalid, "session files do not support --batch (parallel requests)"); + continue; + } + std::string rest = line.substr(8); + size_t p = 0; + while (p < rest.size() && rest[p] == ' ') ++p; + size_t sp = rest.find(' ', p); + const std::string slot_name = sp == std::string::npos ? rest.substr(p) : rest.substr(p, sp - p); + if (!is_valid_pin_name(slot_name)) { + refuse(strata::core::SessionError::invalid, "invalid pin name"); + continue; + } + bool resident = true; + int save_mode = -1; + std::string save_path; + bool bad_opt = false; + for (size_t cur_pos = sp == std::string::npos ? rest.size() : sp + 1; cur_pos < rest.size();) { + while (cur_pos < rest.size() && rest[cur_pos] == ' ') ++cur_pos; + if (cur_pos >= rest.size()) break; + if (rest.rfind("path=", cur_pos) == cur_pos) { + save_path = rest.substr(cur_pos + 5); + if (save_path.empty()) bad_opt = true; + break; + } + const size_t nxt = rest.find(' ', cur_pos); + const std::string opt = nxt == std::string::npos ? rest.substr(cur_pos) : rest.substr(cur_pos, nxt - cur_pos); + if (opt == "resident=ram") resident = true; + else if (opt == "resident=spill") resident = false; + else if (opt == "save=1") save_mode = 1; + else if (opt == "save=0") save_mode = 0; + else { + bad_opt = true; + break; + } + cur_pos = nxt == std::string::npos ? rest.size() : nxt + 1; + } + if (bad_opt) { + refuse(strata::core::SessionError::invalid, "invalid PIN_CUR option"); + continue; + } + if ((long long) ss.kept.seq().size() != engine.pos() || ss.kept.seq().empty()) { + refuse(strata::core::SessionError::invalid, "no active conversation to pin"); + continue; + } + const auto r = ss.kept.pin_current(slot_name, resident); + if (r == Conversations::Restored::memory) { + refuse(strata::core::SessionError::memory, "no memory for pinned prefix"); + continue; + } + if (r != Conversations::Restored::ok) { + refuse(strata::core::SessionError::invalid, "no active conversation to pin"); + continue; + } + std::filesystem::path disk_path; + if (!save_path.empty()) disk_path = session_path(save_path); + else if (save_mode != 0 && !ss.pin_dir.empty()) disk_path = session_path(ss.pin_dir) / (slot_name + ".bin"); + if (!disk_path.empty()) { + strata::core::SessionError kind = strata::core::SessionError::io; + std::string why; + if (!save_pin_file(ss, disk_path, kind, why)) { + refuse(kind, why); + continue; + } + } else if (save_mode == 1) { + refuse(strata::core::SessionError::invalid, "save=1 needs --pin-dir or path="); + continue; + } + const long long tok = ss.kept.pinned_tokens(slot_name); + const size_t bytes = ss.kept.pinned_bytes(slot_name); + std::fprintf(stderr, "strata-poly: pinned slot '%s': %lld tokens, %zu MiB (%s) in %.1f ms\n", + slot_name.c_str(), tok, bytes >> 20, resident ? "ram" : "spill", ms_since(t0)); + std::printf("PINNED %lld %zu %.1f\n", tok, bytes, ms_since(t0)); + std::fflush(stdout); + continue; + } + // PIN_LOAD : load a persisted session file into a named RAM slot. + if (line.rfind("PIN_LOAD ", 0) == 0) { + const Clock::time_point t0 = Clock::now(); + if (!slots.empty()) { + std::printf("SERR invalid 0 session files do not support --batch (parallel requests)\n"); + std::fflush(stdout); + continue; + } + const std::string rest = line.substr(9); + size_t p = 0; + while (p < rest.size() && rest[p] == ' ') ++p; + const size_t sp = rest.find(' ', p); + const std::string slot_name = sp == std::string::npos ? rest.substr(p) : rest.substr(p, sp - p); + std::string file_path = sp == std::string::npos ? std::string() : rest.substr(sp + 1); + size_t fp = 0; + while (fp < file_path.size() && file_path[fp] == ' ') ++fp; + file_path = file_path.substr(fp); + if (!is_valid_pin_name(slot_name) || file_path.empty()) { + std::printf("SERR invalid 0 expected: PIN_LOAD \n"); + std::fflush(stdout); + continue; + } + bool io = false; + const std::string why = pin_session_named(ss, slot_name, true, file_path, io); + if (why.empty()) { + std::printf("PINNED %lld %zu %.1f\n", (long long) ss.kept.pinned_tokens(slot_name), + ss.kept.pinned_bytes(slot_name), ms_since(t0)); + } else { + std::fprintf(stderr, "strata-poly: PIN_LOAD %s: %s\n", slot_name.c_str(), why.c_str()); + std::printf("SERR %s 0 %s\n", io ? "io" : "invalid", why.c_str()); + } + std::fflush(stdout); + continue; + } + if (line == "UNPIN" || line.rfind("UNPIN ", 0) == 0) { + if (line == "UNPIN") { + ss.kept.unpin(); + } else { + std::string name = line.substr(6); + bool unlink_disk = false; + const size_t sp = name.find(' '); + if (sp != std::string::npos) { + const std::string opt = name.substr(sp + 1); + name = name.substr(0, sp); + unlink_disk = opt == "unlink=1"; + } + if (is_valid_pin_name(name)) { + ss.kept.unpin_named(name); + if (unlink_disk && !ss.pin_dir.empty()) { + std::error_code ec; + std::filesystem::remove(session_path(ss.pin_dir) / (name + ".bin"), ec); + } + } + } + std::printf("UNPINNED %lld %zu\n", (long long) ss.kept.pinned_tokens(), ss.kept.pinned_bytes()); + std::fflush(stdout); + continue; + } + if (line == "PINS") { + const auto items = ss.kept.pinned_info(); + for (const auto& item : items) { + std::printf("PIN_ITEM %s %lld %zu %s\n", item.name.empty() ? "-" : item.name.c_str(), + (long long) item.tokens, item.bytes, item.resident ? "ram" : "spill"); + } + std::printf("PINS %zu %lld %zu\n", items.size(), (long long) ss.kept.pinned_tokens(), + ss.kept.pinned_bytes()); + std::fflush(stdout); + continue; + } if (line.rfind("GEN ", 0) != 0 && line.rfind("GENI ", 0) != 0) { std::printf("ERR expected: GEN or GENI image_pad= \n"); std::fflush(stdout); continue; } - if (!parse_gen(line, max_new, s, pad, turn_at, file, ids)) { + bool req_prefill_only = false; + if (!parse_gen(line, max_new, s, pad, turn_at, file, ids, req_prefill_only)) { std::printf("ERR bad request\n"); std::fflush(stdout); continue; } + if (req_prefill_only && !slots.empty()) { + std::printf("ERR prefill=1 does not support --batch\n"); + std::fflush(stdout); + continue; + } const long long n = (long long) ids.size(); if (n + max_new > engine.max_context()) { std::printf("ERR prompt (%lld tokens) + max_new (%lld) exceeds the context (%d)\n", n, max_new, @@ -1343,7 +1622,7 @@ int serve(Session& ss) { } std::fflush(stdout); }, - slots.empty() ? nullptr : &between); + slots.empty() ? nullptr : &between, req_prefill_only); co_ok = ss.co_done; ss.co_read.clear(); } @@ -1724,6 +2003,9 @@ void usage() { " --pinned-session FILE --serve: a session file (SAVE) whose conversation stays for the whole run,\n" " a system prompt read once: a prompt that starts with it goes on from\n" " its end, whatever took the engine since; it is never pushed out\n" + " --pin-dir DIR --serve: directory for named .bin prefix pins persisted by PIN_CUR\n" + " and auto-reloaded at startup\n" + " --pin-cache-mib N RAM limit in MiB for named pinned prefixes (default 0 = unlimited)\n" " --batch N N answers written together, each in a sequence of its own with its own\n" " state and attention rows (default 0 = one at a time; at most 16);\n" " --slots N is the same\n" @@ -1830,7 +2112,7 @@ int main(int argc, char** argv) { long long max_new = 32; int top_probs = 0, lookup = 3, image_pad = -1, check = 0; bool stagger = false; // --check-stagger - std::string images, pinned; + std::string images, pinned, pin_dir; std::vector ids, eos, follow; for (int i = 1; i < argc; ++i) { const std::string a = argv[i]; @@ -1861,6 +2143,8 @@ int main(int argc, char** argv) { else if (a == "--vram-pool") o.vram_pool = true; else if (a == "--expert-profile") o.profile = val(); else if (a == "--pinned-session") pinned = val(); + else if (a == "--pin-dir") pin_dir = val(); + else if (a == "--pin-cache-mib") cache.o.pin_mib = std::atoll(val()); else if (a == "--no-gpu-experts") o.gpu_experts = false; else if (a == "--any-node") o.stay_near = false; else if (a == "--lock-experts") o.lock_experts = true; @@ -1985,6 +2269,7 @@ int main(int argc, char** argv) { if (const char* v = std::getenv("STRATA_ROUTE_TAIL_SKIP")) o.tail_skip = std::atoi(v); const long long most = 1LL << 24; // MiB: 16 TiB if (cache.o.checkpoints < 0 || cache.o.every < 0 || cache.o.park_mib < 0 || cache.o.park_mib > most || + cache.o.pin_mib < 0 || cache.o.pin_mib > most || cache.o.park_slots < 0 || cache.o.park_slots > 1024 || cache.o.park_min < 0 || cache.min_free_mib < 0 || cache.min_free_mib > most) { std::fprintf(stderr, "strata-poly: a cache option is negative or too large\n"); @@ -2051,6 +2336,7 @@ int main(int argc, char** argv) { } Session ss(engine, eos, cache, lookup); ss.pinned = pinned; + ss.pin_dir = pin_dir; int rc = 0; if (want_serve) { rc = serve(ss); diff --git a/engine/src/poly/spill.cpp b/engine/src/poly/spill.cpp index 19d99019c..82ea443e8 100644 --- a/engine/src/poly/spill.cpp +++ b/engine/src/poly/spill.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -184,6 +185,7 @@ uint8_t* Spill::data() const { void Spill::release() const { std::lock_guard l(m_); + if (pinned_ram_) return; const bool used = used_; used_ = false; if (heap_) { @@ -199,6 +201,40 @@ void Spill::release() const { if (view_ && used) drop(); } +bool Spill::pin_ram() const { + std::lock_guard l(m_); + used_ = true; + if (!heap_ && filed_) { + if (!view_) map(); + if (cold_) { + bring_in(view_, n_); + cold_ = false; + } + uint8_t* copy = new (std::nothrow) uint8_t[n_]; + if (!copy) return false; + if (n_ > 0) std::memcpy(copy, view_, n_); + heap_ = copy; + } + if (!heap_ && n_ > 0) return false; + pinned_ram_ = true; + return true; +} + +void Spill::unpin_ram() const { + std::lock_guard l(m_); + pinned_ram_ = false; +} + +bool Spill::is_pinned_ram() const { + std::lock_guard l(m_); + return pinned_ram_; +} + +bool Spill::has_heap() const { + std::lock_guard l(m_); + return heap_ != nullptr; +} + // Nothing writes or frees the heap while it is queued and not filed: it is read without the lock. A file that // cannot be made or written leaves it in the heap, and it is not tried again. // STRATA_NO_SPILL keeps every blob on the heap instead (parking still works; RAM use grows accordingly). @@ -216,7 +252,7 @@ void Spill::write() const { } file_ = f; filed_ = true; - if (!used_) { + if (!used_ && !pinned_ram_) { delete[] heap_; heap_ = nullptr; } diff --git a/engine/src/poly/spill.hpp b/engine/src/poly/spill.hpp index 1e89b204c..a67e8c153 100644 --- a/engine/src/poly/spill.hpp +++ b/engine/src/poly/spill.hpp @@ -32,6 +32,12 @@ class Spill : public std::enable_shared_from_this { /// Between requests, on the thread that uses data(). void release() const; + /// Keep bytes hot in host heap RAM so release() / background spill skips dropping them. + bool pin_ram() const; + void unpin_ram() const; + bool is_pinned_ram() const; + bool has_heap() const; + private: void write() const; // on the writer's thread void map() const; @@ -45,6 +51,7 @@ class Spill : public std::enable_shared_from_this { mutable bool filed_ = false; // the file holds it mutable bool used_ = false; // data() was asked since the last release() mutable bool cold_ = false; // the mapping's pages are out of the process + mutable bool pinned_ram_ = false; // resident in host RAM: never written out or evicted by release() mutable intptr_t file_ = -1; // the file: a handle on Windows, a descriptor elsewhere mutable void* mapping_ = nullptr; // Windows: the file mapping's handle }; diff --git a/terminal/serve/server.py b/terminal/serve/server.py index 698f2368f..ed30066ae 100644 --- a/terminal/serve/server.py +++ b/terminal/serve/server.py @@ -451,6 +451,50 @@ def combined_embeddings_path(vision_dir: Path, nbytes: int) -> Path: TURN_OPENERS_OF_PRE = {"laguna": ("",)} WARM_MIN_TOKENS = 2048 # a shorter prompt start is quick to read again: not kept BEFORE_LOAD_TIMEOUT_S = 120.0 # #1997: how long the before_load command may run (the config's before_load_timeout_s) +PIN_NAME_RE = re.compile(r"^[A-Za-z0-9._-]{1,64}$") +INKLING_EFFORT_RE = re.compile(r"<\|message_system\|>(?:<\|content_text\|>)?Thinking effort level:") + + +def parse_strata_pin(req: dict) -> dict | None: + """Validate optional OpenAI top-level `strata_pin` object (`{"name", "prefill_only", "resident", "anchor"}`).""" + spec = req.get("strata_pin") + if spec is None: + return None + if not isinstance(spec, dict): + raise ValueError("strata_pin must be an object") + allowed = {"name", "prefill_only", "resident", "anchor"} + unknown = [k for k in spec if k not in allowed] + if unknown: + raise ValueError(f"strata_pin: unknown field {unknown[0]!r}") + name = spec.get("name") + if not isinstance(name, str) or name in (".", "..") or not PIN_NAME_RE.fullmatch(name): + raise ValueError("strata_pin.name must be 1..64 characters of A-Z, a-z, 0-9, '.', '_', '-'") + prefill_only = spec.get("prefill_only") + if prefill_only is not None and not isinstance(prefill_only, bool): + raise ValueError("strata_pin.prefill_only must be true or false") + resident = spec.get("resident", "ram") + if resident == "disk": + resident = "spill" + if resident not in ("ram", "spill"): + raise ValueError('strata_pin.resident must be "ram" or "spill"') + anchor = spec.get("anchor") + if anchor is not None and not isinstance(anchor, str): + raise ValueError("strata_pin.anchor must be a string or null") + return {"name": name, "prefill_only": prefill_only, "resident": resident, "anchor": anchor or None} + + +def configured_pin_dir(cfg: dict) -> str | None: + """Resolved pin directory from explicit config (`pin_dir` / `cache_dir`) or existing default `.pins/*.bin`.""" + raw = cfg.get("pin_dir") + if isinstance(raw, str) and raw.strip(): + return os.path.abspath(raw.strip()) + cache = cfg.get("cache_dir") + if isinstance(cache, str) and cache.strip(): + return os.path.join(os.path.abspath(cache.strip()), "pins") + existing = cfg.get("_existing_pin_dir") + if isinstance(existing, str) and existing.strip(): + return os.path.abspath(existing.strip()) + return None def inkling_template_kwargs(kwargs: dict) -> dict: @@ -2720,7 +2764,8 @@ def generate(self, ids, max_new, sampling, cancel, embeddings=None, prefill_only if carry is not NO_LINE: # the line read after a token for its LP line line, carry = carry, NO_LINE else: - line = lines_q.get(timeout=min(wait, 0.5)) + poll_s = 0.05 if getattr(cancel, "_fast_poll", False) else 0.5 + line = lines_q.get(timeout=min(wait, poll_s)) except queue.Empty: if cancel.is_set(): return @@ -2911,26 +2956,36 @@ def session_file(self, action: str, path: str) -> dict: with self._exclusive_control(): return self._session_file(action, path) + def pin_cur(self, name: str, resident: str = "ram", path: str | None = None, save: bool | None = None) -> dict: + if not isinstance(name, str) or name in (".", "..") or not PIN_NAME_RE.fullmatch(name): + raise ValueError("invalid pin name") + if resident not in ("ram", "spill"): + raise ValueError('resident must be "ram" or "spill"') + parts = [name, f"resident={resident}"] + if save is not None: + parts.append(f"save={int(save)}") + if path: + parts.append(f"path={path}") + return self.session_file("pin_cur", " ".join(parts)) + + def pin_load(self, name: str, path: str) -> dict: + if not isinstance(name, str) or name in (".", "..") or not PIN_NAME_RE.fullmatch(name): + raise ValueError("invalid pin name") + return self.session_file("pin_load", f"{name} {path}") + + def unpin_slot(self, name: str | None = None, unlink: bool = False) -> dict: + arg = "" if not name else (f"{name} unlink=1" if unlink else name) + return self.session_file("unpin", arg) + def _session_file(self, action: str, path: str) -> dict: - """Disk sessions: `SAVE ` / `RESTORE ` between requests (the caller holds the service FIFO), and - strata-poly's `PIN ` (action "pin": the file's conversation is kept beside the conversation cache, and a - prompt that starts with it goes on from there; Service.pin_start). - -> {"tokens", "bytes", "ms"}. SessionRefused (kind, published) when the engine refused or failed the file and - is still in step (`SERR <0|1> `). Any line this exchange does not allow - an unknown or - malformed one, a bare ERR, an answer with negative counts or a non-finite time - means the two sides lost - step: the engine is ended (EngineDied) and the next request starts it again. EngineDied also when it ended - by itself (a restore transfer that failed after the device state changed ends it on purpose: FATAL), and - EngineSilent (#481) when it printed nothing valid for engine_silence_s - a SESSION progress line (one per - block of the file moved, at most 16 MiB) counts only when its numbers are. `SWAIT ` announces - a step that blocks in one call (a flush, the device transfer): until the next line the wait is that step's - explicit allowance (at most SESSION_WAIT_MAX_S) when it is longer than engine_silence_s - no more, so a step - that never ends is still ended.""" + """Disk sessions and named host-RAM pins (`SAVE`, `RESTORE`, `PIN`, `PIN_CUR`, `PIN_LOAD`, `UNPIN`).""" send, want = {"save": ("SAVE", "SAVED"), "restore": ("RESTORE", "RESTORED"), - "pin": ("PIN", "PINNED")}.get(action, ("", "")) - if not send or any(c in path for c in "\r\n\0"): + "pin": ("PIN", "PINNED"), "pin_cur": ("PIN_CUR", "PINNED"), + "pin_load": ("PIN_LOAD", "PINNED"), "unpin": ("UNPIN", "UNPINNED")}.get(action, ("", "")) + if not send or any(c in path for c in "\r\n\0") or (action != "unpin" and not path): raise ValueError("invalid session command") try: - self.proc.stdin.write(f"{send} {path}\n") + self.proc.stdin.write(f"{send} {path}\n" if path else f"{send}\n") self.proc.stdin.flush() except OSError: raise self._engine_died() from None @@ -3000,11 +3055,16 @@ def count(s: str) -> int: raise SessionRefused(parts[1], parts[3].strip(), parts[2] == "1") if head == want: try: - if len(f) != 4: - raise ValueError - tokens, size, ms = count(f[1]), count(f[2]), float(f[3]) - if not math.isfinite(ms) or ms < 0: - raise ValueError + if want == "UNPINNED": + if len(f) != 3: + raise ValueError + tokens, size, ms = count(f[1]), count(f[2]), 0.0 + else: + if len(f) != 4: + raise ValueError + tokens, size, ms = count(f[1]), count(f[2]), float(f[3]) + if not math.isfinite(ms) or ms < 0: + raise ValueError except ValueError: raise out_of_step(line) from None return {"tokens": tokens, "bytes": size, "ms": ms} @@ -3822,6 +3882,13 @@ def engine_args(cfg: dict, exe: str | None = None, *, announce: bool = True) -> args += ["--vram-segment-mib", str(seg)] args += parallel_args(cfg, args) args += pool_cores_args(cfg, args) + if poly: + pin_dir = configured_pin_dir(cfg) + if pin_dir and "--pin-dir" not in args: + args += ["--pin-dir", pin_dir] + pin_mib = cfg.get("pin_cache_mib") + if isinstance(pin_mib, int) and not isinstance(pin_mib, bool) and pin_mib > 0 and "--pin-cache-mib" not in args: + args += ["--pin-cache-mib", str(pin_mib)] args = conversation_cache_min_tokens_args(args, exe or cfg.get("exe")) return draft_costs_args(cfg, learned_profile_args(cfg, args), exe or cfg.get("exe")) @@ -4337,6 +4404,7 @@ def __init__(self, engine: Engine, tokenizer, template: ChatTemplate, model_name self.instance_id = uuid.uuid4().hex self.status_lock = threading.Lock() self.admission_changed = threading.Condition(self.status_lock) + self.pin_idle_cond = threading.Condition(self.status_lock) self.mcp = None # serve/mcp.py's McpHub when MCP servers are configured self.offline = False # no image URL fetch or MCP subprocess in strict local mode self.telemetry_key = "" # optional read-only key, valid only on /v1/telemetry @@ -4371,6 +4439,12 @@ def __init__(self, engine: Engine, tokenizer, template: ChatTemplate, model_name self.warm_start = False self.warm_ids = None # the start kept last (keep_start()) self.warm_stop = threading.Event() # set: no warm read runs, or the one running is to stop + self.pin_dir: str | None = None # opt-in named pin dir (--pin-dir / --cache-dir) + self.cache_dir: str | None = None + self.pin_cache_mib: int = 0 + self.pin_preempt = threading.Event() # set while interactive request is pending or running + self._pin_lock = threading.Lock() + self.real_requests_pending = 0 self.models_root = ROOT # where the installation's run configs are (serve/models.py) # "memory_debug": true in the config (or $STRATA_MEMORY_DEBUG): a switch prints the free VRAM around it self.memory_debug = bool(os.environ.get("STRATA_MEMORY_DEBUG")) @@ -4496,15 +4570,32 @@ def warm_path(self) -> Path: config = Path(self.config_path) return config.with_name(config.stem + ".warm-start") + def _system_turn_end(self, ids) -> int | None: + """Index in `ids` where leading system/tools turns end (before `Thinking effort level:` on Inkling 2 and + before the first non-system turn).""" + opens = [i for i, t in enumerate(ids) if t in self.turn_ids] + if not opens: + return None + if self.call_format != "inkling": + return opens[1] if len(opens) > 1 else None + sys_id = self.tok.encode("<|message_system|>", parse_special=True) + sys_tok = sys_id[0] if len(sys_id) == 1 else None + for idx, p in enumerate(opens): + if sys_tok is not None and ids[p] != sys_tok: + return p + nxt = opens[idx + 1] if idx + 1 < len(opens) else len(ids) + head = self.tok.decode(ids[p:min(nxt, p + 64)]) + if "Thinking effort level:" in head: + return p + return None + def keep_start(self, ids, seed: bool = False) -> None: - """"warm_start": keep the prompt's first turn (the system prompt with the tools) for start_warm(), when it is - long and not the one kept already. A first turn that leaves the kept one after a long common start (a date - or a folder written near its end) keeps that common start: it is what the next chat begins with as well, and - the session file made of it (pin_start()) ends where a chat can go on from. `seed`: the first turn is the - config's own ("warm_start": "FILE"); it replaces a kept start that is not a part of it.""" - opens = (i for i, t in enumerate(ids) if t in self.turn_ids) - next(opens, None) - end = next(opens, None) # the second turn's opener: the first turn ends there + """"warm_start": keep the prompt's static system/tools prefix for start_warm(), when it is long and not the one + kept already. A first turn that leaves the kept one after a long common start (a date or a folder written near + its end) keeps that common start: it is what the next chat begins with as well, and the session file made of it + (pin_start()) ends where a chat can go on from. `seed`: the first turn is the config's own ("warm_start": + "FILE"); it replaces a kept start that is not a part of it.""" + end = self._system_turn_end(ids) if end is None: return first, kept = ids[:end], self.warm_ids or [] @@ -4557,6 +4648,43 @@ def pin_start(self, make: bool = False) -> bool: f"({r['bytes'] >> 20} MiB, {r['ms'] / 1000:.1f} s)", flush=True) return True + def default_pin_dir(self) -> Path | None: + if self.pin_dir: + return Path(self.pin_dir) + if self.cache_dir: + return Path(self.cache_dir) / "pins" + if self.config_path: + cfg = Path(self.config_path) + return cfg.with_name(cfg.stem + ".pins") + return None + + def load_saved_pins(self) -> None: + """Reload persisted `.bin` named pins when engine starts without `--pin-dir` CLI or after mock setup.""" + info = getattr(self.engine, "info", None) or {} + if "pinned_tokens" not in info or getattr(self.engine, "batch", False): + return + if int(info.get("pinned_slots") or 0) > 0: + return + d = self.default_pin_dir() + if d is None or not d.is_dir(): + return + loader = getattr(self.engine, "pin_load", None) + if loader is None and hasattr(self.engine, "session_file"): + loader = lambda name, p: self.engine.session_file("pin_load", f"{name} {p}") + if loader is None: + return + for path in sorted(d.glob("*.bin")): + name = path.stem + if name in (".", "..") or not PIN_NAME_RE.fullmatch(name): + continue + try: + with self.fifo: + r = loader(name, str(path)) + print(f"[strata] pinned prefix '{name}' reloaded: {r['tokens']} tokens ({r['bytes'] >> 20} MiB)", + flush=True) + except (SessionRefused, EngineDied, ValueError, OSError) as e: + print(f"[strata] skipped saved pin {path.name}: {e}", flush=True) + def start_warm(self) -> None: """"warm_start": read the prompt start keep_start() kept when the server ran last, so that the first request that starts with it again reads only what follows. A request stops the read (run() sets warm_stop); the part @@ -4564,6 +4692,7 @@ def start_warm(self) -> None: reads it only to write that file. "warm_start": "FILE" names a chat request (messages and tools, as /v1/chat/completions takes them) whose first turn is the start, for an installation that knows its agent's system prompt before the first request.""" + self.load_saved_pins() if not self.warm_start or not self.loaded(): return path = self.warm_path() @@ -6128,6 +6257,23 @@ def fetch(src): ctx = getattr(self.engine, "known_ctx", 0) if ctx <= 0: raise EngineStarting("the engine is starting (a minute or two); try again shortly") + pin_spec = parse_strata_pin(req) if isinstance(req, dict) else None + pin_prefill_only = False + if pin_spec is not None and isinstance(req, dict): + limit_new = token_limit(req.get("max_completion_tokens"), "max_completion_tokens") + limit_old = token_limit(req.get("max_tokens"), "max_tokens") + explicit_zero = (limit_new == 0) or (limit_new is None and limit_old == 0) + pin_prefill_only = (pin_spec["prefill_only"] is True) or (pin_spec["prefill_only"] is None and explicit_zero) + prefix_ids = self.resolve_pin_prefix(messages, tools, kwargs, ids, anchor=pin_spec["anchor"], + has_images=bool(images)) + req["_strata_pin_resolved"] = {**pin_spec, "prefill_only": pin_prefill_only, "prefix_ids": prefix_ids} + if pin_prefill_only: + if len(prefix_ids) > ctx: + self.forget_prompt(encoded_ids) + raise ContextOverflow("request exceeds the context window: " + f"pinned prefix ({len(prefix_ids)} tokens) exceeds context ({ctx})", + prompt=len(prefix_ids), context=ctx) + return ids, kwargs.get("enable_thinking", True) is not False, 0 room = ctx - CTX_SLACK - len(ids) fit = self.fit_max_tokens or self.drop_oldest if max_new is None or max_new <= 0 or (fit and room < 1): @@ -6180,6 +6326,45 @@ def fetch(src): PREFIX_END = "\u0001strata-prefix-end\u0001" # marks where a message's shared part ends in the rendered prompt + def _head_prefix_ids(self, head_msgs, tools, kwargs, strip_inkling_effort: bool = False) -> list[int]: + """Token ids for rendered `head_msgs` + `tools`, trimmed at `PREFIX_END` (and Inkling 2's effort turn).""" + marked, marked_tools, changed = mark_think_literals(head_msgs, tools, self.literals) + effort = kwargs.get("reasoning_effort") + off = kwargs.get("enable_thinking") is False + kw = ({k: v for k, v in kwargs.items() if k not in ("reasoning_effort", "enable_thinking")} + if self.effort_end and (off or effort not in (None, "", "xhigh", "high")) else dict(kwargs)) + if self.call_format == "inkling": + kw = inkling_template_kwargs(kwargs) + elif self.hy4: + kw = hy4_dialect.template_kwargs(kwargs) + else: + kw = {**self.template_tokens, **({"preserve_thinking": True} if self.preserve_thinking else {}), **kw, + "enable_thinking": not off} + if self.openai_tools and marked_tools: + marked_tools = [{"type": "function", "function": t} for t in marked_tools] + kw["add_generation_prompt"] = False + text = self.template.render(marked, tools=marked_tools, **kw) + cut = text.find(self.PREFIX_END) + if cut >= 0: + text = text[:cut] + if strip_inkling_effort and self.call_format == "inkling": + m = INKLING_EFFORT_RE.search(text) + if m: + text = text[:m.start()] + if changed: + text, plain = unmark_think_literals(text, self.literals) + return self.tok.encode(text, parse_special=True, plain=plain) + return self.tok.encode(text, parse_special=True) + + @staticmethod + def _lcp_len(a, b) -> int: + n = 0 + for x, y in zip(a, b): + if x != y: + break + n += 1 + return n + def resolve_prefix(self, spec, messages, tools, kwargs, ids, has_images=False) -> dict: """R1: `"strata_prefix"` marks the start of the prompt as a shared read-only prefix: a long document that many short questions follow. Three ways to say where it ends: `{"messages": K}` (the first K messages), `{"message": @@ -6201,34 +6386,6 @@ def resolve_prefix(self, spec, messages, tools, kwargs, ids, has_images=False) - print("[strata] strata_prefix ignored: the request has images", flush=True) return {} what = ",".join(f"{k}={v}" for k, v in spec.items()) - - def lcp(a, b): - n = 0 - for x, y in zip(a, b): - if x != y: - break - n += 1 - return n - - def head_ids(msgs): - """The ids the rendered `msgs` start with (a message's trailing marker cut at PREFIX_END when it is there).""" - marked, marked_tools, changed = mark_think_literals(msgs, tools, self.literals) - effort = kwargs.get("reasoning_effort") - off = kwargs.get("enable_thinking") is False # render_prompt's rule for #458's effort_end - kw = ({k: v for k, v in kwargs.items() if k not in ("reasoning_effort", "enable_thinking")} - if self.effort_end and (off or effort not in (None, "", "xhigh", "high")) else dict(kwargs)) - if self.call_format == "inkling": # the effort as render_prompt writes it - kw = inkling_template_kwargs(kwargs) - kw["add_generation_prompt"] = False - text = self.template.render(marked, tools=marked_tools, **kw) - cut = text.find(self.PREFIX_END) - if cut >= 0: - text = text[:cut] - if changed: - text, plain = unmark_think_literals(text, self.literals) - return self.tok.encode(text, parse_special=True, plain=plain) - return self.tok.encode(text, parse_special=True) - if "tokens" in spec: n = spec["tokens"] elif "messages" in spec: @@ -6237,8 +6394,7 @@ def head_ids(msgs): print(f"[strata] strata_prefix.messages={k} ignored: the request has {len(messages)} message(s) and the " "prefix must leave at least the last one", flush=True) return {} - head = head_ids(messages[:k]) - n = lcp(head, ids) + n = self._lcp_len(self._head_prefix_ids(messages[:k], tools, kwargs), ids) else: i, chars = spec["message"], spec["chars"] text = messages[i].get("content") if 0 <= i < len(messages) else None @@ -6246,14 +6402,148 @@ def head_ids(msgs): print(f"[strata] strata_prefix ignored: message {i} has no text of {chars} characters", flush=True) return {} cut = messages[:i] + [{**messages[i], "content": text[:chars] + self.PREFIX_END}] - head = head_ids(cut) - n = lcp(head, ids) + n = self._lcp_len(self._head_prefix_ids(cut, tools, kwargs), ids) if n < 1 or n >= len(ids) - 1: print(f"[strata] strata_prefix {what} ignored: it leaves no usable prefix of the {len(ids)}-token prompt " f"(common start {n})", flush=True) return {} return {"tokens": n} + def resolve_pin_prefix(self, messages, tools, kwargs, ids, anchor: str | None = None, + has_images: bool = False) -> list[int]: + """Compute static prefix token IDs for `strata_pin`. + + - If `anchor` is provided and matches inside the leading system/developer prompt, truncates right before `anchor` + (excluding `anchor` itself). + - When `anchor` is omitted/null (or absent), renders tools + leading system prompt turns, stopping before + Inkling 2's `Thinking effort level:` turn and before any `<|message_user|>` turn. + """ + if has_images: + raise ValueError("strata_pin does not support requests containing images") + sys_end = next((i for i, m in enumerate(messages) if m.get("role") not in ("system", "developer")), len(messages)) + head = None + if anchor: + for idx in range(sys_end): + content = messages[idx].get("content") + if isinstance(content, str): + pos = content.find(anchor) + if pos >= 0: + cut_msgs = list(messages[:idx]) + [{**messages[idx], "content": content[:pos] + self.PREFIX_END}] + head = self._head_prefix_ids(cut_msgs, tools, kwargs, strip_inkling_effort=True) + break + elif isinstance(content, list): + found = False + new_parts = [] + for part in content: + if isinstance(part, dict) and part.get("type") in (None, "text", "input_text") and isinstance(part.get("text"), str): + pos = part["text"].find(anchor) + if pos >= 0: + new_parts.append({**part, "text": part["text"][:pos] + self.PREFIX_END}) + found = True + break + new_parts.append(part) + if found: + cut_msgs = list(messages[:idx]) + [{**messages[idx], "content": new_parts}] + head = self._head_prefix_ids(cut_msgs, tools, kwargs, strip_inkling_effort=True) + break + if head is None: + print("[strata] strata_pin.anchor not found in system prompt; using full system prefix", flush=True) + if head is None: + if sys_end == 0 and not tools: + raise ValueError("strata_pin requires a system prompt or tools prefix") + head = self._head_prefix_ids(messages[:sys_end], tools, kwargs, strip_inkling_effort=True) + n = self._lcp_len(head, ids) + if n < 1: + raise ValueError("strata_pin produced an empty static prefix") + return list(ids[:n]) + + def _pin_file_path(self, name: str) -> str | None: + if self.pin_dir or self.cache_dir: + return None # --pin-dir already configured on the engine + d = self.default_pin_dir() + if d is None: + return None + d.mkdir(parents=True, exist_ok=True) + return str(d / f"{name}.bin") + + def _send_pin_cur(self, name: str, resident: str = "ram", path: str | None = None) -> dict: + if hasattr(self.engine, "pin_cur"): + return self.engine.pin_cur(name, resident=resident, path=path) + if hasattr(self.engine, "session_file"): + parts = [name, f"resident={resident}"] + if path: + parts.append(f"path={path}") + return self.engine.session_file("pin_cur", " ".join(parts)) + raise ValueError("this engine does not support named prefix pinning (PIN_CUR)") + + def pin_prefix(self, name: str, prefix_ids: list[int], resident: str = "ram", cancel=None) -> dict: + """Prefill `prefix_ids` and capture into named Host-RAM slot `name` (preemptible by interactive requests).""" + if getattr(self.engine, "batch", 0): + raise ValueError('strata_pin is not available with parallel requests ("parallel" / --batch)') + + class _CombinedCancel: + _fast_poll = True + + def __init__(self, primary, preempt): + self._primary, self._preempt = primary, preempt + + def is_set(self) -> bool: + return (self._primary is not None and self._primary.is_set()) or self._preempt.is_set() + + with self._pin_lock: + preempted = 0 + pin_path = self._pin_file_path(name) + while True: + if cancel is not None and cancel.is_set(): + raise QueueCancelled("the client disconnected while waiting to pin prefix") + with self.status_lock: + while self.real_requests_pending > 0: + if cancel is not None and cancel.is_set(): + raise QueueCancelled("the client disconnected while waiting to pin prefix") + self.pin_idle_cond.wait(timeout=0.1) + with self.fifo: + if self.pin_preempt.is_set(): + preempted += 1 + continue + self.ensure_loaded() + if self.pin_preempt.is_set(): + preempted += 1 + continue + t0 = time.perf_counter() + warm_cancel = _CombinedCancel(cancel, self.pin_preempt) + gen = self.engine.generate(prefix_ids, 0, {}, warm_cancel, prefill_only=True) + try: + for _ in gen: + if self.pin_preempt.is_set() or (cancel is not None and cancel.is_set()): + break + finally: + gen.close() + if self.pin_preempt.is_set() and not (cancel is not None and cancel.is_set()): + preempted += 1 + print(f"[strata] strata_pin '{name}': preempted by interactive request; retrying when idle", + flush=True) + continue + if cancel is not None and cancel.is_set(): + raise QueueCancelled("the client disconnected during prefix prefill") + last = dict(getattr(self.engine, "last", None) or {}) + reused = int(last.get("reused") or 0) + prompt_ms = float(last.get("prompt_ms") or ((time.perf_counter() - t0) * 1000.0)) + t_pin = time.perf_counter() + pin_res = self._send_pin_cur(name, resident=resident, path=pin_path) + pin_ms = float(pin_res.get("ms") or ((time.perf_counter() - t_pin) * 1000.0)) + return { + "name": name, + "tokens": int(pin_res.get("tokens") or len(prefix_ids)), + "bytes": int(pin_res.get("bytes") or 0), + "resident": resident, + "cached_tokens": reused, + "prompt_tokens": len(prefix_ids), + "prompt_ms": round(prompt_ms, 1), + "pin_ms": round(pin_ms, 1), + "preempted": preempted, + "status": "pinned", + } + def drop_embeddings(self) -> None: """Delete the combined image file prepare() wrote when no run() took it over (a run deletes its own as it ends): a request can end before its answer starts - its client gone, anything raised after prepare() - and @@ -6459,6 +6749,7 @@ def _cut(evs): if emb and getattr(self.engine, "split_engine", False) is not True: sampling = {**(sampling or {}), "image_pad": self.embeddings.pad} self.warm_stop.set() # a warm read (start_warm()) gives way + real_counted = False if self.warm_start and tools and not emb: self.keep_start(ids) img_keys, self.embeddings.keys = getattr(self.embeddings, "keys", None), None @@ -6507,6 +6798,10 @@ def replica_selected(index: int) -> None: self._terminal_event_locked(request_id, "queued") queued_counted = True try: + with self.status_lock: + self.real_requests_pending += 1 + self.pin_preempt.set() + real_counted = True # --batch: the engine runs several requests at once (StrataEngine.generate_batched orders them) turn = contextlib.ExitStack() if not par: @@ -6991,6 +7286,11 @@ def replica_selected(index: int) -> None: raise finally: with self.status_lock: + if real_counted: + self.real_requests_pending = max(0, self.real_requests_pending - 1) + if self.real_requests_pending == 0: + self.pin_preempt.clear() + self.pin_idle_cond.notify_all() if queued_counted: self.status["queued"] -= 1 self.terminal_requests.pop(request_id, None) @@ -8671,6 +8971,7 @@ def _captured(self, items, api): def _openai(self, req): req = svc.with_shared(req, "openai") + pin_spec = parse_strata_pin(req) bias_api.normalize(req.get("logit_bias"), len(getattr(svc.tok, "tokens", ())) or None) messages, tools, kw = openai_to_messages(req) require_messages(messages) # an empty conversation is a 400, as OpenAI answers it, not a reply to nothing @@ -8722,13 +9023,49 @@ def _openai(self, req): check_request_sampling(req) # ... and a sampling field of the wrong type cancel = self.cancel # watched since _post() (#430 #431 #1999) ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force, req=req, cancel=cancel) + pin_resolved = req.pop("_strata_pin_resolved", None) _debug_req("openai", req, messages, tools, max_new, thinking, len(ids)) - run = run_with_mcp(svc, svc.mcp, messages, tools, kw, ids, thinking, max_new, max_req, req, cancel, - {t["name"] for t in extra}) if use_mcp else None - chunks = openai_chunks(svc, req, ids, thinking, tools, max_new, cancel, run=run, force=force) - if validator is not None: - chunks = structured_chunks(chunks, validator) - chunks = self._capture(chunks, "openai") + if pin_resolved is not None and pin_resolved["prefill_only"]: + pin_info = svc.pin_prefix(pin_resolved["name"], pin_resolved["prefix_ids"], + resident=pin_resolved["resident"], cancel=cancel) + cid = "chatcmpl-" + uuid.uuid4().hex[:24] + created = int(time.time()) + model = svc.model_for(req) + usage = { + "prompt_tokens": pin_info["prompt_tokens"], + "completion_tokens": 0, + "total_tokens": pin_info["prompt_tokens"], + "prompt_tokens_details": {"cached_tokens": pin_info["cached_tokens"]}, + } + + def pin_chunks(): + yield {"id": cid, "object": "chat.completion.chunk", "created": created, "model": model, + "choices": [{"index": 0, "delta": {"role": "assistant", "content": ""}, + "finish_reason": None}]} + yield {"id": cid, "object": "chat.completion.chunk", "created": created, "model": model, + "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}], + "usage": usage, "strata_pin": pin_info} + + chunks = self._capture(pin_chunks(), "openai") + else: + pin_info = None + if pin_resolved is not None: + pin_info = svc.pin_prefix(pin_resolved["name"], pin_resolved["prefix_ids"], + resident=pin_resolved["resident"], cancel=cancel) + run = run_with_mcp(svc, svc.mcp, messages, tools, kw, ids, thinking, max_new, max_req, req, cancel, + {t["name"] for t in extra}) if use_mcp else None + base_chunks = openai_chunks(svc, req, ids, thinking, tools, max_new, cancel, run=run, force=force) + if pin_info is not None: + def with_pin(src): + for c in src: + if c is not None and c.get("usage") is not None: + c = {**c, "strata_pin": pin_info} + yield c + base_chunks = with_pin(base_chunks) + chunks = base_chunks + if validator is not None: + chunks = structured_chunks(chunks, validator) + chunks = self._capture(chunks, "openai") if not req.get("stream"): return self._json(200, openai_collect(chunks)) self._sse() @@ -9438,6 +9775,9 @@ def number(key, kind, words): "anthropic_think_unasked": mode == "model", "tool_call_recovery": flag("tool_call_recovery"), # opt-in: see OutputParser's recover "warm_start": warm, # opt-in: see Service.start_warm + "pin_dir": over["pin_dir"] if "pin_dir" in over else cfg.get("pin_dir") or None, + "cache_dir": over["cache_dir"] if "cache_dir" in over else cfg.get("cache_dir") or None, + "pin_cache_mib": over["pin_cache_mib"] if "pin_cache_mib" in over else number("pin_cache_mib", int, "a whole number of MiB"), "repeat_stop_tokens": rs, "reasoning_budget_tokens": budget if budget is not None else 0, "reasoning_loop_recovery": loops, @@ -9799,6 +10139,12 @@ def notify_lifecycle(kind: str, payload: dict) -> None: ap.add_argument("--slot-save-path", default=None, metavar="DIR", help="enable POST /slots/0?action=save|restore {\"filename\": NAME} (llama-server's API): the " "conversation the engine holds, to or from DIR/NAME (also \"slot_save_path\" in the config)") + ap.add_argument("--pin-dir", default=None, metavar="DIR", + help="opt-in directory for persisted .bin Host-RAM prefix pins (also \"pin_dir\" in the config)") + ap.add_argument("--cache-dir", default=None, metavar="DIR", + help="opt-in cache directory (/pins holds persisted prefix pins; also \"cache_dir\" in the config)") + ap.add_argument("--pin-cache-mib", type=int, default=None, metavar="MIB", + help="RAM budget in MiB for named pinned prefixes (default 0 = unlimited)") ap.add_argument("--replicas", type=int, default=None, metavar="N", help="data-parallel replicas (opt-in): cut the \"gpu\" list into N equal groups and run one engine on " "each, requests spread over them (also \"replicas\" in the config: a number, or " @@ -9898,9 +10244,21 @@ def request_stop(reason: str): "prefill_gpu": int(pair[0]), "decode_gpu": int(pair[1])} if a.gpu is not None: cfg_overrides["gpu"] = int(a.gpu) if a.gpu.strip().isdigit() else a.gpu + if a.pin_dir is not None: + cfg_overrides["pin_dir"] = a.pin_dir + if a.cache_dir is not None: + cfg_overrides["cache_dir"] = a.cache_dir + if a.pin_cache_mib is not None: + if a.pin_cache_mib < 0: + ap.error("--pin-cache-mib must be 0 or more") + cfg_overrides["pin_cache_mib"] = a.pin_cache_mib # (the file was read above, its saved tuning, --parallel, --batch-groups and --split-serve put on it: read again, # it lost them, and a server started with --parallel 16 answered one request at a time) cfg = {**cfg, **cfg_overrides} if a.config else dict(cfg_overrides) + if a.config and not cfg.get("pin_dir") and not cfg.get("cache_dir"): + default_pins = Path(a.config).with_name(Path(a.config).stem + ".pins") + if default_pins.is_dir() and any(default_pins.glob("*.bin")): + cfg["_existing_pin_dir"] = str(default_pins) a.host = a.host or cfg.get("host") or "127.0.0.1" # issue #26: the run scripts pass no --host, the config can supplied_args = argv if argv is not None else sys.argv[1:] if ("STRATA_API_KEY" in os.environ and not os.environ["STRATA_API_KEY"].strip()) or \ @@ -9959,6 +10317,12 @@ def request_stop(reason: str): lazy = False overrides = {"fit_max_tokens": True if a.fit_max_tokens else False if a.no_fit_max_tokens else None, "idle_unload_s": a.idle_unload, "min_free_vram_mib": a.min_free_vram_mib, "before_load": a.before_load} + if a.pin_dir is not None: + overrides["pin_dir"] = a.pin_dir + if a.cache_dir is not None: + overrides["cache_dir"] = a.cache_dir + if a.pin_cache_mib is not None: + overrides["pin_cache_mib"] = a.pin_cache_mib try: settings = model_settings(cfg, overrides) # #37: the model's own settings, read again at every switch except ValueError as e: diff --git a/terminal/serve/server_parts/openai_api.py b/terminal/serve/server_parts/openai_api.py index 961b71a64..280579d61 100644 --- a/terminal/serve/server_parts/openai_api.py +++ b/terminal/serve/server_parts/openai_api.py @@ -207,6 +207,8 @@ def openai_collect(chunks) -> dict: out["strata_rejected_tool_calls"] = last["strata_rejected_tool_calls"] if last.get("strata_unread_tool_markup"): out["strata_unread_tool_markup"] = last["strata_unread_tool_markup"] + if last.get("strata_pin"): + out["strata_pin"] = last["strata_pin"] return out diff --git a/terminal/serve/test_inkling.py b/terminal/serve/test_inkling.py index 4e9d1ab02..6d3c46ad7 100644 --- a/terminal/serve/test_inkling.py +++ b/terminal/serve/test_inkling.py @@ -20,6 +20,7 @@ import threading import unittest from pathlib import Path +from unittest import mock ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT / "tools")) @@ -558,6 +559,68 @@ def test_a_forced_call_without_thinking_replaces_the_text_block(self): text = self.tok.decode(ids) self.assertTrue(text.endswith(f"<|message_user|><|content_text|>q{END}" + force), text[-120:]) + def test_keep_start_captures_tools_and_system_before_thinking_effort(self): + import serve.server as server + with tempfile.TemporaryDirectory() as d: + cfg = Path(d) / "strata-inkling.json" + cfg.write_text("{}", encoding="utf-8") + self.svc.config_path = str(cfg) + long_sys = "Static system prompt instruction block. " * 90 + msgs = [{"role": "system", "content": long_sys}, {"role": "user", "content": "Hello"}] + ids = self.svc.encode_prompt(msgs, self.TOOLS, {}) + with mock.patch.object(server, "WARM_MIN_TOKENS", 64): + self.svc.keep_start(ids) + kept_txt = self.tok.decode(self.svc.warm_ids) + self.assertIn("tool_declare", kept_txt) + self.assertIn(long_sys, kept_txt) + self.assertNotIn("Thinking effort level:", kept_txt) + self.assertNotIn("<|message_user|>", kept_txt) + + def test_strata_pin_prefix_with_and_without_anchor(self): + static_sys = "You are Meta agent. Follow every rule carefully." + anchor = "\n\n" + dynamic_tail = "Session date: 2026-11-25." + # Case A: anchor present in system prompt -> truncates right before anchor, keeps tool_declare + static_sys + req_anchored = { + "messages": [{"role": "system", "content": static_sys + anchor + dynamic_tail}, + {"role": "user", "content": "ping"}], + "tools": [{"type": "function", "function": self.TOOLS[0]}], + "strata_pin": {"name": "meta", "prefill_only": True, "anchor": anchor}, + } + ids_a, _, max_a = self.svc.prepare(*openai_to_messages(req_anchored)[:3], 0, req=req_anchored) + self.assertEqual(max_a, 0) + pin_a = self.tok.decode(req_anchored["_strata_pin_resolved"]["prefix_ids"]) + self.assertIn("tool_declare", pin_a) + self.assertIn(static_sys, pin_a) + self.assertNotIn("LINGER_STATIC_PREFIX_END", pin_a) + self.assertNotIn(dynamic_tail, pin_a) + self.assertNotIn("Thinking effort level:", pin_a) + self.assertNotIn("<|message_user|>", pin_a) + + # Normal follow-up turn without anchor shares exact prefix even across different efforts + for eff in ("low", "high", "none"): + follow = {"messages": [{"role": "system", "content": static_sys + dynamic_tail}, + {"role": "user", "content": "Real query"}], + "tools": [{"type": "function", "function": self.TOOLS[0]}], + "reasoning_effort": eff} + f_ids = self.svc.encode_prompt(*openai_to_messages(follow)) + self.assertEqual(f_ids[:len(req_anchored["_strata_pin_resolved"]["prefix_ids"])], + req_anchored["_strata_pin_resolved"]["prefix_ids"]) + + # Case B: anchor omitted -> renders tools + full system turn before Thinking effort level & user turn + req_auto = { + "messages": [{"role": "system", "content": static_sys}, {"role": "user", "content": "warmup"}], + "tools": [{"type": "function", "function": self.TOOLS[0]}], + "max_tokens": 1, + "strata_pin": {"name": "meta", "prefill_only": True, "resident": "ram"}, + } + self.svc.prepare(*openai_to_messages(req_auto)[:3], 1, req=req_auto) + pin_b = self.tok.decode(req_auto["_strata_pin_resolved"]["prefix_ids"]) + self.assertIn("tool_declare", pin_b) + self.assertIn(static_sys, pin_b) + self.assertNotIn("Thinking effort level:", pin_b) + self.assertNotIn("<|message_user|>", pin_b) + class Pictures(unittest.TestCase): """A picture in a user or tool turn: the template writes <|content_image|><|unused_200054|> in a block of its own, diff --git a/terminal/serve/test_server.py b/terminal/serve/test_server.py index 392f8a884..ecda40107 100644 --- a/terminal/serve/test_server.py +++ b/terminal/serve/test_server.py @@ -4013,7 +4013,7 @@ def test_a_known_key_with_a_bad_value_is_named_and_skipped(self): self.assertIn("top_p", said[0]) def test_several_bad_keys_are_each_named(self): - got, said = self.load('{"reasoning_effort": "medium", "nope": 1, "top_k": 900}') + got, said = self.load('{"reasoning_effort": "medium", "nope": 1, "top_k": -1}') self.assertEqual(got, {"reasoning_effort": "medium"}) self.assertEqual(len(said), 2) @@ -8170,3 +8170,243 @@ def test_falsy_non_object_values_are_ignored_as_before(self): with self.subTest(chat_template_kwargs=ctk): status, b = self.post({"model": "x", "max_tokens": 8, "messages": msgs, "chat_template_kwargs": ctk}) self.assertEqual(status, 200, b) + + +class _MultiPinMockEngine(MockEngine): + """Simulates multi-slot Host-RAM prefix pinning (`PIN_CUR`, `PIN_LOAD`, `GEN 0 prefill=1`).""" + + def __init__(self, tok, reply="ok", max_context=CTX, prefill_chunk_delay_s=0.0): + super().__init__(tok, reply, max_context=max_context) + self.info = {"sessions": 1, "pinned_tokens": 0, "pinned_slots": 0} + self.pins: dict[str, list[int]] = {} + self.cur_ids: list[int] = [] + self.calls: list[tuple[list[int], int, bool]] = [] + self.prefill_chunk_delay_s = prefill_chunk_delay_s + self.started_prefill = threading.Event() + + def generate(self, ids, max_new, sampling, cancel, embeddings=None, prefill_only=False): + best_pin = max( + (len(os.path.commonprefix([p_ids, list(ids)])) for p_ids in self.pins.values()), + default=0, + ) + cur_same = len(os.path.commonprefix([self.cur_ids, list(ids)])) + reused = max(best_pin, cur_same) + self.calls.append((list(ids), max_new, bool(prefill_only))) + if prefill_only: + self.started_prefill.set() + if self.prefill_chunk_delay_s > 0: + deadline = time.monotonic() + self.prefill_chunk_delay_s + while time.monotonic() < deadline: + if cancel is not None and cancel.is_set(): + self.last = {"generated": 0, "prompt_tokens": len(ids), "prompt_ms": 1.0, + "decode_ms": 0.0, "finish": "cancel", "reused": reused, + "prompt_read": max(0, len(ids) - reused)} + return + time.sleep(0.01) + self.cur_ids = list(ids) + self.last = {"generated": 0, "prompt_tokens": len(ids), "prompt_ms": 5.0, + "decode_ms": 0.0, "finish": "stop", "reused": reused, + "prompt_read": max(0, len(ids) - reused)} + yield None + return + self.cur_ids = list(ids) + emitted = 0 + try: + for t in super().generate(ids, max_new, sampling, cancel, embeddings): + if t is not None: + emitted += 1 + self.last = {"generated": emitted, "prompt_tokens": len(ids), "prompt_ms": 5.0, + "decode_ms": 5.0, "finish": "stop", "reused": reused, + "prompt_read": max(0, len(ids) - reused)} + yield t + finally: + self.last = {"generated": emitted, "prompt_tokens": len(ids), "prompt_ms": 5.0, + "decode_ms": 5.0, "finish": "stop", "reused": reused, + "prompt_read": max(0, len(ids) - reused)} + + def pin_cur(self, name, resident="ram", path=None, save=None): + self.pins[name] = list(self.cur_ids) + if path: + Path(path).parent.mkdir(parents=True, exist_ok=True) + Path(path).write_text(json.dumps(self.cur_ids), encoding="utf-8") + return {"tokens": len(self.cur_ids), "bytes": len(self.cur_ids) * 64, "ms": 1.0} + + def pin_load(self, name, path): + ids = json.loads(Path(path).read_text(encoding="utf-8")) + self.pins[name] = ids + return {"tokens": len(ids), "bytes": len(ids) * 64, "ms": 1.0} + + +class StrataPinHttpAndPreemption(unittest.TestCase): + """WHI-1016: OpenAI /v1/chat/completions `strata_pin`, multi-slot pins, restart reload, and preemption.""" + + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.cfg_path = Path(self.dir.name) / "strata-m.json" + self.cfg_path.write_text("{}", encoding="utf-8") + self.tok = ByteTokenizer() + self.engine = _MultiPinMockEngine(self.tok, "ok", max_context=CTX) + self.svc = Service(self.engine, self.tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.svc.config_path = str(self.cfg_path) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + self.dir.cleanup() + + def post(self, body): + req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=30) as r: + return r.status, json.loads(r.read()) + except urllib.error.HTTPError as e: + with e: + return e.code, json.loads(e.read()) + + def test_max_tokens_zero_and_one_with_prefill_only_and_multi_slot_hits(self): + meta_sys = "Meta static instructions carefully followed." + alter_sys = "Alter ego static system persona rules." + anchor = "" + tail = " Dynamic timestamp: 2026-11-25." + + # max_tokens: 0 + prefill_only: true + anchor + st, r1 = self.post({ + "model": "x", "max_tokens": 0, + "messages": [{"role": "system", "content": meta_sys + anchor + tail}, + {"role": "user", "content": "warmup"}], + "strata_pin": {"name": "meta", "prefill_only": True, "resident": "ram", "anchor": anchor}, + }) + self.assertEqual(st, 200, r1) + self.assertEqual(r1["choices"][0]["message"]["content"], "") + self.assertEqual(r1["choices"][0]["finish_reason"], "stop") + self.assertEqual(r1["usage"]["completion_tokens"], 0) + self.assertEqual(r1["strata_pin"]["name"], "meta") + self.assertEqual(r1["strata_pin"]["status"], "pinned") + self.assertIn(meta_sys, self.tok.decode(self.engine.pins["meta"])) + self.assertNotIn(anchor, self.tok.decode(self.engine.pins["meta"])) + self.assertNotIn(tail, self.tok.decode(self.engine.pins["meta"])) + + # max_tokens: 1 + prefill_only: true (Bifrost passthrough compat) without anchor + st, r2 = self.post({ + "model": "x", "max_tokens": 1, + "messages": [{"role": "system", "content": alter_sys}, + {"role": "user", "content": "warmup"}], + "strata_pin": {"name": "alter_ego", "prefill_only": True, "resident": "ram"}, + }) + self.assertEqual(st, 200, r2) + self.assertEqual(r2["usage"]["completion_tokens"], 0) + self.assertEqual(r2["strata_pin"]["name"], "alter_ego") + self.assertIn(alter_sys, self.tok.decode(self.engine.pins["alter_ego"])) + + # Bifrost clamped shape: max_tokens deleted, clamped to max_completion_tokens=16 + prefill_only: true + st, r2_bf = self.post({ + "model": "x", "max_completion_tokens": 16, + "messages": [{"role": "system", "content": alter_sys}, + {"role": "user", "content": "warmup"}], + "strata_pin": {"name": "alter_ego", "prefill_only": True, "resident": "ram"}, + }) + self.assertEqual(st, 200, r2_bf) + self.assertEqual(r2_bf["choices"][0]["message"]["content"], "") + self.assertEqual(r2_bf["choices"][0]["finish_reason"], "stop") + self.assertEqual(r2_bf["usage"]["completion_tokens"], 0) + self.assertEqual(r2_bf["strata_pin"]["status"], "pinned") + + # Normal requests with NO strata_pin hit both pinned slots alternately + st, chat1 = self.post({ + "model": "x", "max_tokens": 8, + "messages": [{"role": "system", "content": meta_sys + tail}, + {"role": "user", "content": "hello meta"}], + }) + self.assertEqual(st, 200, chat1) + self.assertEqual(chat1["usage"]["prompt_tokens_details"]["cached_tokens"], len(self.engine.pins["meta"])) + + st, chat2 = self.post({ + "model": "x", "max_tokens": 8, + "messages": [{"role": "system", "content": alter_sys}, + {"role": "user", "content": "hello alter"}], + }) + self.assertEqual(st, 200, chat2) + self.assertEqual(chat2["usage"]["prompt_tokens_details"]["cached_tokens"], len(self.engine.pins["alter_ego"])) + + # Restart reload from persisted .bin files + engine2 = _MultiPinMockEngine(self.tok, "ok", max_context=CTX) + svc2 = Service(engine2, self.tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + svc2.config_path = str(self.cfg_path) + svc2.load_saved_pins() + self.assertEqual(set(engine2.pins), {"meta", "alter_ego"}) + + def test_streaming_and_validation_and_default_cli_args_byte_identical(self): + # Invalid strata_pin specs return HTTP 400 cleanly + for bad in ("meta", {"name": "../bad"}, {"name": "ok", "resident": "nvme"}, + {"name": "ok", "prefill_only": "yes"}, {"name": "ok", "extra": 1}): + st, body = self.post({"model": "x", "max_tokens": 1, + "messages": [{"role": "system", "content": "sys"}, + {"role": "user", "content": "hi"}], + "strata_pin": bad}) + self.assertEqual(st, 400, (bad, body)) + + # Streaming prefill_only emits valid OpenAI SSE chunks + usage + [DONE] + req = urllib.request.Request( + self.base + "/v1/chat/completions", + data=json.dumps({ + "model": "x", "max_tokens": 1, "stream": True, + "messages": [{"role": "system", "content": "Streamed system prompt."}], + "strata_pin": {"name": "stream_pin", "prefill_only": True}, + }).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(req, timeout=30) as r: + raw = r.read().decode("utf-8") + self.assertIn("data: [DONE]", raw) + self.assertIn('"finish_reason": "stop"', raw) + self.assertIn('"completion_tokens": 0', raw) + + # Default path without opt-in flags produces byte-identical engine_args + base_cfg = {"exe": "strata-poly", "args": ["--model", "m.gguf"]} + self.assertEqual(engine_args(base_cfg), ["--model", "m.gguf"]) + opted_in = {**base_cfg, "pin_dir": self.dir.name, "pin_cache_mib": 1024} + self.assertEqual(engine_args(opted_in), + ["--model", "m.gguf", "--pin-dir", os.path.abspath(self.dir.name), "--pin-cache-mib", "1024"]) + + def test_warmup_preempted_by_interactive_request_and_retries_when_idle(self): + slow = _MultiPinMockEngine(self.tok, "ok", max_context=CTX, prefill_chunk_delay_s=0.4) + svc = Service(slow, self.tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + results = {} + + def run_warmup(): + req = urllib.request.Request( + base + "/v1/chat/completions", + data=json.dumps({ + "model": "x", "max_tokens": 1, + "messages": [{"role": "system", "content": "Long system prefix to warm up."}], + "strata_pin": {"name": "preempt_test", "prefill_only": True}, + }).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(req, timeout=30) as r: + results["warm"] = json.loads(r.read()) + + try: + t = threading.Thread(target=run_warmup, daemon=True) + t.start() + self.assertTrue(slow.started_prefill.wait(timeout=5)) + req_real = urllib.request.Request( + base + "/v1/chat/completions", + data=json.dumps({"model": "x", "max_tokens": 16, + "messages": [{"role": "user", "content": "urgent interactive"}]}).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(req_real, timeout=30) as r: + results["real"] = json.loads(r.read()) + t.join(timeout=10) + self.assertEqual(results["real"]["choices"][0]["message"]["content"], "ok") + self.assertGreaterEqual(results["warm"]["strata_pin"]["preempted"], 1) + self.assertEqual(results["warm"]["strata_pin"]["status"], "pinned") + finally: + httpd.shutdown() + httpd.server_close()