mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-05 07:48:45 +00:00
inkling: park a slot's conversation in host RAM before another request overwrites it, and put it back (--slot-cache-mib, #7620)
A slot holds one conversation; a request that continues nothing of it (a title, a summary request, a helper agent) wiped it, and the next step of the chat read its whole prompt again (RTX 3060, 11K tokens: 30 to 46 s a step). With --slot-cache-mib N (or STRATA_INK_SLOT_CACHE_MIB, 0 = off, the default) the serve loop parks the slot's conversation first: InkBackend::park_slot(slot, seq_len) copies the global K/V of [0, seq_len) to a host buffer and moves the slot's prompt-end checkpoint into the parked object; unpark_slot writes the K/V back and restores the checkpoint, so the slot holds the conversation exactly as it was. The scheduler keeps the parked conversations under a byte budget, least recently used first, parks only conversations of 512 tokens or more, parks nothing for a normal follow-up, and reads from the start when a put-back fails. CUDA backend (one GPU, not the layer split): the K/V copy follows the descriptor layout (card part, virtual-memory range or mapped host tail; FP16 K and V, FP8 / K8V8 / K8V4 also the scale arrays). Other backends keep the default (cannot park). Tests: test_shared_prefix.py (7 new, GPU-free, mock backend that aborts on a restore over a different K/V).
This commit is contained in:
1 parent
03bb4f48ba
commit
21699a4c08
6 files changed
+342
-4
No files matched your search
@@ -1189,6 +1189,99 @@ public:
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- #7620 (--slot-cache-mib): a slot's conversation parked in host RAM, and put back ----
|
||||
// The global K/V of one slot, positions [0, n), visit by visit (global visits only), to / from one host buffer. Per visit the arrays are K, V and, for
|
||||
// FP8 / K8V8 / K8V4, the K and V scales (FP16: K and V). A position below the card's part is read from the card (or the virtual-memory range), the rest
|
||||
// from the mapped host tail (the descriptor's h_* arrays), exactly as ink_kv_load4 addresses them. false: n does not fit what is allocated.
|
||||
struct KvPark {
|
||||
void* dev = nullptr; // the visit's array on the card (or null)
|
||||
void* host = nullptr; // its mapped host tail (or null)
|
||||
size_t row = 0; // bytes of one position of this array
|
||||
size_t dev_stride = 0; // positions between two slots of the card's array
|
||||
size_t host_stride = 0; // positions between two slots of the host tail
|
||||
int dev_rows = 0; // positions [0, dev_rows) are on the card, [dev_rows, cap) on the host
|
||||
};
|
||||
int kv_park_arrays(int v, KvPark* out) const {
|
||||
const auto& kv = runner_->kv_desc[v];
|
||||
if (kv.is_swa) return 0;
|
||||
const size_t kvdim = (size_t)strata::ink::kInkKVHeads * strata::ink::kInkHeadDim;
|
||||
const int dev_rows = kv.host_cap > 0 ? kv.dev_cap : kv.cap_pos;
|
||||
const size_t dstride = kv.host_cap > 0 ? (size_t)kv.dev_cap : (size_t)kv.cap_pos;
|
||||
auto put = [&](int i, void* d, void* h, size_t row) {
|
||||
out[i].dev = d; out[i].host = h; out[i].row = row; out[i].dev_stride = dstride; out[i].host_stride = (size_t)kv.host_cap; out[i].dev_rows = dev_rows;
|
||||
};
|
||||
if (kv.kv_fmt == 0) {
|
||||
put(0, kv.k_f16, kv.h_k_f16, kvdim * sizeof(__half));
|
||||
put(1, kv.v_f16, kv.h_v_f16, kvdim * sizeof(__half));
|
||||
return 2;
|
||||
}
|
||||
put(0, kv.k_f8, kv.h_k_f8, kvdim);
|
||||
put(1, kv.v_f8, kv.h_v_f8, kv.kv_fmt == 3 ? kvdim / 2 : kvdim);
|
||||
put(2, kv.k_sc, kv.h_k_sc, (size_t)strata::ink::kInkKVHeads * sizeof(float));
|
||||
put(3, kv.v_sc, kv.h_v_sc, (size_t)strata::ink::kInkKVHeads * sizeof(float));
|
||||
return 4;
|
||||
}
|
||||
size_t kv_park_bytes(int n) const {
|
||||
size_t total = 0;
|
||||
KvPark a[4];
|
||||
for (int v = 0; v < strata::ink::kInkVisits; ++v) {
|
||||
const int na = kv_park_arrays(v, a);
|
||||
for (int i = 0; i < na; ++i) total += a[i].row * (size_t)n;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
bool kv_park_io(bool to_host, int slot, int n, uint8_t* buf) {
|
||||
KvPark a[4];
|
||||
size_t off = 0;
|
||||
cudaSetDevice(gpu_id_);
|
||||
INK_CK(cudaStreamSynchronize(runner_->st));
|
||||
for (int v = 0; v < strata::ink::kInkVisits; ++v) {
|
||||
const int na = kv_park_arrays(v, a);
|
||||
if (na == 0) continue;
|
||||
if (n > runner_->kv_desc[v].cap_pos) return false;
|
||||
for (int i = 0; i < na; ++i) {
|
||||
const int on_card = std::min(n, a[i].dev_rows);
|
||||
if (on_card > 0) {
|
||||
if (!a[i].dev) return false;
|
||||
uint8_t* p = static_cast<uint8_t*>(a[i].dev) + (size_t)slot * a[i].dev_stride * a[i].row;
|
||||
INK_CK(cudaMemcpy(to_host ? (void*)(buf + off) : (void*)p, to_host ? (const void*)p : (const void*)(buf + off), (size_t)on_card * a[i].row, cudaMemcpyDefault));
|
||||
}
|
||||
if (n > on_card) {
|
||||
if (!a[i].host) return false;
|
||||
uint8_t* p = static_cast<uint8_t*>(a[i].host) + (size_t)slot * a[i].host_stride * a[i].row; // host rows start at position dev_rows
|
||||
uint8_t* q = buf + off + (size_t)on_card * a[i].row;
|
||||
if (to_host) std::memcpy(q, p, (size_t)(n - on_card) * a[i].row); else std::memcpy(p, q, (size_t)(n - on_card) * a[i].row);
|
||||
}
|
||||
off += (size_t)n * a[i].row;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
std::unique_ptr<ParkedState> park_slot(int slot, int seq_len) override {
|
||||
if (!initialized_ || model_.ls_active || slot < 0 || slot >= max_slots_ || seq_len <= 0 || slot >= (int)prompt_ckpts_.size()) return nullptr;
|
||||
auto& ck = prompt_ckpts_[slot];
|
||||
if (!ck.valid || ck.seq_len != seq_len) return nullptr;
|
||||
auto parked = std::make_unique<CudaParked>();
|
||||
try {
|
||||
parked->kv.resize(kv_park_bytes(seq_len));
|
||||
if (!kv_park_io(true, slot, seq_len, parked->kv.data())) return nullptr;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return nullptr;
|
||||
}
|
||||
parked->ck = std::move(ck);
|
||||
ck = PromptCkpt{}; // the slot has no checkpoint now (the conversation lives in `parked`)
|
||||
return parked;
|
||||
}
|
||||
bool unpark_slot(int slot, int seq_len, ParkedState& st) override {
|
||||
if (!initialized_ || model_.ls_active || slot < 0 || slot >= max_slots_ || slot >= (int)prompt_ckpts_.size()) return false;
|
||||
auto* parked = dynamic_cast<CudaParked*>(&st);
|
||||
if (!parked || !parked->ck.valid || parked->ck.seq_len != seq_len || parked->kv.size() != kv_park_bytes(seq_len)) return false;
|
||||
if (!kv_park_io(false, slot, seq_len, parked->kv.data())) return false;
|
||||
prompt_ckpts_[slot] = std::move(parked->ck);
|
||||
parked->ck = PromptCkpt{};
|
||||
return restore_checkpoint(slot, seq_len, false);
|
||||
}
|
||||
|
||||
void snapshot_slot(int slot) override {
|
||||
if (!initialized_ || slot < 0 || slot >= max_slots_ || model_.ls_active || !d_sconv_snap_) return;
|
||||
strata::ink::k_ink_sconv_slot_copy<<<dim3(strata::ink::kInkVisits, 4), 256, 0, runner_->st>>>(
|
||||
@@ -2769,6 +2862,15 @@ private:
|
||||
strata::ink::PinnedVec<uint8_t> dspark_k, dspark_v;
|
||||
strata::ink::PinnedVec<float> dspark_frnn;
|
||||
};
|
||||
// #7620: a parked conversation: the slot's prompt-end checkpoint and the global K/V up to it (kv_park_io's layout)
|
||||
struct CudaParked final : ParkedState {
|
||||
PromptCkpt ck;
|
||||
std::vector<uint8_t> kv;
|
||||
size_t bytes() const override {
|
||||
return kv.size() + ck.sconv.size() * sizeof(float) + ck.swa_k.size() + ck.swa_v.size() + ck.swa_ksc.size() + ck.swa_vsc.size()
|
||||
+ ck.dspark_k.size() + ck.dspark_v.size() + ck.dspark_frnn.size() * sizeof(float);
|
||||
}
|
||||
};
|
||||
|
||||
bool initialized_ = false;
|
||||
int gpu_id_ = 0;
|
||||
|
||||
@@ -120,6 +120,26 @@ public:
|
||||
return false;
|
||||
}
|
||||
|
||||
// #7620 (opt-in, --slot-cache-mib): park a slot's conversation in host RAM before another request overwrites it, and put it back later.
|
||||
// park_slot(slot, seq_len) takes the slot's valid prompt-end checkpoint at `seq_len` (the one save_prompt_checkpoint made: ShortConv, SWA rings,
|
||||
// drafter state) and COPIES the global K/V of positions [0, seq_len) out; the slot's own checkpoint is gone afterwards. It returns null when the
|
||||
// backend cannot (no checkpoint at seq_len, layer split, no host memory). unpark_slot(slot, seq_len, st) writes the K/V back into the slot's
|
||||
// global K/V and restores the checkpoint, exactly what restore_prompt_checkpoint does for a slot whose K/V is intact; the slot then holds the
|
||||
// conversation as it was at seq_len, and the checkpoint stays valid for the next request. false: nothing was changed that matters (the caller
|
||||
// reads the prompt from the start).
|
||||
struct ParkedState {
|
||||
virtual ~ParkedState() = default;
|
||||
virtual size_t bytes() const = 0;
|
||||
};
|
||||
virtual std::unique_ptr<ParkedState> park_slot(int slot, int seq_len) {
|
||||
(void)slot; (void)seq_len;
|
||||
return nullptr;
|
||||
}
|
||||
virtual bool unpark_slot(int slot, int seq_len, ParkedState& st) {
|
||||
(void)slot; (void)seq_len; (void)st;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Separate shared-prefix snapshot; valid only while this slot's global KV prefix is intact.
|
||||
virtual bool supports_shared_checkpoint() const { return false; }
|
||||
virtual bool save_shared_checkpoint(int slot, int seq_len) {
|
||||
|
||||
@@ -1025,6 +1025,7 @@ int main(int argc, char** argv) {
|
||||
bool mode_serve = false, mode_bench = false, mode_selfcheck = false, mode_info = false, mode_export = false;
|
||||
bool verify_hash = false;
|
||||
bool vision_reader_given = false;
|
||||
bool slot_cache_given = false;
|
||||
std::string info_file, export_file, export_dir, kld_ref, dump_ref, prompt_ids_str;
|
||||
std::string tkl_corpus, tkl_cfgs, tkl_out, tkl_only, tgen_in, tgen_out, tgen_stop, tkl_calib, turbo_preset;
|
||||
bool fast_kernels_flag = false; // --fast-kernels: the card's opt-in fast kernel set (STRATA_INK_FAST_KERNELS=1)
|
||||
@@ -1103,6 +1104,10 @@ int main(int argc, char** argv) {
|
||||
} else if (a == "--tail-role-token") {
|
||||
// #7241 (opt-in): the id of <|message_system|>; with --serve, the prompt checkpoint goes in front of a trailing level turn (ink_serve.h)
|
||||
cfg.tail_role_token = std::atoll(next().c_str());
|
||||
} else if (a == "--slot-cache-mib") {
|
||||
// #7620 (opt-in): host RAM for conversations parked when another request is about to overwrite their slot (with --serve; 0 = off, the default)
|
||||
cfg.slot_cache_bytes = std::max<long long>(0, std::atoll(next().c_str())) * 1048576LL;
|
||||
slot_cache_given = true;
|
||||
} else if (a == "--chunk") {
|
||||
cfg.bopts.chunk = std::max(1, std::atoi(next().c_str()));
|
||||
cfg.bopts.chunk_auto = false;
|
||||
@@ -1284,6 +1289,10 @@ int main(int argc, char** argv) {
|
||||
if (cfg.bopts.vision_idle_s < 0) {
|
||||
if (const char* e = std::getenv("STRATA_INK_VISION_IDLE_S"); e && *e) cfg.bopts.vision_idle_s = std::max(0, std::atoi(e));
|
||||
}
|
||||
// #7620: --slot-cache-mib wins over STRATA_INK_SLOT_CACHE_MIB (host RAM, MiB, for conversations parked instead of overwritten; 0 / unset = off)
|
||||
if (!slot_cache_given) {
|
||||
if (const char* e = std::getenv("STRATA_INK_SLOT_CACHE_MIB"); e && *e) cfg.slot_cache_bytes = std::max<long long>(0, std::atoll(e)) * 1048576LL;
|
||||
}
|
||||
|
||||
if (mode_serve) {
|
||||
strata::core::set_serve_error_line(true);
|
||||
|
||||
@@ -62,6 +62,29 @@ public:
|
||||
bool supports_shared_checkpoint() const override { return !std::getenv("INK_TEST_NO_CHECKPOINT"); }
|
||||
bool save_shared_checkpoint(int s, int n) override { return save(s, n, shared[s]); }
|
||||
bool restore_shared_checkpoint(int s, int n) override { return restore(s, n, shared[s]); }
|
||||
// #7620: a parked conversation = the slot's global K/V up to n and its prompt-end checkpoint; putting it back rewrites the K/V (the restore above then finds it intact)
|
||||
struct MockParked final : ink2::InkBackend::ParkedState {
|
||||
std::vector<int32_t> global;
|
||||
Checkpoint ck;
|
||||
size_t bytes() const override { return (global.size() + ck.prefix.size()) * sizeof(int32_t) + 64; }
|
||||
};
|
||||
std::unique_ptr<ink2::InkBackend::ParkedState> park_slot(int s, int n) override {
|
||||
if (std::getenv("INK_TEST_NO_PARK") || n <= 0 || static_cast<int>(prompt[s].prefix.size()) != n || static_cast<int>(global[s].size()) < n) return nullptr;
|
||||
auto p = std::make_unique<MockParked>();
|
||||
p->global.assign(global[s].begin(), global[s].begin() + n);
|
||||
p->ck = std::move(prompt[s]);
|
||||
prompt[s] = {};
|
||||
return p;
|
||||
}
|
||||
bool unpark_slot(int s, int n, ink2::InkBackend::ParkedState& st) override {
|
||||
auto* p = dynamic_cast<MockParked*>(&st);
|
||||
if (std::getenv("INK_TEST_UNPARK_FAILS") || !p || static_cast<int>(p->ck.prefix.size()) != n || static_cast<int>(p->global.size()) != n) return false;
|
||||
global[s] = p->global;
|
||||
prompt[s] = p->ck;
|
||||
position[s] = n;
|
||||
recurrent[s] = p->ck.recurrent;
|
||||
return true;
|
||||
}
|
||||
bool forward_batch(const ink2::StepBatch& b, float* logits, ink2::TapCapture*, std::string&) override {
|
||||
int row = 0;
|
||||
for (int i = 0; i < b.n_tokens; ++i) {
|
||||
@@ -92,6 +115,9 @@ int main() {
|
||||
cfg.bopts.max_ctx = 32768;
|
||||
cfg.draft_mode = "off";
|
||||
if (const char* t = std::getenv("INK_TEST_TAIL_ROLE")) cfg.tail_role_token = std::atoll(t); // --tail-role-token
|
||||
if (const char* t = std::getenv("INK_TEST_SLOT_CACHE_MIB")) cfg.slot_cache_bytes = std::atoll(t) * 1048576LL; // --slot-cache-mib
|
||||
if (const char* t = std::getenv("INK_TEST_SLOT_CACHE_BYTES")) cfg.slot_cache_bytes = std::atoll(t); // the same in bytes (a budget the toy states fill)
|
||||
cfg.park_min_tokens = 8; // the test prompts are 24 tokens long
|
||||
int rc;
|
||||
{
|
||||
MockBackend backend;
|
||||
|
||||
@@ -516,6 +516,10 @@ struct ServeConfig {
|
||||
// short turn of that role (the thinking-effort turn Control puts at the END of the prompt, effort_position "end") has its prompt checkpoint one
|
||||
// token in front of that turn instead of at the end of the prompt, so a request that changes only the level reads only the tail.
|
||||
int64_t tail_role_token = -1;
|
||||
// --slot-cache-mib N (#7620, opt-in, 0 = off): host RAM for conversations parked when another request is about to overwrite their slot, and put back when
|
||||
// a later request continues one (a title, a summary request, a helper agent between two steps of a chat; the app puts a 12 GB card on one slot).
|
||||
int64_t slot_cache_bytes = 0;
|
||||
int park_min_tokens = 512; // the shortest conversation worth parking (a shorter one is read again faster than it is moved); tests lower it
|
||||
std::string version = "0.1.72";
|
||||
};
|
||||
|
||||
@@ -615,12 +619,12 @@ inline int run_serve_loop(const ServeConfig& cfg, InkModelFile& mf, InkBackend&
|
||||
if (kd == KvDtype::K8V4) return "k8v4";
|
||||
return "fp16";
|
||||
}();
|
||||
proto("INFO engine=strata-inkling-%s arch=inkling2_loop backend=%s model=%s layers=%d visits=%d vocab=%d chunk=%d batch_slots=%d slot_read=1 shared_prefix=%d kv_dtype=%s drafter=%s drafting=%s images=%d image_pad=%d parallel=%d ckpt_key=1 vision_reader=%s",
|
||||
proto("INFO engine=strata-inkling-%s arch=inkling2_loop backend=%s model=%s layers=%d visits=%d vocab=%d chunk=%d batch_slots=%d slot_read=1 shared_prefix=%d kv_dtype=%s drafter=%s drafting=%s images=%d image_pad=%d parallel=%d ckpt_key=1 vision_reader=%s slot_cache_mib=%d",
|
||||
cfg.version.c_str(), backend.backend_name(), base.c_str(), c.n_phys, c.n_visits, V, chunk_sz,
|
||||
P, backend.supports_shared_checkpoint() ? 1 : 0, kv_str,
|
||||
(mf.m.dspark.present || backend.dspark_ready()) ? "dspark" : "none",
|
||||
use_dspark ? "dspark" : "off",
|
||||
images_ok ? 1 : 0, c.image_token_id, kMaxParallelSlots, images_ok ? (vision_gpu ? "gpu" : "cpu") : "off");
|
||||
images_ok ? 1 : 0, c.image_token_id, kMaxParallelSlots, images_ok ? (vision_gpu ? "gpu" : "cpu") : "off", static_cast<int>(std::max<int64_t>(0, cfg.slot_cache_bytes) / 1048576));
|
||||
proto("READY %d stop hold holdb", eff_max_ctx);
|
||||
|
||||
std::vector<ActiveReq> reqs(P);
|
||||
@@ -628,6 +632,54 @@ inline int run_serve_loop(const ServeConfig& cfg, InkModelFile& mf, InkBackend&
|
||||
ServeInput in;
|
||||
in.start();
|
||||
|
||||
// #7620: conversations parked in host RAM (--slot-cache-mib). A slot holds one conversation; a request that continues nothing of it used to wipe it
|
||||
// (a title between two steps of an agent: the next step read the whole prompt again, 30 to 46 s at 11 to 16K tokens on a 12 GB card). With a budget the
|
||||
// slot's conversation (its prompt-end checkpoint and the global K/V up to it) is parked before it is overwritten and put back when a later prompt
|
||||
// starts with it. Least recently used goes first when the budget is full.
|
||||
struct ParkedConv {
|
||||
std::vector<int32_t> prefix; // the tokens the parked state covers (the checkpoint's prefix)
|
||||
std::unique_ptr<InkBackend::ParkedState> st;
|
||||
size_t bytes = 0;
|
||||
double used = 0.0;
|
||||
};
|
||||
std::vector<ParkedConv> parked;
|
||||
size_t parked_bytes = 0;
|
||||
const size_t park_budget = static_cast<size_t>(std::max<int64_t>(0, cfg.slot_cache_bytes));
|
||||
const int kParkMinTokens = std::max(1, cfg.park_min_tokens); // a conversation shorter than this is cheaper to read again than to move
|
||||
auto park_forget = [&](size_t i) { parked_bytes -= parked[i].bytes; parked.erase(parked.begin() + static_cast<std::ptrdiff_t>(i)); };
|
||||
auto park_make_room = [&](size_t need) {
|
||||
while (!parked.empty() && parked_bytes + need > park_budget) {
|
||||
size_t lru = 0;
|
||||
for (size_t i = 1; i < parked.size(); ++i) if (parked[i].used < parked[lru].used) lru = i;
|
||||
std::fprintf(stderr, "[ink-serve] parked conversation of %zu tokens dropped (the budget is full)\n", parked[lru].prefix.size());
|
||||
park_forget(lru);
|
||||
}
|
||||
};
|
||||
// the slot's conversation (rq.prompt_ckpt_prefix is what its checkpoint covers) goes to host RAM; false: nothing parked (too short, off, no room, the backend cannot)
|
||||
auto park_current = [&](ActiveReq& rq) -> bool {
|
||||
const int n = static_cast<int>(rq.prompt_ckpt_prefix.size());
|
||||
if (park_budget == 0 || n < kParkMinTokens) return false;
|
||||
for (auto& p : parked) if (p.prefix == rq.prompt_ckpt_prefix) { p.used = now_s(); return false; } // already parked
|
||||
auto st = backend.park_slot(rq.slot, n);
|
||||
if (!st) return false;
|
||||
const size_t b = st->bytes();
|
||||
if (b > park_budget) {
|
||||
std::fprintf(stderr, "[ink-serve] a conversation of %d tokens (%.0f MiB) does not fit the %.0f MiB slot cache: not parked\n", n, b / 1048576.0, park_budget / 1048576.0);
|
||||
return false;
|
||||
}
|
||||
park_make_room(b);
|
||||
ParkedConv pc;
|
||||
pc.prefix = rq.prompt_ckpt_prefix;
|
||||
pc.st = std::move(st);
|
||||
pc.bytes = b;
|
||||
pc.used = now_s();
|
||||
parked.push_back(std::move(pc));
|
||||
parked_bytes += b;
|
||||
std::fprintf(stderr, "[ink-serve] slot %d: conversation of %d tokens parked in host RAM (%.0f MiB; %zu parked, %.0f of %.0f MiB)\n", rq.slot, n, b / 1048576.0,
|
||||
parked.size(), parked_bytes / 1048576.0, park_budget / 1048576.0);
|
||||
return true;
|
||||
};
|
||||
|
||||
auto is_stop_tok = [&](int32_t tok) -> bool {
|
||||
return tok == c.eos_token_id || tok == c.eot_token_id;
|
||||
};
|
||||
@@ -758,7 +810,42 @@ inline int run_serve_loop(const ServeConfig& cfg, InkModelFile& mf, InkBackend&
|
||||
std::equal(rq.shared_prefix.begin(), rq.shared_prefix.end(), rq.prompt_ids.begin())) {
|
||||
shared_match = pg.pin;
|
||||
}
|
||||
if (shared_match > full_match && shared_match > ckpt_match &&
|
||||
// #7620 (--slot-cache-mib): a parked conversation this prompt starts with, longer than anything the slot itself offers, comes back; and the slot's
|
||||
// own conversation is parked first when this request is about to overwrite it (neither its stream nor its checkpoint continues into this prompt)
|
||||
bool parked_done = false;
|
||||
if (park_budget > 0) {
|
||||
const int best_here = std::max({full_match, ckpt_match, shared_match});
|
||||
int pi = -1, pl = 0;
|
||||
for (size_t i = 0; i < parked.size(); ++i) {
|
||||
const int n = static_cast<int>(parked[i].prefix.size());
|
||||
if (n > pl && n > best_here && n < rq.prompt_len &&
|
||||
std::equal(parked[i].prefix.begin(), parked[i].prefix.end(), rq.prompt_ids.begin())) { pi = static_cast<int>(i); pl = n; }
|
||||
}
|
||||
if (pi >= 0) {
|
||||
ParkedConv taken = std::move(parked[static_cast<size_t>(pi)]);
|
||||
park_forget(static_cast<size_t>(pi));
|
||||
park_current(rq); // the slot's own conversation changes places with the parked one
|
||||
parked_done = true;
|
||||
if (backend.unpark_slot(rq.slot, pl, *taken.st)) {
|
||||
reuse = pl;
|
||||
rq.cached_prefix = taken.prefix;
|
||||
rq.prompt_ckpt_prefix = taken.prefix; // the checkpoint came back with it: the next request can use it again
|
||||
rq.shared_prefix.clear(); // the K/V it pinned was rewritten
|
||||
std::fprintf(stderr, "[ink-serve] slot %d: parked conversation of %d tokens put back (%zu parked, %.0f MiB)\n", rq.slot, pl, parked.size(), parked_bytes / 1048576.0);
|
||||
} else {
|
||||
backend.reset_slot(rq.slot); // the K/V may be half written: read from the start
|
||||
rq.cached_prefix.clear();
|
||||
rq.prompt_ckpt_prefix.clear();
|
||||
rq.shared_prefix.clear();
|
||||
std::fprintf(stderr, "[ink-serve] slot %d: the parked conversation of %d tokens could not be put back\n", rq.slot, pl);
|
||||
}
|
||||
} else if (full_match == 0 && ckpt_match == 0) {
|
||||
park_current(rq);
|
||||
}
|
||||
}
|
||||
if (parked_done) {
|
||||
// decided above
|
||||
} else if (shared_match > full_match && shared_match > ckpt_match &&
|
||||
backend.restore_shared_checkpoint(rq.slot, shared_match)) {
|
||||
reuse = shared_match;
|
||||
rq.cached_prefix = rq.shared_prefix;
|
||||
|
||||
@@ -12,12 +12,13 @@ B = PREFIX + [31, 32, 33, 34]
|
||||
|
||||
|
||||
class Engine:
|
||||
def __init__(self, no_checkpoint=False, tail_role=None):
|
||||
def __init__(self, no_checkpoint=False, tail_role=None, extra_env=None):
|
||||
env = dict(os.environ)
|
||||
if no_checkpoint:
|
||||
env["INK_TEST_NO_CHECKPOINT"] = "1"
|
||||
if tail_role is not None:
|
||||
env["INK_TEST_TAIL_ROLE"] = str(tail_role)
|
||||
env.update(extra_env or {})
|
||||
self.p = subprocess.Popen([ENGINE], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
text=True, env=env)
|
||||
self.info = {}
|
||||
@@ -318,5 +319,98 @@ class QuitShutdown(unittest.TestCase):
|
||||
self.run_once(50, None)
|
||||
|
||||
|
||||
CHAT = list(range(100, 140)) # a conversation (40 tokens; its prompt-end checkpoint covers the first 39)
|
||||
HELPER = list(range(500, 520)) # a title request: another prompt, 20 tokens
|
||||
OTHER = list(range(700, 730))
|
||||
|
||||
|
||||
class ParkedConversations(unittest.TestCase):
|
||||
"""#7620 (--slot-cache-mib): a request that continues nothing of the slot's conversation used to wipe it; with a budget the conversation is parked in
|
||||
host RAM first and comes back when a later prompt starts with it. The mock backend keeps its global K/V as tokens and refuses a restore over K/V that
|
||||
is not the checkpoint's, so a wrong put-back cannot pass: every reused answer is compared with a cold run."""
|
||||
|
||||
def engine(self, **env):
|
||||
e = Engine(extra_env={"INK_TEST_SLOT_CACHE_MIB": "64", **env})
|
||||
self.addCleanup(e.close)
|
||||
return e
|
||||
|
||||
def cold(self, ids):
|
||||
e = Engine()
|
||||
try:
|
||||
return e.request(ids, pin=None)[0]
|
||||
finally:
|
||||
e.close()
|
||||
|
||||
def test_without_a_budget_the_helper_request_wipes_the_conversation(self):
|
||||
e = Engine()
|
||||
self.addCleanup(e.close)
|
||||
self.assertEqual(e.info.get("slot_cache_mib"), "0")
|
||||
e.request(CHAT, pin=None)
|
||||
e.request(HELPER, pin=None)
|
||||
_, reuse = e.request(CHAT + [201, 202, 203], pin=None)
|
||||
self.assertEqual(reuse, 0)
|
||||
|
||||
def test_a_parked_conversation_comes_back_after_a_helper_request_and_answers_as_cold(self):
|
||||
e = self.engine()
|
||||
self.assertEqual(e.info.get("slot_cache_mib"), "64")
|
||||
self.assertEqual(e.request(CHAT, pin=None)[1], 0)
|
||||
self.assertEqual(e.request(HELPER, pin=None)[1], 0)
|
||||
follow = CHAT + [201, 202, 203]
|
||||
tokens, reuse = e.request(follow, pin=None)
|
||||
self.assertEqual(reuse, len(CHAT) - 1, "the chat's prompt-end checkpoint came back")
|
||||
self.assertEqual(tokens, self.cold(follow))
|
||||
|
||||
def test_two_conversations_change_places_each_time_and_both_answer_as_cold(self):
|
||||
e = self.engine()
|
||||
e.request(CHAT, pin=None)
|
||||
e.request(HELPER, pin=None)
|
||||
a = CHAT + [201, 202]
|
||||
self.assertEqual(e.request(a, pin=None)[1], len(CHAT) - 1)
|
||||
b = HELPER + [301, 302]
|
||||
tokens, reuse = e.request(b, pin=None)
|
||||
self.assertEqual(reuse, len(HELPER) - 1, "the helper's conversation was parked when the chat came back")
|
||||
self.assertEqual(tokens, self.cold(b))
|
||||
a2 = a + [211, 212]
|
||||
tokens, reuse = e.request(a2, pin=None)
|
||||
self.assertGreaterEqual(reuse, len(CHAT) - 1)
|
||||
self.assertEqual(tokens, self.cold(a2))
|
||||
|
||||
def test_a_normal_follow_up_parks_nothing(self):
|
||||
e = self.engine()
|
||||
first, _ = e.request(CHAT, pin=None)
|
||||
follow = CHAT + first + [201, 202]
|
||||
tokens, reuse = e.request(follow, pin=None)
|
||||
self.assertGreater(reuse, len(CHAT) - 1, "the held stream continued: no checkpoint or parked state was needed")
|
||||
self.assertEqual(tokens, self.cold(follow))
|
||||
|
||||
def test_the_least_recently_used_conversation_goes_when_the_budget_is_full(self):
|
||||
# room for one toy state beside a small one: the 40-token chat is 376 bytes, the 20-token helper 216, the budget 500
|
||||
for newest_first in (False, True):
|
||||
e = Engine(extra_env={"INK_TEST_SLOT_CACHE_BYTES": "500"})
|
||||
self.addCleanup(e.close)
|
||||
e.request(CHAT, pin=None)
|
||||
e.request(HELPER, pin=None) # the chat is parked (376 of 500 bytes)
|
||||
e.request(OTHER, pin=None) # the helper is parked: 376 + 216 does not fit, the chat (the oldest) goes
|
||||
if newest_first:
|
||||
self.assertEqual(e.request(HELPER + [301], pin=None)[1], len(HELPER) - 1, "the newer parked state is still there")
|
||||
else:
|
||||
self.assertEqual(e.request(CHAT + [201], pin=None)[1], 0, "the oldest was dropped for the budget: read again")
|
||||
|
||||
def test_a_state_that_cannot_be_put_back_is_read_again_and_answers_as_cold(self):
|
||||
e = self.engine(INK_TEST_UNPARK_FAILS="1")
|
||||
e.request(CHAT, pin=None)
|
||||
e.request(HELPER, pin=None)
|
||||
follow = CHAT + [201, 202, 203]
|
||||
tokens, reuse = e.request(follow, pin=None)
|
||||
self.assertEqual(reuse, 0)
|
||||
self.assertEqual(tokens, self.cold(follow))
|
||||
|
||||
def test_a_backend_that_cannot_park_behaves_as_before(self):
|
||||
e = self.engine(INK_TEST_NO_PARK="1")
|
||||
e.request(CHAT, pin=None)
|
||||
e.request(HELPER, pin=None)
|
||||
self.assertEqual(e.request(CHAT + [201, 202, 203], pin=None)[1], 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user