feat(runtime): conversation manager: parked conversations, resume choice, checkpoint chain
Port of the conversation block of generate.cpp as a device-independent policy (ConversationManager over a SessionEngine): park_current with the RAM admission rule, the live/checkpoint/parked resume choice, parked-image validation and fallback, steering isolation, the root-pinned turn/periodic checkpoint chain, STRATA_CKPT_REREAD, cancelled prompts and the end-of-request live-state update, plus the PromptPlan bookkeeping hook. Verified three ways: (1) a simulated device whose bytes are a pure function of the token prefix proves that every resume path (live, checkpoint, parked live, parked checkpoint, empty) leaves the device in exactly the state of a fresh read of ids[..resume], across 16 random traffic seeds; (2) scenario tests for A/B/A parking, rewritten tails, pinned root rotation, RAM/byte/slot pressure, invalid and failing restores; (3) a differential test against 28 random + 4 scripted (#342 sub-agent) traces generated by the transliterated C++ policy running over the real ConversationCache/eviction_victim/memory admission. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
de51dbb0f0
commit
fc0fcd7b4b
@@ -1,7 +1,7 @@
|
||||
//! Native and explicitly selected experimental CUDA owner actor.
|
||||
//! CUDA owners and borrowed buffers remain ordinary locals on that thread.
|
||||
#[path = "backend_original_prompt.rs"]
|
||||
mod original_prompt;
|
||||
pub(crate) mod original_prompt;
|
||||
pub use crate::model_binding::qwen4exp_kar_ple::InheritedKarArchive;
|
||||
#[path = "backend_measurement.rs"]
|
||||
mod measurement;
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//! Binding of the conversation policy to a session's device state: the
|
||||
//! [`SessionEngine`] over any [`StateMemory`] that can also zero a session and
|
||||
//! resynchronise the drafter. Production implements `SessionDevice` on the CUDA
|
||||
//! owners of the session (see the CUDA-driver conversation device); tests use
|
||||
//! host memory.
|
||||
|
||||
use super::cache::{ConversationCheckpoint, ConversationKvReuse, SavedConversation};
|
||||
use super::manager::SessionEngine;
|
||||
use super::memory::available_memory;
|
||||
use super::model::{ConvError, ConvResult, ModelGeometry, QsaDesc, SessionSpec, StateMemory};
|
||||
use super::snapshot::{
|
||||
ConversationView, RestoreOutcome, snapshot_bytes, snapshot_capture_bytes, snapshot_restore,
|
||||
snapshot_save, snapshot_validate,
|
||||
};
|
||||
use super::state::{checkpoint_restore, checkpoint_save};
|
||||
|
||||
/// Session operations beyond raw state access.
|
||||
pub trait SessionDevice: StateMemory {
|
||||
/// `session_zero` plus stream synchronisation: a fresh sequence.
|
||||
fn zero_session(&mut self) -> Result<(), String>;
|
||||
/// `mtp.kv_restore(resume)`.
|
||||
fn restore_draft(&mut self, resume: usize) -> Result<(), String>;
|
||||
/// Control-vector enable state for the next request.
|
||||
fn set_steering(&mut self, _enabled: bool) {}
|
||||
/// Available host physical memory; unknown by default off Linux.
|
||||
fn available_memory(&mut self) -> Option<u64> {
|
||||
available_memory()
|
||||
}
|
||||
}
|
||||
|
||||
/// [`SessionEngine`] over one session's geometry, carve and draft state.
|
||||
pub struct DeviceEngine<'a, D: SessionDevice> {
|
||||
pub device: &'a mut D,
|
||||
pub geometry: &'a ModelGeometry,
|
||||
pub session: &'a SessionSpec,
|
||||
pub draft: &'a QsaDesc,
|
||||
}
|
||||
|
||||
fn device_error(what: &str, message: String) -> ConvError {
|
||||
ConvError(format!("{what}: {message}"))
|
||||
}
|
||||
|
||||
impl<D: SessionDevice> SessionEngine for DeviceEngine<'_, D> {
|
||||
fn snapshot_bytes(&mut self, view: &ConversationView<'_>) -> ConvResult<usize> {
|
||||
snapshot_bytes(view, self.session, self.geometry, self.draft)
|
||||
}
|
||||
|
||||
fn snapshot_capture_bytes(
|
||||
&mut self,
|
||||
reuse: &ConversationKvReuse,
|
||||
view: &ConversationView<'_>,
|
||||
) -> ConvResult<usize> {
|
||||
snapshot_capture_bytes(reuse, view, self.session, self.geometry, self.draft)
|
||||
}
|
||||
|
||||
fn snapshot_save(
|
||||
&mut self,
|
||||
view: &ConversationView<'_>,
|
||||
reuse: ConversationKvReuse,
|
||||
reused_bytes: &mut usize,
|
||||
) -> ConvResult<SavedConversation> {
|
||||
snapshot_save(
|
||||
view,
|
||||
self.session,
|
||||
self.geometry,
|
||||
self.draft,
|
||||
self.device,
|
||||
reuse,
|
||||
Some(reused_bytes),
|
||||
)
|
||||
}
|
||||
|
||||
fn snapshot_validate(&mut self, image: &SavedConversation) -> ConvResult<()> {
|
||||
snapshot_validate(image, self.session, self.geometry, self.draft)
|
||||
}
|
||||
|
||||
fn snapshot_restore(&mut self, image: &SavedConversation) -> RestoreOutcome {
|
||||
snapshot_restore(image, self.session, self.geometry, self.draft, self.device)
|
||||
}
|
||||
|
||||
fn checkpoint_save(&mut self, c: &mut ConversationCheckpoint) -> ConvResult<()> {
|
||||
checkpoint_save(c, self.session, self.geometry, self.device)
|
||||
}
|
||||
|
||||
fn checkpoint_restore(&mut self, c: &ConversationCheckpoint) -> ConvResult<()> {
|
||||
checkpoint_restore(c, self.session, self.geometry, self.device)
|
||||
}
|
||||
|
||||
fn synchronize(&mut self) -> ConvResult<()> {
|
||||
self.device
|
||||
.synchronize()
|
||||
.map_err(|message| device_error("conversation snapshot synchronize", message))
|
||||
}
|
||||
|
||||
fn zero_session(&mut self) -> ConvResult<()> {
|
||||
self.device
|
||||
.zero_session()
|
||||
.map_err(|message| device_error("zeroing the session", message))
|
||||
}
|
||||
|
||||
fn restore_draft(&mut self, resume: usize) -> ConvResult<()> {
|
||||
self.device
|
||||
.restore_draft(resume)
|
||||
.map_err(|message| device_error("restoring the draft ring", message))
|
||||
}
|
||||
|
||||
fn set_steering(&mut self, enabled: bool) {
|
||||
self.device.set_steering(enabled);
|
||||
}
|
||||
|
||||
fn available_memory(&mut self) -> Option<u64> {
|
||||
self.device.available_memory()
|
||||
}
|
||||
}
|
||||
@@ -17,3 +17,6 @@ $cxx $flags "$here/gen_state_golden.cpp" "$strata/src/core/conversation_state.cp
|
||||
"$strata/src/core/conversation_snapshot.cpp" -o "$tmp/gen_state"
|
||||
"$tmp/gen_state" > "$here/state_golden.json"
|
||||
echo "wrote $here/state_golden.json"
|
||||
$cxx $flags "$here/gen_manager_golden.cpp" -o "$tmp/gen_manager"
|
||||
"$tmp/gen_manager" > "$here/manager_golden.json"
|
||||
echo "wrote $here/manager_golden.json"
|
||||
|
||||
@@ -0,0 +1,423 @@
|
||||
// Golden-fixture generator for the Rust conversation manager.
|
||||
//
|
||||
// The conversation block of generate.cpp (park_current, the resume choice at
|
||||
// the head of a request, checkpoint_at, the periodic prompt checkpoint, the
|
||||
// turn/root segment loop and the end-of-request live update) lives inside a
|
||||
// 6,600-line CUDA translation unit and cannot be compiled on its own. Its
|
||||
// statements are transliterated here VERBATIM in structure (same order, same
|
||||
// conditions, same clock/LRU updates) against the real, unmodified
|
||||
// ConversationCache, eviction_victim and memory admission, with a synthetic
|
||||
// "device": snapshots carry fixed-size payloads and no CUDA is touched. The
|
||||
// resulting per-request decisions and cache state are the oracle that the
|
||||
// Rust ConversationManager must reproduce.
|
||||
#include "strata/core/conversation_cache.hpp"
|
||||
#include "strata/core/conversation_memory.hpp"
|
||||
#include "strata/program/conv_cache.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace strata::core;
|
||||
using ImgKey = ConversationImageKey;
|
||||
using ConvCheckpoint = ConversationCheckpoint;
|
||||
|
||||
namespace {
|
||||
struct Rng {
|
||||
uint64_t s;
|
||||
explicit Rng(uint64_t seed) : s(seed * 6364136223846793005ULL + 1442695040888963407ULL) {}
|
||||
uint64_t next() { s = s * 6364136223846793005ULL + 1442695040888963407ULL; return s >> 33; }
|
||||
uint64_t below(uint64_t n) { return n ? next() % n : 0; }
|
||||
};
|
||||
|
||||
template<class T> std::string arr(const std::vector<T>& v) {
|
||||
std::string out = "[";
|
||||
for (size_t i = 0; i < v.size(); ++i) out += (i ? "," : "") + std::to_string(v[i]);
|
||||
return out + "]";
|
||||
}
|
||||
// Token arrays are mostly consecutive runs: [start, length] pairs keep the fixture small.
|
||||
std::string runs_json(const std::vector<int32_t>& v) {
|
||||
std::string out = "[";
|
||||
for (size_t i = 0; i < v.size();) {
|
||||
size_t j = i + 1;
|
||||
while (j < v.size() && v[j] == v[j - 1] + 1) ++j;
|
||||
out += (i ? "," : "") + std::string("[") + std::to_string(v[i]) + "," + std::to_string(j - i) + "]";
|
||||
i = j;
|
||||
}
|
||||
return out + "]";
|
||||
}
|
||||
std::string imgs_json(const std::vector<ImgKey>& v) {
|
||||
std::string out = "[";
|
||||
for (size_t i = 0; i < v.size(); ++i)
|
||||
out += (i ? "," : "") + std::string("[") + std::to_string(v[i].start) + "," + std::to_string(v[i].hash) + "]";
|
||||
return out + "]";
|
||||
}
|
||||
|
||||
struct ConversationView { // the shape of conversation_snapshot.hpp's view, which needs CUDA headers
|
||||
const std::vector<int32_t>& ids;
|
||||
const std::vector<ConversationImageKey>& images;
|
||||
const std::vector<ConversationCheckpoint>& checkpoints;
|
||||
bool cvec;
|
||||
};
|
||||
|
||||
constexpr size_t kPayload = 100; // synthetic running-state payload per checkpoint / live
|
||||
constexpr int64_t kChunk = 256; // batched prompt chunk (request_capacity with an admitted capacity of 256)
|
||||
constexpr int64_t kWindow = 4; // verify-window width (read_windows)
|
||||
constexpr int64_t kShortRead = 64; // windows_ok: at most this many tokens go through the verify windows
|
||||
|
||||
struct Options {
|
||||
int prompt_cache = 6;
|
||||
int64_t prompt_cache_every = 16384;
|
||||
int64_t prompt_cache_root = 2048;
|
||||
int turn_token = 7;
|
||||
size_t cache_bytes = 0;
|
||||
size_t cache_slots = 4;
|
||||
uint64_t min_free = 0;
|
||||
bool reread = false;
|
||||
bool incremental = true;
|
||||
};
|
||||
|
||||
// ---- the generate.cpp state ------------------------------------------------------------------------------------
|
||||
struct Serve {
|
||||
Options o;
|
||||
std::vector<int32_t> live;
|
||||
std::vector<ImgKey> live_imgs;
|
||||
bool live_ok = false;
|
||||
std::vector<ConvCheckpoint> checks;
|
||||
uint64_t check_clock = 0;
|
||||
bool cvec_cached = true;
|
||||
ConversationCache conversations;
|
||||
int64_t pp_next_check = 0;
|
||||
std::optional<uint64_t> available; // injected telemetry
|
||||
bool validate_fails = false; // injected: the next parked image is unusable
|
||||
int parked_events = 0;
|
||||
explicit Serve(const Options& opt) : o(opt), conversations(opt.prompt_cache > 0 ? opt.cache_bytes : 0, opt.cache_slots) {}
|
||||
|
||||
// synthetic device ---------------------------------------------------------------------------------------
|
||||
static SavedConversation image_of(const ConversationView& v) {
|
||||
SavedConversation s;
|
||||
s.live.ids = std::vector<int32_t>(v.ids.begin(), v.ids.end());
|
||||
s.live.imgs = std::vector<ImgKey>(v.images.begin(), v.images.end());
|
||||
s.live.gdn = std::vector<uint8_t>(kPayload, 1);
|
||||
s.cvec = v.cvec;
|
||||
s.checkpoints = v.checkpoints;
|
||||
return s;
|
||||
}
|
||||
|
||||
// ---- park_current (generate.cpp:4415) ---------------------------------------------------------------------
|
||||
void park_current(size_t held) {
|
||||
if (!conversations.enabled() || !live_ok || live.empty()) return;
|
||||
const ConversationView view{live, live_imgs, checks, cvec_cached};
|
||||
auto reuse = conversations.take_reuse();
|
||||
size_t estimate = image_of(view).bytes();
|
||||
const size_t fresh_estimate = estimate;
|
||||
if (!reuse.kv.empty()) { reuse = {}; estimate = fresh_estimate; } // (the synthetic device never retains K/V)
|
||||
conversations.drop_superseded(live, live_imgs, checks, cvec_cached);
|
||||
if (!conversations.make_room(estimate, held)) return;
|
||||
const uint64_t floor = o.min_free;
|
||||
const size_t additional = estimate - reuse.bytes();
|
||||
if (!conversation_memory_admit(available, additional, floor)) return;
|
||||
SavedConversation image = image_of(view);
|
||||
if (!conversation_memory_admit(available, 0, floor)) return;
|
||||
const bool stored = conversations.put(std::move(image), held);
|
||||
if (stored) ++parked_events;
|
||||
}
|
||||
|
||||
static std::vector<ImgKey> imgs_below(const std::vector<ImgKey>& all, int64_t L) {
|
||||
std::vector<ImgKey> v;
|
||||
for (const ImgKey& k : all) if (k.start < L) v.push_back(k);
|
||||
return v;
|
||||
}
|
||||
|
||||
// ---- checkpoint_at (generate.cpp:4495) --------------------------------------------------------------------
|
||||
bool checkpoint_at(int64_t L, const std::vector<int32_t>& cur, const std::vector<ImgKey>& req_imgs) {
|
||||
if (o.prompt_cache <= 0 || L < 1) return true;
|
||||
for (ConvCheckpoint& c : checks)
|
||||
if ((int64_t) c.ids.size() == L) { c.used = ++check_clock; return true; }
|
||||
ConvCheckpoint c;
|
||||
c.ids.assign(cur.begin(), cur.begin() + L);
|
||||
c.imgs = imgs_below(req_imgs, L);
|
||||
c.gdn = std::vector<uint8_t>(kPayload, 2);
|
||||
c.used = ++check_clock;
|
||||
checks.push_back(std::move(c));
|
||||
while ((int) checks.size() > o.prompt_cache) {
|
||||
std::vector<uint64_t> stamps;
|
||||
for (const ConvCheckpoint& k : checks) stamps.push_back(k.used);
|
||||
const size_t victim = strata::program::conv_cache::eviction_victim(stamps.data(), stamps.size(), o.prompt_cache);
|
||||
checks.erase(checks.begin() + (std::ptrdiff_t) victim);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
struct Request {
|
||||
std::vector<int32_t> ids;
|
||||
std::vector<ImgKey> imgs;
|
||||
bool cvec = true;
|
||||
int gen = 1;
|
||||
int stop_after = -1; // cancel before this prompt action (-1: never)
|
||||
int64_t available = -1; // -1: unknown
|
||||
bool validate_fails = false;
|
||||
};
|
||||
|
||||
struct Outcome {
|
||||
int64_t resume = 0;
|
||||
bool from_live = false;
|
||||
bool restored = false;
|
||||
int64_t restored_tokens = 0;
|
||||
bool restored_live = false;
|
||||
int64_t reread_to = -1;
|
||||
int64_t read_from = 0;
|
||||
std::vector<int32_t> consumed;
|
||||
};
|
||||
|
||||
// The request path from `cur = ids` to `finish` (generate.cpp:5013-5640, conversation parts only).
|
||||
Outcome run_request(Serve& S, const Request& r) {
|
||||
Outcome out;
|
||||
S.available = r.available < 0 ? std::nullopt : std::optional<uint64_t>((uint64_t) r.available);
|
||||
S.validate_fails = r.validate_fails;
|
||||
const std::vector<int32_t>& ids = r.ids;
|
||||
const std::vector<ImgKey>& req_imgs = r.imgs;
|
||||
const int64_t n = (int64_t) ids.size();
|
||||
auto starts_with = [&](const std::vector<int32_t>& pre, const std::vector<ImgKey>& pre_imgs) -> bool {
|
||||
const int64_t L = (int64_t) pre.size();
|
||||
if (L < 1 || L > n - 1) return false;
|
||||
for (int64_t i = 0; i < L; ++i)
|
||||
if ((int32_t) ids[(size_t) i] != pre[(size_t) i]) return false;
|
||||
return Serve::imgs_below(req_imgs, L) == pre_imgs;
|
||||
};
|
||||
const bool want_cvec = r.cvec;
|
||||
int64_t resume = 0;
|
||||
bool from_live = false;
|
||||
if (S.o.prompt_cache > 0 && want_cvec == S.cvec_cached) {
|
||||
if (S.live_ok && starts_with(S.live, S.live_imgs)) { resume = (int64_t) S.live.size(); from_live = true; }
|
||||
for (const ConvCheckpoint& c : S.checks)
|
||||
if ((int64_t) c.ids.size() > resume && starts_with(c.ids, c.imgs)) {
|
||||
resume = (int64_t) c.ids.size();
|
||||
from_live = false;
|
||||
}
|
||||
}
|
||||
const auto parked = S.conversations.best(ids, req_imgs, want_cvec);
|
||||
std::optional<SavedConversation> incoming;
|
||||
if (parked.tokens > resume) incoming.emplace(S.conversations.take(parked.index));
|
||||
if (incoming && S.validate_fails) incoming.reset();
|
||||
if ((!from_live || incoming)) S.park_current(incoming ? incoming->bytes() : 0);
|
||||
if (incoming) {
|
||||
S.live = std::move(incoming->live.ids);
|
||||
S.live_imgs = std::move(incoming->live.imgs);
|
||||
S.checks = std::move(incoming->checkpoints);
|
||||
S.cvec_cached = incoming->cvec;
|
||||
resume = parked.tokens;
|
||||
from_live = parked.live;
|
||||
if (S.o.incremental) S.conversations.retain(std::vector<ConversationKv>{}, int64_t(S.live.size()));
|
||||
incoming.reset();
|
||||
out.restored = true; out.restored_tokens = resume; out.restored_live = from_live;
|
||||
}
|
||||
if (want_cvec != S.cvec_cached) {
|
||||
S.live_ok = false;
|
||||
S.checks.clear();
|
||||
S.cvec_cached = want_cvec;
|
||||
}
|
||||
S.checks.erase(std::remove_if(S.checks.begin(), S.checks.end(), [&](const ConvCheckpoint& c) {
|
||||
return (int64_t) c.ids.size() > resume || !starts_with(c.ids, c.imgs);
|
||||
}), S.checks.end());
|
||||
S.live_ok = false;
|
||||
int64_t reread_to = -1;
|
||||
if (resume == 0) {
|
||||
S.checks.clear();
|
||||
} else if (!from_live) {
|
||||
ConvCheckpoint* c = nullptr;
|
||||
for (ConvCheckpoint& k : S.checks) if ((int64_t) k.ids.size() == resume) c = &k;
|
||||
if (c != nullptr) c->used = ++S.check_clock;
|
||||
if (S.o.reread && c != nullptr) reread_to = resume;
|
||||
}
|
||||
const int64_t read_from = reread_to > 0 ? 0 : resume;
|
||||
S.conversations.limit_reuse(read_from);
|
||||
S.pp_next_check = reread_to > 0 ? INT64_MAX : resume + S.o.prompt_cache_every;
|
||||
out.resume = resume; out.from_live = from_live; out.reread_to = reread_to; out.read_from = read_from;
|
||||
|
||||
// ---- the prompt: segments up to the root / the last turn boundary / the last token ------------------------
|
||||
int64_t turn_at = -1;
|
||||
if (S.o.prompt_cache > 0 && S.o.turn_token >= 0)
|
||||
for (int64_t i = n - 1; i > resume; --i)
|
||||
if (ids[(size_t) i] == S.o.turn_token) { turn_at = i; break; }
|
||||
int64_t root_at = -1;
|
||||
if (S.o.prompt_cache > 0 && S.o.turn_token >= 0 && S.o.prompt_cache_root > 0 && read_from == 0)
|
||||
for (int64_t i = 1; i < turn_at; ++i)
|
||||
if (ids[(size_t) i] == S.o.turn_token) {
|
||||
if (i >= S.o.prompt_cache_root) root_at = i;
|
||||
break;
|
||||
}
|
||||
int64_t at = read_from;
|
||||
int actions = 0;
|
||||
bool cancelled = false;
|
||||
for (const int64_t to : {reread_to, root_at, turn_at, n - 1}) {
|
||||
if (to <= at) continue;
|
||||
const bool win = (to - at) <= kShortRead;
|
||||
const int64_t width = win ? kWindow : kChunk;
|
||||
while (at < to) {
|
||||
if (r.stop_after >= 0 && actions == r.stop_after) { cancelled = true; break; }
|
||||
const int64_t count = std::min(width, to - at);
|
||||
at += count;
|
||||
++actions;
|
||||
if (!win) { // sp.run's chunk callback
|
||||
if (S.o.prompt_cache_every > 0 && at >= S.pp_next_check) {
|
||||
S.checkpoint_at(at, ids, req_imgs);
|
||||
S.pp_next_check = at + S.o.prompt_cache_every;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (cancelled) break;
|
||||
if (to == turn_at || to == root_at) S.checkpoint_at(to, ids, req_imgs);
|
||||
}
|
||||
// ---- the decode: consumed = ids[0..n-1) + the last prompt token + all generated tokens but the last -------
|
||||
if (!cancelled) {
|
||||
std::vector<int32_t> consumed(ids.begin(), ids.end());
|
||||
for (int i = 0; i + 1 < r.gen; ++i) consumed.push_back(200000 + (int32_t) ids.size() * 10 + i);
|
||||
out.consumed = consumed;
|
||||
S.live.swap(consumed);
|
||||
S.live_imgs = Serve::imgs_below(req_imgs, (int64_t) S.live.size());
|
||||
S.live_ok = S.o.prompt_cache > 0;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string state_json(const Serve& S) {
|
||||
std::string cps = "[";
|
||||
for (size_t i = 0; i < S.checks.size(); ++i)
|
||||
cps += (i ? "," : "") + std::string("[") + std::to_string(S.checks[i].ids.size()) + "," + std::to_string(S.checks[i].used) + "]";
|
||||
cps += "]";
|
||||
return "{\"live\":" + std::to_string(S.live.size()) + ",\"live_ok\":" + (S.live_ok ? "true" : "false") + ",\"cvec\":" + (S.cvec_cached ? "true" : "false") +
|
||||
",\"checks\":" + cps + ",\"clock\":" + std::to_string(S.check_clock) + ",\"pp_next\":" + std::to_string(S.pp_next_check) +
|
||||
",\"cache\":{\"size\":" + std::to_string(S.conversations.size()) + ",\"bytes\":" + std::to_string(S.conversations.bytes()) +
|
||||
",\"evictions\":" + std::to_string(S.conversations.evictions()) + ",\"superseded\":" + std::to_string(S.conversations.superseded()) +
|
||||
",\"retained\":" + std::to_string(S.conversations.retained_bytes()) + "},\"parks\":" + std::to_string(S.parked_events) + "}";
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::string options_json(const Options& o) {
|
||||
return std::string("{\"prompt_cache\":") + std::to_string(o.prompt_cache) + ",\"every\":" + std::to_string(o.prompt_cache_every) +
|
||||
",\"root\":" + std::to_string(o.prompt_cache_root) + ",\"turn\":" + std::to_string(o.turn_token) + ",\"cache_bytes\":" +
|
||||
std::to_string(o.cache_bytes) + ",\"slots\":" + std::to_string(o.cache_slots) + ",\"min_free\":" + std::to_string(o.min_free) +
|
||||
",\"reread\":" + (o.reread ? "true" : "false") + ",\"incremental\":" + (o.incremental ? "true" : "false") + "}";
|
||||
}
|
||||
|
||||
// Run one request and emit it together with everything the Rust port must reproduce.
|
||||
Outcome emit_request(Serve& S, const Request& r, std::string& reqs, bool first) {
|
||||
const Outcome res = run_request(S, r);
|
||||
reqs += (first ? "" : ",") + std::string("{\"ids\":") + runs_json(r.ids) + ",\"imgs\":" + imgs_json(r.imgs) + ",\"cvec\":" + (r.cvec ? "true" : "false") +
|
||||
",\"gen\":" + std::to_string(r.gen) + ",\"stop_after\":" + std::to_string(r.stop_after) + ",\"available\":" + std::to_string(r.available) +
|
||||
",\"validate_fails\":" + (r.validate_fails ? "true" : "false") + ",\"expect\":{\"resume\":" + std::to_string(res.resume) +
|
||||
",\"from_live\":" + (res.from_live ? "true" : "false") + ",\"restored\":" +
|
||||
(res.restored ? "[" + std::to_string(res.restored_tokens) + "," + (res.restored_live ? "true" : "false") + "]" : std::string("null")) +
|
||||
",\"reread_to\":" + std::to_string(res.reread_to) + ",\"read_from\":" + std::to_string(res.read_from) +
|
||||
",\"consumed\":" + std::to_string(res.consumed.size()) + ",\"state\":" + state_json(S) + "}}";
|
||||
return res;
|
||||
}
|
||||
|
||||
// #342: MAIN conversation parked, then a sub-agent whose every turn re-renders the previous reply (so no turn
|
||||
// continues the live session and each one parks a stale-tail copy of the one before).
|
||||
std::string subagent_trace(const char* sep, size_t slots, size_t budget, int turns, bool with_main_return) {
|
||||
Options o;
|
||||
o.prompt_cache = 6; o.prompt_cache_every = 100000; o.prompt_cache_root = 8; o.cache_bytes = budget; o.cache_slots = slots;
|
||||
Serve S(o);
|
||||
std::string reqs = "[";
|
||||
bool first = true;
|
||||
auto emit = [&](std::vector<int32_t> ids, int gen) {
|
||||
Request r; r.ids = std::move(ids); r.gen = gen; r.available = 1000000;
|
||||
return emit_request(S, r, reqs, std::exchange(first, false));
|
||||
};
|
||||
auto block = [](int32_t base, int n) { std::vector<int32_t> v; for (int i = 0; i < n; ++i) v.push_back(base + i); return v; };
|
||||
auto cat = [](std::vector<int32_t> a, const std::vector<int32_t>& b) { a.insert(a.end(), b.begin(), b.end()); return a; };
|
||||
std::vector<int32_t> main_ids = cat(cat(cat({7}, block(100, 30)), cat({7}, block(1000, 20))), cat({7}, block(2000, 20)));
|
||||
const auto main_run = emit(main_ids, 6);
|
||||
std::vector<int32_t> rendered = cat({7}, block(5000, 24)); // the sub-agent's system prompt, rendered history so far
|
||||
for (int t = 1; t <= turns; ++t) {
|
||||
const std::vector<int32_t> ids = cat(cat(cat(rendered, {7}), block(6000 + 100 * t, 6)), {8, 8});
|
||||
emit(ids, 5);
|
||||
rendered = cat(ids, block(7000 + 10 * t, 3)); // the reply, as the client re-renders it
|
||||
}
|
||||
if (with_main_return) {
|
||||
emit(cat(main_run.consumed, cat({7}, block(9000, 5))), 4);
|
||||
}
|
||||
reqs += "]";
|
||||
return std::string(sep) + "{\"options\":" + options_json(o) + ",\"requests\":" + reqs + "}";
|
||||
}
|
||||
|
||||
int main() {
|
||||
std::string out = "{\"traces\":[";
|
||||
for (int t = 0; t < 28; ++t) {
|
||||
Rng rng(31000 + t);
|
||||
Options o;
|
||||
o.prompt_cache = 1 + (int) rng.below(7);
|
||||
o.prompt_cache_every = rng.below(3) == 0 ? 0 : (rng.below(2) ? 100 + (int64_t) rng.below(300) : 100000);
|
||||
const int64_t roots[] = {8, 40, 120, 2048, 0};
|
||||
o.prompt_cache_root = roots[rng.below(5)];
|
||||
o.cache_bytes = rng.below(6) == 0 ? 0 : (size_t) (6000 + rng.below(60000));
|
||||
o.cache_slots = 1 + rng.below(5);
|
||||
o.min_free = rng.below(3) == 0 ? 1000 + rng.below(5000) : 0;
|
||||
o.reread = rng.below(8) == 0;
|
||||
o.incremental = rng.below(4) != 0;
|
||||
Serve S(o);
|
||||
// conversation family
|
||||
std::vector<std::vector<int32_t>> histories;
|
||||
std::string reqs = "[";
|
||||
const int steps = 30;
|
||||
for (int step = 0; step < steps; ++step) {
|
||||
Request r;
|
||||
auto fresh_chat = [&](int sys_salt) {
|
||||
std::vector<int32_t> v = {7};
|
||||
const int sys = 10 + (int) rng.below(120);
|
||||
for (int i = 0; i < sys; ++i) v.push_back(100 + sys_salt * 1000 + i);
|
||||
const int turns = 1 + (int) rng.below(3);
|
||||
for (int tn = 0; tn < turns; ++tn) {
|
||||
v.push_back(7);
|
||||
const int len = 3 + (int) rng.below(90);
|
||||
for (int i = 0; i < len; ++i) v.push_back((int32_t) (50000 + rng.below(3) * 10 + i + tn * 500));
|
||||
}
|
||||
return v;
|
||||
};
|
||||
const uint64_t pick = rng.below(7);
|
||||
if (histories.empty() || pick == 0) {
|
||||
r.ids = fresh_chat(rng.below(2) ? 0 : (int) (1 + rng.below(3)));
|
||||
} else {
|
||||
auto base = rng.below(5) < 3 ? histories.back() : histories[rng.below(histories.size())];
|
||||
const uint64_t how = rng.below(3);
|
||||
if (how == 0) {
|
||||
base.push_back(7);
|
||||
const int len = 2 + (int) rng.below(60);
|
||||
for (int i = 0; i < len; ++i) base.push_back(70000 + i);
|
||||
r.ids = base;
|
||||
} else if (how == 1) {
|
||||
const size_t cut = 1 + rng.below(base.size() - 1);
|
||||
base.resize(cut);
|
||||
const int len = 2 + (int) rng.below(40);
|
||||
for (int i = 0; i < len; ++i) base.push_back(80000 + i + (int32_t) rng.below(2));
|
||||
r.ids = base;
|
||||
} else {
|
||||
r.ids = base;
|
||||
}
|
||||
}
|
||||
if (rng.below(12) == 0) r.imgs.push_back({(int64_t) rng.below(r.ids.size()), rng.below(2)});
|
||||
r.cvec = rng.below(8) != 0;
|
||||
r.gen = 1 + (int) rng.below(10);
|
||||
r.stop_after = rng.below(8) == 0 ? (int) rng.below(4) : -1;
|
||||
r.available = rng.below(6) == 0 ? -1 : (int64_t) (rng.below(3) ? 1000000 : 3000);
|
||||
r.validate_fails = rng.below(10) == 0;
|
||||
const Outcome res = emit_request(S, r, reqs, step == 0);
|
||||
if (!res.consumed.empty()) histories.push_back(res.consumed);
|
||||
}
|
||||
reqs += "]";
|
||||
out += (t ? "," : "") + std::string("{\"options\":") + options_json(o) + ",\"requests\":" + reqs + "}";
|
||||
}
|
||||
// scripted #342 sub-agent traffic, with and without the MAIN conversation coming back
|
||||
out += subagent_trace(",", 4, 1 << 20, 9, true);
|
||||
out += subagent_trace(",", 3, 1 << 20, 7, true);
|
||||
out += subagent_trace(",", 2, 1 << 20, 6, true);
|
||||
out += subagent_trace(",", 4, 12000, 8, false);
|
||||
out += "]}\n";
|
||||
std::fputs(out.c_str(), stdout);
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,309 @@
|
||||
//! Differential test of [`ConversationManager`] against the conversation
|
||||
//! block of `generate.cpp` (transliterated in `golden/gen_manager_golden.cpp`
|
||||
//! over the real C++ cache, eviction policy and memory admission): 28 random
|
||||
//! serving traces of 30 requests each, with parking budgets, memory telemetry,
|
||||
//! steering flips, cancelled prompts, invalid parked images and the
|
||||
//! checkpoint re-read check. Every request's resume decision and the complete
|
||||
//! cache/chain state after it must match.
|
||||
|
||||
use super::cache::{
|
||||
ConversationCheckpoint, ConversationImageKey, ConversationKvReuse, SavedConversation,
|
||||
};
|
||||
use super::manager::{ConversationManager, ConversationOptions, SessionEngine};
|
||||
use super::model::{ConvError, ConvResult};
|
||||
use super::snapshot::{ConversationView, RestoreOutcome};
|
||||
use crate::backend::original_prompt::{PromptOptions, PromptPath, PromptPlan};
|
||||
use serde_json::Value;
|
||||
|
||||
const PAYLOAD: usize = 100;
|
||||
|
||||
/// The synthetic device of the C++ harness: fixed-size payloads, no memory.
|
||||
struct Synthetic {
|
||||
available: Option<u64>,
|
||||
validate_fails: bool,
|
||||
}
|
||||
|
||||
fn image_of(view: &ConversationView<'_>) -> SavedConversation {
|
||||
let mut s = SavedConversation::default();
|
||||
s.live.ids = view.ids.to_vec();
|
||||
s.live.imgs = view.images.to_vec();
|
||||
s.live.gdn = vec![1; PAYLOAD];
|
||||
s.cvec = view.cvec;
|
||||
s.checkpoints = view.checkpoints.to_vec();
|
||||
s
|
||||
}
|
||||
|
||||
impl SessionEngine for Synthetic {
|
||||
fn snapshot_bytes(&mut self, view: &ConversationView<'_>) -> ConvResult<usize> {
|
||||
Ok(image_of(view).bytes())
|
||||
}
|
||||
fn snapshot_capture_bytes(
|
||||
&mut self,
|
||||
_: &ConversationKvReuse,
|
||||
view: &ConversationView<'_>,
|
||||
) -> ConvResult<usize> {
|
||||
Ok(image_of(view).bytes())
|
||||
}
|
||||
fn snapshot_save(
|
||||
&mut self,
|
||||
view: &ConversationView<'_>,
|
||||
_: ConversationKvReuse,
|
||||
_: &mut usize,
|
||||
) -> ConvResult<SavedConversation> {
|
||||
Ok(image_of(view))
|
||||
}
|
||||
fn snapshot_validate(&mut self, _: &SavedConversation) -> ConvResult<()> {
|
||||
if self.validate_fails {
|
||||
Err(ConvError("injected".into()))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
fn snapshot_restore(&mut self, _: &SavedConversation) -> RestoreOutcome {
|
||||
RestoreOutcome::Restored
|
||||
}
|
||||
fn checkpoint_save(&mut self, c: &mut ConversationCheckpoint) -> ConvResult<()> {
|
||||
c.gdn = vec![2; PAYLOAD];
|
||||
Ok(())
|
||||
}
|
||||
fn checkpoint_restore(&mut self, _: &ConversationCheckpoint) -> ConvResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
fn synchronize(&mut self) -> ConvResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
fn zero_session(&mut self) -> ConvResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
fn restore_draft(&mut self, _: usize) -> ConvResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
fn set_steering(&mut self, _: bool) {}
|
||||
fn available_memory(&mut self) -> Option<u64> {
|
||||
self.available
|
||||
}
|
||||
}
|
||||
|
||||
fn runs(v: &Value) -> Vec<i32> {
|
||||
let mut out = Vec::new();
|
||||
for run in v.as_array().unwrap() {
|
||||
let (start, len) = (
|
||||
run[0].as_i64().unwrap() as i32,
|
||||
run[1].as_i64().unwrap() as i32,
|
||||
);
|
||||
out.extend((0..len).map(|i| start + i));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn imgs(v: &Value) -> Vec<ConversationImageKey> {
|
||||
v.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|p| ConversationImageKey {
|
||||
start: p[0].as_i64().unwrap(),
|
||||
hash: p[1].as_u64().unwrap(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manager_decisions_match_the_generate_cpp_policy() {
|
||||
let golden: Value = serde_json::from_str(include_str!("golden/manager_golden.json")).unwrap();
|
||||
let mut totals = [0usize; 5];
|
||||
for (t, trace) in golden["traces"].as_array().unwrap().iter().enumerate() {
|
||||
let o = &trace["options"];
|
||||
let options = ConversationOptions {
|
||||
prompt_cache: o["prompt_cache"].as_i64().unwrap(),
|
||||
prompt_cache_every: o["every"].as_i64().unwrap(),
|
||||
conversation_cache_bytes: o["cache_bytes"].as_u64().unwrap() as usize,
|
||||
conversation_cache_slots: o["slots"].as_u64().unwrap() as usize,
|
||||
conversation_cache_min_free_bytes: o["min_free"].as_u64().unwrap(),
|
||||
incremental_capture: o["incremental"].as_bool().unwrap(),
|
||||
reread_checkpoints: o["reread"].as_bool().unwrap(),
|
||||
};
|
||||
let plan_options = PromptOptions {
|
||||
root_min: o["root"].as_u64().unwrap() as usize,
|
||||
turn_token: Some(o["turn"].as_u64().unwrap() as u32),
|
||||
..PromptOptions::original_mode17(262144)
|
||||
};
|
||||
let mut mgr = ConversationManager::new(options);
|
||||
let mut parks = 0usize;
|
||||
for (step, req) in trace["requests"].as_array().unwrap().iter().enumerate() {
|
||||
let ctx = format!("trace {t} request {step}");
|
||||
let ids = runs(&req["ids"]);
|
||||
let images = imgs(&req["imgs"]);
|
||||
let available = req["available"].as_i64().unwrap();
|
||||
let mut engine = Synthetic {
|
||||
available: (available >= 0).then_some(available as u64),
|
||||
validate_fails: req["validate_fails"].as_bool().unwrap(),
|
||||
};
|
||||
let want = &req["expect"];
|
||||
let start = mgr
|
||||
.begin_request(&mut engine, &ids, &images, req["cvec"].as_bool().unwrap())
|
||||
.unwrap_or_else(|e| panic!("{ctx}: {e}"));
|
||||
assert_eq!(
|
||||
start.resume as i64,
|
||||
want["resume"].as_i64().unwrap(),
|
||||
"{ctx}: resume"
|
||||
);
|
||||
assert_eq!(
|
||||
start.from_live,
|
||||
want["from_live"].as_bool().unwrap(),
|
||||
"{ctx}: from_live"
|
||||
);
|
||||
let restored = start.restored.map(|(tokens, live)| (tokens as i64, live));
|
||||
let expected_restored = match &want["restored"] {
|
||||
Value::Null => None,
|
||||
pair => Some((pair[0].as_i64().unwrap(), pair[1].as_bool().unwrap())),
|
||||
};
|
||||
assert_eq!(restored, expected_restored, "{ctx}: restored");
|
||||
assert_eq!(
|
||||
start.reread_to.map_or(-1, |v| v as i64),
|
||||
want["reread_to"].as_i64().unwrap(),
|
||||
"{ctx}: reread_to"
|
||||
);
|
||||
assert_eq!(
|
||||
start.read_from as i64,
|
||||
want["read_from"].as_i64().unwrap(),
|
||||
"{ctx}: read_from"
|
||||
);
|
||||
let prompt: Vec<u32> = ids.iter().map(|&i| i as u32).collect();
|
||||
let plan = PromptPlan::new(
|
||||
&prompt,
|
||||
start.resume,
|
||||
start.reread_to,
|
||||
None,
|
||||
plan_options,
|
||||
256,
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("{ctx}: {e:?}"));
|
||||
let stop_after = req["stop_after"].as_i64().unwrap();
|
||||
let mut cancelled = false;
|
||||
for (actions, action) in plan.enumerate() {
|
||||
if action.path == PromptPath::FinalSeed {
|
||||
break;
|
||||
}
|
||||
if stop_after >= 0 && actions as i64 == stop_after {
|
||||
cancelled = true;
|
||||
break;
|
||||
}
|
||||
mgr.after_prompt_action(&mut engine, &ids, &images, &action)
|
||||
.unwrap_or_else(|e| panic!("{ctx}: {e}"));
|
||||
}
|
||||
let generated = req["gen"].as_i64().unwrap() as usize;
|
||||
let consumed_len = if cancelled {
|
||||
0
|
||||
} else {
|
||||
ids.len() + generated - 1
|
||||
};
|
||||
if !cancelled {
|
||||
let mut consumed = ids.clone();
|
||||
consumed
|
||||
.extend((0..generated as i32 - 1).map(|i| 200000 + ids.len() as i32 * 10 + i));
|
||||
mgr.finish_request(consumed, &images, false);
|
||||
} else {
|
||||
mgr.finish_request(Vec::new(), &images, true);
|
||||
}
|
||||
assert_eq!(
|
||||
consumed_len as i64,
|
||||
want["consumed"].as_i64().unwrap(),
|
||||
"{ctx}: consumed"
|
||||
);
|
||||
parks += mgr
|
||||
.take_events()
|
||||
.iter()
|
||||
.filter(|e| e.starts_with("conversation cache: parked "))
|
||||
.count();
|
||||
// The state after the request.
|
||||
let state = &want["state"];
|
||||
assert_eq!(
|
||||
mgr.live().len() as i64,
|
||||
state["live"].as_i64().unwrap(),
|
||||
"{ctx}: live length"
|
||||
);
|
||||
assert_eq!(
|
||||
mgr.live_ok(),
|
||||
state["live_ok"].as_bool().unwrap(),
|
||||
"{ctx}: live_ok"
|
||||
);
|
||||
assert_eq!(
|
||||
mgr.cvec_cached(),
|
||||
state["cvec"].as_bool().unwrap(),
|
||||
"{ctx}: cvec"
|
||||
);
|
||||
let chain: Vec<(i64, u64)> = mgr
|
||||
.checkpoints()
|
||||
.iter()
|
||||
.map(|c| (c.ids.len() as i64, c.used))
|
||||
.collect();
|
||||
let expected: Vec<(i64, u64)> = state["checks"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|p| (p[0].as_i64().unwrap(), p[1].as_u64().unwrap()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
chain, expected,
|
||||
"{ctx}: checkpoint chain (length, LRU stamp)"
|
||||
);
|
||||
assert_eq!(
|
||||
mgr.check_clock(),
|
||||
state["clock"].as_u64().unwrap(),
|
||||
"{ctx}: LRU clock"
|
||||
);
|
||||
assert_eq!(
|
||||
mgr.next_periodic_checkpoint(),
|
||||
state["pp_next"].as_i64().unwrap(),
|
||||
"{ctx}: next periodic checkpoint"
|
||||
);
|
||||
let cache = mgr.cache();
|
||||
let c = &state["cache"];
|
||||
assert_eq!(
|
||||
cache.size() as u64,
|
||||
c["size"].as_u64().unwrap(),
|
||||
"{ctx}: cache size"
|
||||
);
|
||||
assert_eq!(
|
||||
cache.bytes() as u64,
|
||||
c["bytes"].as_u64().unwrap(),
|
||||
"{ctx}: cache bytes"
|
||||
);
|
||||
assert_eq!(
|
||||
cache.evictions() as u64,
|
||||
c["evictions"].as_u64().unwrap(),
|
||||
"{ctx}: evictions"
|
||||
);
|
||||
assert_eq!(
|
||||
cache.superseded() as u64,
|
||||
c["superseded"].as_u64().unwrap(),
|
||||
"{ctx}: superseded"
|
||||
);
|
||||
assert_eq!(
|
||||
cache.retained_bytes() as u64,
|
||||
c["retained"].as_u64().unwrap(),
|
||||
"{ctx}: retained"
|
||||
);
|
||||
assert_eq!(
|
||||
parks as u64,
|
||||
state["parks"].as_u64().unwrap(),
|
||||
"{ctx}: parked images"
|
||||
);
|
||||
let path = if restored.is_some() {
|
||||
0
|
||||
} else if start.resume == 0 {
|
||||
1
|
||||
} else if start.from_live {
|
||||
2
|
||||
} else {
|
||||
3
|
||||
};
|
||||
totals[path] += 1;
|
||||
totals[4] += usize::from(cancelled);
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
totals.iter().all(|&n| n >= 20),
|
||||
"the traces cover every path: {totals:?}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,566 @@
|
||||
//! Conversation parking, resume and checkpoint policy of `--serve`, port of
|
||||
//! the conversation block of `generate.cpp` (`park_current`, the resume choice
|
||||
//! at the head of a request, `checkpoint_at`, the periodic prompt checkpoint
|
||||
//! and the end-of-request live-state update).
|
||||
//!
|
||||
//! State kept between requests:
|
||||
//!
|
||||
//! * `live`: the tokens (and picture identities) the session holds right
|
||||
//! now, so a request starting with exactly them continues without a copy;
|
||||
//! * `checks`: saved running-state points, each a prefix of `live`; they form
|
||||
//! a chain (a radix cache collapsed onto the one branch of history whose
|
||||
//! cells the session holds). Its root, the deepest point every request so
|
||||
//! far shared (the end of the system prompt in practice), is pinned and the
|
||||
//! rest rotate by least recent use ([`eviction_victim`]);
|
||||
//! * `cache`: whole parked conversations in host RAM (opt in, byte and slot
|
||||
//! budgeted, admitted against physical memory), for switching between
|
||||
//! independent conversations without re-reading either.
|
||||
//!
|
||||
//! The device is behind [`SessionEngine`], so the identical policy runs
|
||||
//! against CUDA owners in production, against host memory in tests, and
|
||||
//! against a synthetic engine in the differential test vs the C++ original.
|
||||
|
||||
use super::cache::{
|
||||
CheckpointKey, ConversationCache, ConversationCheckpoint, ConversationImageKey,
|
||||
ConversationKvReuse, SavedConversation,
|
||||
};
|
||||
use super::memory::memory_admit;
|
||||
use super::model::{ConvError, ConvResult};
|
||||
use super::retention::eviction_victim;
|
||||
use super::snapshot::{ConversationView, RestoreOutcome};
|
||||
use crate::backend::original_prompt::{PromptAction, PromptPath};
|
||||
|
||||
/// Everything the policy needs from the device side.
|
||||
pub trait SessionEngine {
|
||||
fn snapshot_bytes(&mut self, view: &ConversationView<'_>) -> ConvResult<usize>;
|
||||
fn snapshot_capture_bytes(
|
||||
&mut self,
|
||||
reuse: &ConversationKvReuse,
|
||||
view: &ConversationView<'_>,
|
||||
) -> ConvResult<usize>;
|
||||
/// Capture the live session. `reuse` is consumed, including on failure.
|
||||
fn snapshot_save(
|
||||
&mut self,
|
||||
view: &ConversationView<'_>,
|
||||
reuse: ConversationKvReuse,
|
||||
reused_bytes: &mut usize,
|
||||
) -> ConvResult<SavedConversation>;
|
||||
/// Reject an unusable image before anything is overwritten.
|
||||
fn snapshot_validate(&mut self, image: &SavedConversation) -> ConvResult<()>;
|
||||
fn snapshot_restore(&mut self, image: &SavedConversation) -> RestoreOutcome;
|
||||
fn checkpoint_save(&mut self, c: &mut ConversationCheckpoint) -> ConvResult<()>;
|
||||
fn checkpoint_restore(&mut self, c: &ConversationCheckpoint) -> ConvResult<()>;
|
||||
/// `cudaDeviceSynchronize`.
|
||||
fn synchronize(&mut self) -> ConvResult<()>;
|
||||
/// `session_zero` plus stream synchronisation: a fresh sequence.
|
||||
fn zero_session(&mut self) -> ConvResult<()>;
|
||||
/// `mtp.kv_restore(resume)`: the drafter's ring may hold cells past
|
||||
/// `resume` from a longer turn; make it consistent with `resume`.
|
||||
fn restore_draft(&mut self, resume: usize) -> ConvResult<()>;
|
||||
/// Control-vector (steering) state the next request reads with.
|
||||
fn set_steering(&mut self, enabled: bool);
|
||||
/// Available host physical memory; `None` when unknown.
|
||||
fn available_memory(&mut self) -> Option<u64>;
|
||||
}
|
||||
|
||||
/// Serving options (`--prompt-cache`, `--prompt-cache-every`,
|
||||
/// `--conversation-cache-mib`, `--conversation-cache-slots`,
|
||||
/// `--conversation-cache-min-free-mib`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ConversationOptions {
|
||||
/// Checkpoint chain capacity; 0 turns every conversation feature off.
|
||||
pub prompt_cache: i64,
|
||||
/// Periodic prompt checkpoints, in tokens; 0 disables them.
|
||||
pub prompt_cache_every: i64,
|
||||
/// Host RAM for parked conversations; 0 disables parking.
|
||||
pub conversation_cache_bytes: usize,
|
||||
pub conversation_cache_slots: usize,
|
||||
/// Physical memory that must stay free after a snapshot is taken.
|
||||
pub conversation_cache_min_free_bytes: u64,
|
||||
/// Keep the restored K/V buffers so the next capture rewrites less
|
||||
/// (`STRATA_SNAPSHOT_FULL_CAPTURE` unset).
|
||||
pub incremental_capture: bool,
|
||||
/// `STRATA_CKPT_REREAD`: re-read a checkpoint's tokens instead of
|
||||
/// restoring it (a correctness check of the checkpoint).
|
||||
pub reread_checkpoints: bool,
|
||||
}
|
||||
|
||||
impl Default for ConversationOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
prompt_cache: 6,
|
||||
prompt_cache_every: 16384,
|
||||
conversation_cache_bytes: 0, // opt in: host RAM for independent conversations
|
||||
conversation_cache_slots: 4,
|
||||
conversation_cache_min_free_bytes: 2560 * 1024 * 1024,
|
||||
incremental_capture: true,
|
||||
reread_checkpoints: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How the request starts reading its prompt.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct RequestStart {
|
||||
/// Prompt tokens that are not read again.
|
||||
pub resume: usize,
|
||||
/// Resumed from the live session (no copy) rather than a checkpoint.
|
||||
pub from_live: bool,
|
||||
/// A parked conversation was restored: `(prompt tokens it matched, live)`.
|
||||
pub restored: Option<(usize, bool)>,
|
||||
/// `STRATA_CKPT_REREAD` only: read `[0, reread_to)` again.
|
||||
pub reread_to: Option<usize>,
|
||||
/// First token that is actually read.
|
||||
pub read_from: usize,
|
||||
}
|
||||
|
||||
/// Prompt positions of the pictures below `limit` (`imgs_below`).
|
||||
pub fn images_below(all: &[ConversationImageKey], limit: usize) -> Vec<ConversationImageKey> {
|
||||
all.iter()
|
||||
.filter(|key| key.start < limit as i64)
|
||||
.copied()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The saved point `pre` (tokens and pictures) is exactly the start of
|
||||
/// `ids`, and at most `ids.len() - 1` long: the last token always starts the
|
||||
/// first verify window.
|
||||
pub fn starts_with(
|
||||
pre: &[i32],
|
||||
pre_imgs: &[ConversationImageKey],
|
||||
ids: &[i32],
|
||||
req_imgs: &[ConversationImageKey],
|
||||
) -> bool {
|
||||
let l = pre.len();
|
||||
if l < 1 || l + 1 > ids.len() || ids[..l] != *pre {
|
||||
return false;
|
||||
}
|
||||
images_below(req_imgs, l) == pre_imgs
|
||||
}
|
||||
|
||||
pub struct ConversationManager {
|
||||
options: ConversationOptions,
|
||||
live: Vec<i32>,
|
||||
live_imgs: Vec<ConversationImageKey>,
|
||||
live_ok: bool,
|
||||
checks: Vec<ConversationCheckpoint>,
|
||||
/// The checkpoints' LRU clock; creation and every use advance it.
|
||||
check_clock: u64,
|
||||
/// The steering state the live session and the checkpoints were read with.
|
||||
cvec_cached: bool,
|
||||
cache: ConversationCache<SavedConversation>,
|
||||
pp_next_check: i64,
|
||||
events: Vec<String>,
|
||||
}
|
||||
|
||||
fn is_allocation(error: &ConvError) -> bool {
|
||||
error.0.ends_with("allocation failed")
|
||||
}
|
||||
|
||||
impl ConversationManager {
|
||||
pub fn new(options: ConversationOptions) -> Self {
|
||||
let budget = if options.prompt_cache > 0 {
|
||||
options.conversation_cache_bytes
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let cache = ConversationCache::new(budget, options.conversation_cache_slots);
|
||||
Self {
|
||||
options,
|
||||
live: Vec::new(),
|
||||
live_imgs: Vec::new(),
|
||||
live_ok: false,
|
||||
checks: Vec::new(),
|
||||
check_clock: 0,
|
||||
cvec_cached: true,
|
||||
cache,
|
||||
pp_next_check: 0,
|
||||
events: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn options(&self) -> &ConversationOptions {
|
||||
&self.options
|
||||
}
|
||||
pub fn live(&self) -> &[i32] {
|
||||
&self.live
|
||||
}
|
||||
pub fn live_ok(&self) -> bool {
|
||||
self.live_ok
|
||||
}
|
||||
pub fn checkpoints(&self) -> &[ConversationCheckpoint] {
|
||||
&self.checks
|
||||
}
|
||||
pub fn cvec_cached(&self) -> bool {
|
||||
self.cvec_cached
|
||||
}
|
||||
pub fn cache(&self) -> &ConversationCache<SavedConversation> {
|
||||
&self.cache
|
||||
}
|
||||
/// The checkpoints' LRU clock.
|
||||
pub fn check_clock(&self) -> u64 {
|
||||
self.check_clock
|
||||
}
|
||||
/// Next prompt position at which a periodic checkpoint is due.
|
||||
pub fn next_periodic_checkpoint(&self) -> i64 {
|
||||
self.pp_next_check
|
||||
}
|
||||
/// Operator-facing log lines produced since the last call.
|
||||
pub fn take_events(&mut self) -> Vec<String> {
|
||||
std::mem::take(&mut self.events)
|
||||
}
|
||||
|
||||
/// Drop everything that refers to the device's state (after an unload,
|
||||
/// a reset or a fatal device error).
|
||||
pub fn invalidate(&mut self) {
|
||||
self.live.clear();
|
||||
self.live_imgs.clear();
|
||||
self.live_ok = false;
|
||||
self.checks.clear();
|
||||
self.cache = ConversationCache::new(self.cache.budget(), self.cache.slots());
|
||||
self.pp_next_check = 0;
|
||||
}
|
||||
|
||||
/// Save only on a switch/rewind, not on each continuing request. `held` is
|
||||
/// an incoming image that is still alive during the exchange. Anything
|
||||
/// recoverable (nothing to park, no room, no RAM, allocation failure)
|
||||
/// skips parking and returns `Ok`; a device failure is fatal.
|
||||
fn park_current(&mut self, engine: &mut dyn SessionEngine, held: usize) -> ConvResult<()> {
|
||||
if !self.cache.enabled() || !self.live_ok || self.live.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let view = ConversationView {
|
||||
ids: &self.live,
|
||||
images: &self.live_imgs,
|
||||
checkpoints: &self.checks,
|
||||
cvec: self.cvec_cached,
|
||||
};
|
||||
let mut reuse = self.cache.take_reuse();
|
||||
let fresh_estimate = match engine.snapshot_bytes(&view) {
|
||||
Ok(n) => n,
|
||||
Err(e) => {
|
||||
self.events
|
||||
.push(format!("conversation cache: skip parking ({e})"));
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
let mut estimate = fresh_estimate;
|
||||
if !reuse.kv.is_empty() {
|
||||
match engine.snapshot_capture_bytes(&reuse, &view) {
|
||||
Ok(n) => estimate = n,
|
||||
Err(_) => {
|
||||
reuse = ConversationKvReuse::default();
|
||||
estimate = fresh_estimate;
|
||||
}
|
||||
}
|
||||
}
|
||||
// A park carrying its own retained K/V replaces memory the cache
|
||||
// already held, so capacity is make_room's call: the with-reuse
|
||||
// estimate must stay uncapped, because put() charges that same true
|
||||
// size and a capped figure would under-evict and overfill the budget.
|
||||
// #342: before make_room evicts oldest-first, the copies of this
|
||||
// conversation a turn back go.
|
||||
let keys: Vec<CheckpointKey<'_>> = self
|
||||
.checks
|
||||
.iter()
|
||||
.map(|c| CheckpointKey {
|
||||
ids: &c.ids,
|
||||
imgs: &c.imgs,
|
||||
})
|
||||
.collect();
|
||||
let dropped =
|
||||
self.cache
|
||||
.drop_superseded(&self.live, &self.live_imgs, &keys, self.cvec_cached);
|
||||
if dropped != 0 {
|
||||
self.events.push(format!(
|
||||
"conversation cache: dropped {dropped} superseded cop{} of this conversation; parked={}",
|
||||
if dropped == 1 { "y" } else { "ies" },
|
||||
self.cache.size()
|
||||
));
|
||||
}
|
||||
if !self.cache.make_room(estimate, held) {
|
||||
self.events.push(format!(
|
||||
"conversation cache: skip parking (snapshot {} MiB exceeds available budget)",
|
||||
estimate >> 20
|
||||
));
|
||||
return Ok(());
|
||||
}
|
||||
let floor = self.options.conversation_cache_min_free_bytes;
|
||||
let additional = estimate.saturating_sub(reuse.bytes());
|
||||
if !memory_admit(engine.available_memory(), additional as u64, floor) {
|
||||
self.events.push(format!(
|
||||
"conversation cache: skip parking (physical RAM admission; need {} MiB plus {} MiB floor, or telemetry unavailable)",
|
||||
additional >> 20,
|
||||
floor >> 20
|
||||
));
|
||||
return Ok(());
|
||||
}
|
||||
let mut reused_bytes = 0usize;
|
||||
let image = match engine.snapshot_save(&view, reuse, &mut reused_bytes) {
|
||||
Ok(image) => image,
|
||||
Err(e) if is_allocation(&e) => {
|
||||
// The active state has not been touched: continue with normal
|
||||
// prompt processing rather than killing a serving process.
|
||||
self.events
|
||||
.push("conversation cache: allocation failed; skip parking".into());
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
if !memory_admit(engine.available_memory(), 0, floor) {
|
||||
self.events.push(
|
||||
"conversation cache: skip parking (physical RAM floor after capture, or telemetry unavailable)".into(),
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
let snapshot_bytes = image.bytes();
|
||||
let tokens = self.live.len();
|
||||
let stored = self.cache.put(image, held).is_ok();
|
||||
self.events.push(format!(
|
||||
"conversation cache: {} {tokens} tokens; parked={} bytes={} evictions={} snapshot_bytes={snapshot_bytes} reused_kv_bytes={reused_bytes}",
|
||||
if stored { "parked" } else { "skipped" },
|
||||
self.cache.size(),
|
||||
self.cache.bytes(),
|
||||
self.cache.evictions(),
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decide where `ids` starts reading and put the device in that state:
|
||||
/// continue the live session, restore a checkpoint, restore a parked
|
||||
/// conversation (parking the outgoing one first), or start empty. Any
|
||||
/// error is fatal for the request and the device state is then undefined.
|
||||
pub fn begin_request(
|
||||
&mut self,
|
||||
engine: &mut dyn SessionEngine,
|
||||
ids: &[i32],
|
||||
req_imgs: &[ConversationImageKey],
|
||||
want_cvec: bool,
|
||||
) -> ConvResult<RequestStart> {
|
||||
let prompt_cache = self.options.prompt_cache > 0;
|
||||
let mut resume = 0usize;
|
||||
let mut from_live = false;
|
||||
if prompt_cache && want_cvec == self.cvec_cached {
|
||||
if self.live_ok && starts_with(&self.live, &self.live_imgs, ids, req_imgs) {
|
||||
resume = self.live.len();
|
||||
from_live = true;
|
||||
}
|
||||
for c in &self.checks {
|
||||
if c.ids.len() > resume && starts_with(&c.ids, &c.imgs, ids, req_imgs) {
|
||||
resume = c.ids.len();
|
||||
from_live = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
let parked = self.cache.best(ids, req_imgs, want_cvec);
|
||||
let mut incoming = if parked.tokens as usize > resume {
|
||||
self.cache.take(parked.index)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// Reject the entire image before parking/overwriting the outgoing
|
||||
// state. Invalid entries can safely fall back to the existing prefix.
|
||||
if let Some(image) = &incoming
|
||||
&& let Err(e) = engine.snapshot_validate(image)
|
||||
{
|
||||
self.events.push(format!(
|
||||
"conversation cache: discard invalid snapshot ({e})"
|
||||
));
|
||||
incoming = None;
|
||||
}
|
||||
// Preserve the outgoing branch before any checkpoint rewind, reset or
|
||||
// incoming restore overwrites the positional state it requires.
|
||||
if !from_live || incoming.is_some() {
|
||||
let held = incoming.as_ref().map_or(0, SavedConversation::bytes);
|
||||
self.park_current(engine, held)?;
|
||||
}
|
||||
let mut restored = None;
|
||||
if let Some(mut image) = incoming {
|
||||
match engine.snapshot_restore(&image) {
|
||||
RestoreOutcome::Restored => {}
|
||||
// Already prevalidated: a failure here is fatal, never
|
||||
// permission to decode from a partially restored session.
|
||||
RestoreOutcome::Invalid(e) | RestoreOutcome::TransferFailed(e) => {
|
||||
return Err(ConvError(format!("restoring parked conversation: {e}")));
|
||||
}
|
||||
}
|
||||
self.live = std::mem::take(&mut image.live.ids);
|
||||
self.live_imgs = std::mem::take(&mut image.live.imgs);
|
||||
self.checks = std::mem::take(&mut image.checkpoints);
|
||||
self.cvec_cached = image.cvec;
|
||||
resume = parked.tokens as usize;
|
||||
from_live = parked.live;
|
||||
restored = Some((resume, from_live));
|
||||
if self.options.incremental_capture {
|
||||
self.cache
|
||||
.retain(std::mem::take(&mut image.kv), self.live.len() as i64);
|
||||
}
|
||||
self.events.push(format!(
|
||||
"conversation cache: restored {resume} tokens ({}); parked={} bytes={}",
|
||||
if from_live { "live" } else { "checkpoint" },
|
||||
self.cache.size(),
|
||||
self.cache.bytes()
|
||||
));
|
||||
}
|
||||
if want_cvec != self.cvec_cached {
|
||||
self.live_ok = false;
|
||||
self.checks.clear();
|
||||
self.cvec_cached = want_cvec;
|
||||
}
|
||||
engine.set_steering(want_cvec);
|
||||
// This request rewrites every cell from `resume` on, so a checkpoint
|
||||
// past it (or not on this prompt's path) no longer has its cells; the
|
||||
// ones kept are prefixes of both the old tokens and the new.
|
||||
self.checks
|
||||
.retain(|c| c.ids.len() <= resume && starts_with(&c.ids, &c.imgs, ids, req_imgs));
|
||||
self.live_ok = false; // until this request has finished, the session is in between
|
||||
let mut reread_to = None;
|
||||
if resume == 0 {
|
||||
engine.zero_session()?;
|
||||
self.checks.clear();
|
||||
} else if !from_live {
|
||||
let Some(index) = self.checks.iter().rposition(|k| k.ids.len() == resume) else {
|
||||
return Err(ConvError(
|
||||
"restoring a conversation checkpoint failed".into(),
|
||||
));
|
||||
};
|
||||
self.check_clock += 1;
|
||||
self.checks[index].used = self.check_clock;
|
||||
if self.options.reread_checkpoints {
|
||||
// THE CHECK OF THE CHECKPOINT: read its tokens again from
|
||||
// position 0 instead of restoring it; with the expert set
|
||||
// fixed the answer must match the restored one token for token.
|
||||
engine.zero_session()?;
|
||||
reread_to = Some(resume);
|
||||
self.events.push(format!(
|
||||
"STRATA_CKPT_REREAD: reading {resume} tokens again instead of restoring"
|
||||
));
|
||||
} else {
|
||||
let c = &self.checks[index];
|
||||
if !c.stage_parts.is_empty() || engine.checkpoint_restore(c).is_err() {
|
||||
return Err(ConvError(
|
||||
"restoring a conversation checkpoint failed".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
// KV streaming: the drafter's ring may hold cells past `resume` from a
|
||||
// longer turn; the main layers' host copies and slots are always
|
||||
// current (every writer writes both), so they need nothing.
|
||||
if resume > 0 && reread_to.is_none() {
|
||||
engine.restore_draft(resume)?;
|
||||
}
|
||||
let read_from = if reread_to.is_some() { 0 } else { resume };
|
||||
self.cache.limit_reuse(read_from as i64);
|
||||
self.pp_next_check = if reread_to.is_some() {
|
||||
i64::MAX
|
||||
} else {
|
||||
resume as i64 + self.options.prompt_cache_every
|
||||
};
|
||||
Ok(RequestStart {
|
||||
resume,
|
||||
from_live,
|
||||
restored,
|
||||
reread_to,
|
||||
read_from,
|
||||
})
|
||||
}
|
||||
|
||||
/// A checkpoint of the state after `ids[..position]`. `Ok` also when
|
||||
/// checkpoints are off. An existing checkpoint at the position just
|
||||
/// becomes the most recently used.
|
||||
pub fn checkpoint_at(
|
||||
&mut self,
|
||||
engine: &mut dyn SessionEngine,
|
||||
ids: &[i32],
|
||||
req_imgs: &[ConversationImageKey],
|
||||
position: usize,
|
||||
) -> ConvResult<()> {
|
||||
if self.options.prompt_cache <= 0 || position < 1 {
|
||||
return Ok(());
|
||||
}
|
||||
if position > ids.len() {
|
||||
return Err(ConvError(
|
||||
"conversation checkpoint beyond the prompt".into(),
|
||||
));
|
||||
}
|
||||
if let Some(existing) = self.checks.iter_mut().find(|c| c.ids.len() == position) {
|
||||
self.check_clock += 1;
|
||||
existing.used = self.check_clock;
|
||||
return Ok(());
|
||||
}
|
||||
let mut c = ConversationCheckpoint {
|
||||
ids: ids[..position].to_vec(),
|
||||
imgs: images_below(req_imgs, position),
|
||||
..ConversationCheckpoint::default()
|
||||
};
|
||||
engine.synchronize()?;
|
||||
engine.checkpoint_save(&mut c)?;
|
||||
self.check_clock += 1;
|
||||
c.used = self.check_clock;
|
||||
self.checks.push(c);
|
||||
while self.checks.len() as i64 > self.options.prompt_cache {
|
||||
let stamps: Vec<u64> = self.checks.iter().map(|k| k.used).collect();
|
||||
let victim = eviction_victim(&stamps, self.options.prompt_cache);
|
||||
self.checks.remove(victim);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A batched prompt chunk finished and the prompt is read up to `done`:
|
||||
/// take the periodic checkpoint when it is due.
|
||||
pub fn chunk_done(
|
||||
&mut self,
|
||||
engine: &mut dyn SessionEngine,
|
||||
ids: &[i32],
|
||||
req_imgs: &[ConversationImageKey],
|
||||
done: usize,
|
||||
) -> ConvResult<()> {
|
||||
if self.options.prompt_cache_every > 0 && done as i64 >= self.pp_next_check {
|
||||
self.checkpoint_at(engine, ids, req_imgs, done)
|
||||
.map_err(|_| ConvError("saving a conversation checkpoint failed".into()))?;
|
||||
self.pp_next_check = done as i64 + self.options.prompt_cache_every;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Bookkeeping after the caller executed one [`PromptAction`] of the
|
||||
/// request's prompt plan: the periodic checkpoint after a batched chunk,
|
||||
/// and the turn/root checkpoint when the action ends its segment.
|
||||
// Used by the Original-path prompt driver (the plan type is crate-private).
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn after_prompt_action(
|
||||
&mut self,
|
||||
engine: &mut dyn SessionEngine,
|
||||
ids: &[i32],
|
||||
req_imgs: &[ConversationImageKey],
|
||||
action: &PromptAction,
|
||||
) -> ConvResult<()> {
|
||||
let end = action.first + action.count;
|
||||
if matches!(action.path, PromptPath::Batched { .. }) {
|
||||
self.chunk_done(engine, ids, req_imgs, end)?;
|
||||
}
|
||||
if action.checkpoint_after {
|
||||
self.checkpoint_at(engine, ids, req_imgs, end)
|
||||
.map_err(|_| ConvError("saving a conversation checkpoint failed".into()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The request is over. `consumed` is what the session now holds: the
|
||||
/// prompt read so far, then every committed token. A request stopped
|
||||
/// while reading the prompt leaves the session between two chunks, with
|
||||
/// nothing to continue from (the checkpoints taken meanwhile are good).
|
||||
pub fn finish_request(
|
||||
&mut self,
|
||||
consumed: Vec<i32>,
|
||||
req_imgs: &[ConversationImageKey],
|
||||
cancelled: bool,
|
||||
) {
|
||||
if !cancelled {
|
||||
self.live_imgs = images_below(req_imgs, consumed.len());
|
||||
self.live = consumed;
|
||||
self.live_ok = self.options.prompt_cache > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -4,12 +4,18 @@
|
||||
//! The pure policy modules depend on `std` only, so they build and test on any
|
||||
//! host; the CUDA-owner bindings live next to the session owners.
|
||||
|
||||
pub mod binding;
|
||||
pub mod buffer;
|
||||
pub mod cache;
|
||||
pub mod checked;
|
||||
#[cfg(test)]
|
||||
mod golden_cache;
|
||||
#[cfg(test)]
|
||||
mod golden_manager;
|
||||
pub mod kv;
|
||||
pub mod manager;
|
||||
#[cfg(test)]
|
||||
mod manager_tests;
|
||||
pub mod memory;
|
||||
pub mod model;
|
||||
pub mod retention;
|
||||
|
||||
@@ -21,9 +21,9 @@ use super::state::{
|
||||
};
|
||||
use super::testing::HostMemory;
|
||||
|
||||
const HYBRID: i32 = 3;
|
||||
pub(super) const HYBRID: i32 = 3;
|
||||
|
||||
fn kv_region(layer: KvLayer, pool: KvPool, resident: bool) -> StateRegion {
|
||||
pub(super) fn kv_region(layer: KvLayer, pool: KvPool, resident: bool) -> StateRegion {
|
||||
StateRegion::Kv {
|
||||
layer,
|
||||
pool,
|
||||
@@ -58,16 +58,27 @@ fn q4_per_head(g: &ModelGeometry) -> usize {
|
||||
|
||||
/// The C++ `Fixture`: one layer's pools (device slots plus host pools for a
|
||||
/// streamed layer) registered in a [`HostMemory`].
|
||||
struct Fixture {
|
||||
g: ModelGeometry,
|
||||
st: QsaDesc,
|
||||
layer: KvLayer,
|
||||
sizes: [usize; 5],
|
||||
pub(super) struct Fixture {
|
||||
pub(super) g: ModelGeometry,
|
||||
pub(super) st: QsaDesc,
|
||||
pub(super) layer: KvLayer,
|
||||
pub(super) sizes: [usize; 5],
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new(mem: &mut HostMemory, layer: KvLayer, fmt: i32, mode: i32) -> Self {
|
||||
let g = ModelGeometry::default();
|
||||
pub(super) fn new(mem: &mut HostMemory, layer: KvLayer, fmt: i32, mode: i32) -> Self {
|
||||
Self::with_geometry(mem, layer, fmt, mode, ModelGeometry::default(), 24)
|
||||
}
|
||||
|
||||
/// `n_pages` four-cell pages of the layer's K/V (`max_cells = 4 * n_pages`).
|
||||
pub(super) fn with_geometry(
|
||||
mem: &mut HostMemory,
|
||||
layer: KvLayer,
|
||||
fmt: i32,
|
||||
mode: i32,
|
||||
g: ModelGeometry,
|
||||
n_pages: i64,
|
||||
) -> Self {
|
||||
let mut st = QsaDesc {
|
||||
kv_mode: mode,
|
||||
without_key: fmt == KV_VALUE_INT8,
|
||||
@@ -76,7 +87,7 @@ impl Fixture {
|
||||
..Default::default()
|
||||
};
|
||||
st.kv_int8 = fmt == KV_INT8 || st.without_key;
|
||||
st.n_pages = 24;
|
||||
st.n_pages = n_pages;
|
||||
st.n_slots = if mode != 0 { 4 } else { st.n_pages };
|
||||
st.max_cells = st.n_pages * 4;
|
||||
st.idx_pooled_rows = if mode == 2 { 2 } else { st.max_cells / 4 + 2 };
|
||||
@@ -171,11 +182,11 @@ impl Fixture {
|
||||
}
|
||||
}
|
||||
|
||||
fn source(&self, i: usize) -> StateRegion {
|
||||
pub(super) fn source(&self, i: usize) -> StateRegion {
|
||||
kv_region(self.layer, KvPool::ALL[i], false)
|
||||
}
|
||||
|
||||
fn fill(&self, mem: &mut HostMemory, salt: u8) {
|
||||
pub(super) fn fill(&self, mem: &mut HostMemory, salt: u8) {
|
||||
for i in 0..5 {
|
||||
if self.sizes[i] == 0 {
|
||||
continue;
|
||||
@@ -190,7 +201,7 @@ impl Fixture {
|
||||
}
|
||||
}
|
||||
|
||||
fn fill_after(&self, mem: &mut HostMemory, salt: u8, first_dirty: i64) {
|
||||
pub(super) fn fill_after(&self, mem: &mut HostMemory, salt: u8, first_dirty: i64) {
|
||||
for i in 0..5 {
|
||||
let offset = if i == 4 {
|
||||
(first_dirty / 4) as usize * self.g.idx_key_dim as usize * 4
|
||||
|
||||
Reference in New Issue
Block a user