Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

Parking with a layer split: the draft ring once, every stage's K/V reused, checkpoints moved not copied

benoit langeaf7918f02dc8
diff --git a/include/strata/core/conversation_cache.hpp b/include/strata/core/conversation_cache.hpp
index 9ad7e36d6..b105deb60 100644
--- a/include/strata/core/conversation_cache.hpp
+++ b/include/strata/core/conversation_cache.hpp
@@ -53,13 +53,72 @@ struct ConversationKvReuse {
std::vector<ConversationKv> kv;
// Original image extent for validation, and the earliest subsequent rewrite.
int64_t captured_tokens = 0, unchanged_tokens = 0;
+ // With a layer split: the later stages' own retained K/V, one per stage, same extents (empty: none)
+ std::vector<ConversationKvReuse> stages;
size_t bytes() const {
- size_t n = kv.capacity() * sizeof(ConversationKv);
+ size_t n = kv.capacity() * sizeof(ConversationKv) + stages.capacity() * sizeof(ConversationKvReuse);
for (const auto& layer : kv) n += layer.bytes();
+ for (const auto& s : stages) n += s.bytes();
return n;
}
};
+/// Layer-split parking: each running checkpoint holds the first stage's state and, in `stage_parts`, one part per
+/// later stage; a parked conversation keeps them in one image per stage. `split` MOVES the checkpoints apart (no
+/// running state is copied): the complete ones (a part for each of `stages` stages) into `stage0` and `parts[k]`,
+/// every part carrying the checkpoint's ids / images / LRU stamp, the others aside; `merge` puts them back in their
+/// original order. merge(split(x)) == x.
+struct ConversationCheckpointSplit {
+ std::vector<ConversationCheckpoint> stage0;
+ std::vector<std::vector<ConversationCheckpoint>> parts; ///< [stage][checkpoint]
+ std::vector<ConversationCheckpoint> rest; ///< not split (no complete set of stage parts)
+ std::vector<bool> complete; ///< per original position: in stage0/parts or in rest
+};
+
+inline ConversationCheckpointSplit conversation_checkpoints_split(std::vector<ConversationCheckpoint>&& checks,
+ size_t stages) {
+ ConversationCheckpointSplit out;
+ out.parts.resize(stages);
+ for (auto& c : checks) {
+ const bool whole = c.stage_parts.size() == stages;
+ out.complete.push_back(whole);
+ if (!whole) { out.rest.push_back(std::move(c)); continue; }
+ for (size_t k = 0; k < stages; ++k) {
+ ConversationCheckpoint part = std::move(c.stage_parts[k]);
+ part.ids = c.ids; part.imgs = c.imgs; part.used = c.used; part.stage_parts.clear();
+ out.parts[k].push_back(std::move(part));
+ }
+ c.stage_parts.clear();
+ out.stage0.push_back(std::move(c));
+ }
+ checks.clear();
+ return out;
+}
+
+/// false (and `out` empty) when the parts do not line up: a stage with another number of checkpoints, or a part
+/// whose ids differ from its checkpoint's.
+inline bool conversation_checkpoints_merge(ConversationCheckpointSplit&& split, std::vector<ConversationCheckpoint>& out) {
+ out.clear();
+ for (const auto& p : split.parts)
+ if (p.size() != split.stage0.size()) return false;
+ size_t whole = 0, other = 0;
+ for (bool c : split.complete) (c ? whole : other) += 1;
+ if (!split.complete.empty() && (whole != split.stage0.size() || other != split.rest.size())) return false;
+ if (split.complete.empty()) split.complete.assign(split.stage0.size(), true); // a restored image: all whole
+ for (size_t j = 0; j < split.stage0.size(); ++j)
+ for (const auto& p : split.parts)
+ if (p[j].ids != split.stage0[j].ids) return false;
+ size_t w = 0, r = 0;
+ for (bool c : split.complete) {
+ if (!c) { out.push_back(std::move(split.rest[r++])); continue; }
+ ConversationCheckpoint cp = std::move(split.stage0[w]);
+ for (auto& p : split.parts) cp.stage_parts.push_back(std::move(p[w]));
+ ++w;
+ out.push_back(std::move(cp));
+ }
+ return true;
+}
+
struct SavedConversation {
// Runtime compatibility only; NOT a model/weights identity or disk schema.
std::array<int64_t, 18> geometry{};
@@ -113,13 +172,17 @@ public:
// Retain only the restored K/V buffers, not duplicate running checkpoints.
// This optimization never evicts a parked conversation to make itself fit.
- void retain(std::vector<ConversationKv>&& kv, int64_t tokens) {
+ // `stage_kv`: with a layer split, the later stages' restored K/V (one per stage), retained with the first's.
+ void retain(std::vector<ConversationKv>&& kv, int64_t tokens,
+ std::vector<std::vector<ConversationKv>>&& stage_kv = {}) {
reuse_ = {};
- ConversationKvReuse candidate{std::move(kv), tokens, tokens};
+ ConversationKvReuse candidate{std::move(kv), tokens, tokens, {}};
+ for (auto& k : stage_kv) candidate.stages.push_back(ConversationKvReuse{std::move(k), tokens, tokens, {}});
if (enabled() && candidate.bytes() <= budget_ - bytes_) reuse_ = std::move(candidate);
}
void limit_reuse(int64_t first_dirty) {
reuse_.unchanged_tokens = std::min(reuse_.unchanged_tokens, first_dirty);
+ for (auto& s : reuse_.stages) s.unchanged_tokens = std::min(s.unchanged_tokens, first_dirty);
if (reuse_.unchanged_tokens <= 0) reuse_ = {};
}
ConversationKvReuse take_reuse() { return std::exchange(reuse_, {}); }
diff --git a/include/strata/core/conversation_snapshot.hpp b/include/strata/core/conversation_snapshot.hpp
index a840bf2ed..1a56680df 100644
--- a/include/strata/core/conversation_snapshot.hpp
+++ b/include/strata/core/conversation_snapshot.hpp
@@ -76,4 +76,21 @@ ConversationRestore conversation_snapshot_restore(const SavedConversation& image
const ModelGeometry& g, const QsaState& draft,
std::string& error);
+// The same with `draft == nullptr`: an image WITHOUT the draft layer's K/V (kv holds the session's own QSA layers
+// only). A layer split's later stages park this way; the draft ring is saved once, with the first stage's image.
+// An image is validated and restored with the same kind of call it was saved with (a K/V layer count mismatch is
+// rejected as invalid).
+bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& session, const ModelGeometry& g,
+ const QsaState* draft, size_t& bytes, std::string& error);
+bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const ConversationView& view,
+ const SessionState& session, const ModelGeometry& g, const QsaState* draft,
+ size_t& bytes, std::string& error);
+bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view, const SessionState& session,
+ const ModelGeometry& g, const QsaState* draft, std::string& error,
+ ConversationKvReuse reuse = {}, size_t* reused_bytes = nullptr);
+bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& session,
+ const ModelGeometry& g, const QsaState* draft, std::string& error);
+ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& session,
+ const ModelGeometry& g, const QsaState* draft, std::string& error);
+
} // namespace strata::core
diff --git a/src/core/conversation_cache_test.cpp b/src/core/conversation_cache_test.cpp
index f10b729b5..f544dd743 100644
--- a/src/core/conversation_cache_test.cpp
+++ b/src/core/conversation_cache_test.cpp
@@ -2,6 +2,7 @@
#include <cstdio>
#include <cstdlib>
+#include <vector>
using namespace strata::core;
@@ -209,5 +210,96 @@ int main() {
check(!disabled.put(image({1,2,3})) && !no_slots.put(image({1,2,3})), "disabled cache stores nothing");
check(disabled.best(a,{},true).tokens == 0, "disabled cache has no matches");
}
+ {
+ // layer-split parking: checkpoints moved apart into stage parts and put back, no running state copied
+ auto running = [](std::initializer_list<int32_t> ids, uint8_t salt, size_t parts) {
+ ConversationCheckpoint c;
+ c.ids = ids;
+ c.gdn.assign(256, salt);
+ c.tails.assign(32, uint8_t(salt + 1));
+ c.used = salt;
+ for (size_t k = 0; k < parts; ++k) {
+ ConversationCheckpoint p;
+ p.gdn.assign(128, uint8_t(salt + 10 + k));
+ c.stage_parts.push_back(std::move(p));
+ }
+ return c;
+ };
+ std::vector<ConversationCheckpoint> checks;
+ checks.push_back(running({1, 2}, 3, 2));
+ checks.push_back(running({1, 2, 3}, 5, 1)); // an incomplete set: kept aside, put back in place
+ checks.push_back(running({1, 2, 3, 4}, 7, 2));
+ const auto original = checks;
+ const uint8_t* gdn0 = checks[0].gdn.data();
+ const uint8_t* part1 = checks[2].stage_parts[1].gdn.data();
+ auto split = conversation_checkpoints_split(std::move(checks), 2);
+ check(checks.empty() && split.stage0.size() == 2 && split.rest.size() == 1 && split.parts.size() == 2 &&
+ split.parts[0].size() == 2 && split.parts[1].size() == 2, "split: complete checkpoints apart, the other aside");
+ check(split.stage0[0].stage_parts.empty() && split.parts[1][1].ids == original[2].ids &&
+ split.parts[1][1].used == original[2].used && split.parts[0][0].gdn == original[0].stage_parts[0].gdn,
+ "split: every stage part carries its checkpoint's ids and LRU stamp");
+ check(split.stage0[0].gdn.data() == gdn0 && split.parts[1][1].gdn.data() == part1,
+ "split moves the running state (same buffers, no copy)");
+ std::vector<ConversationCheckpoint> back;
+ check(conversation_checkpoints_merge(std::move(split), back) && back.size() == 3, "merge puts them back");
+ bool same = true;
+ for (size_t j = 0; j < back.size(); ++j) {
+ same = same && back[j].ids == original[j].ids && back[j].gdn == original[j].gdn &&
+ back[j].tails == original[j].tails && back[j].used == original[j].used &&
+ back[j].stage_parts.size() == original[j].stage_parts.size();
+ for (size_t k = 0; same && k < back[j].stage_parts.size(); ++k)
+ same = back[j].stage_parts[k].gdn == original[j].stage_parts[k].gdn;
+ }
+ check(same, "merge(split(x)) == x, in the original order");
+ check(back[0].gdn.data() == gdn0 && back[2].stage_parts[1].gdn.data() == part1, "merge moves them back too");
+
+ auto torn = conversation_checkpoints_split(std::vector<ConversationCheckpoint>(original), 2);
+ torn.parts[1].pop_back();
+ check(!conversation_checkpoints_merge(std::move(torn), back) && back.empty(), "a stage short of a part is refused");
+ auto mixed = conversation_checkpoints_split(std::vector<ConversationCheckpoint>(original), 2);
+ mixed.parts[0][0].ids = {9, 9};
+ check(!conversation_checkpoints_merge(std::move(mixed), back) && back.empty(), "a part of another checkpoint is refused");
+ // a restored image: stage 0's checkpoints and each stage's, with no record of an incomplete one
+ ConversationCheckpointSplit restored;
+ restored.stage0.push_back(running({4, 5}, 11, 0));
+ restored.parts.resize(2);
+ for (auto& p : restored.parts) { auto c = running({4, 5}, 12, 0); p.push_back(std::move(c)); }
+ check(conversation_checkpoints_merge(std::move(restored), back) && back.size() == 1 &&
+ back[0].stage_parts.size() == 2, "a restored image's parts are all whole");
+ auto none = conversation_checkpoints_split({}, 3);
+ check(conversation_checkpoints_merge(std::move(none), back) && back.empty(), "no checkpoints: nothing to do");
+ }
+ {
+ // the later stages' retained K/V, kept with the first stage's and limited together
+ auto kv = [](size_t n) {
+ std::vector<ConversationKv> v(2);
+ for (auto& l : v) l.k.resize(n, 1);
+ return v;
+ };
+ ConversationCache cache(1 << 20, 4);
+ std::vector<std::vector<ConversationKv>> stage_kv;
+ stage_kv.push_back(kv(1000));
+ stage_kv.push_back(kv(2000));
+ cache.retain(kv(500), 40, std::move(stage_kv));
+ check(cache.retained_bytes() >= 2 * (500 + 1000 + 2000), "retained bytes count every stage");
+ cache.limit_reuse(30);
+ auto r = cache.take_reuse();
+ check(r.kv.size() == 2 && r.stages.size() == 2 && r.unchanged_tokens == 30 &&
+ r.stages[0].unchanged_tokens == 30 && r.stages[1].unchanged_tokens == 30 &&
+ r.stages[1].captured_tokens == 40, "every stage's reuse is limited to the first rewrite");
+ check(cache.retained_bytes() == 0, "taken once");
+ std::vector<std::vector<ConversationKv>> big;
+ big.push_back(kv(1 << 20));
+ cache.retain(kv(500), 40, std::move(big));
+ check(cache.retained_bytes() == 0, "a stage's K/V over the budget drops the whole reuse");
+ std::vector<std::vector<ConversationKv>> one;
+ one.push_back(kv(100));
+ cache.retain(kv(500), 40, std::move(one));
+ cache.limit_reuse(0);
+ check(cache.retained_bytes() == 0, "a rewrite from the start drops every stage's reuse");
+ cache.retain(kv(500), 40);
+ r = cache.take_reuse();
+ check(r.kv.size() == 2 && r.stages.empty(), "no layer split: no stage reuse, as before");
+ }
std::printf("conversation_cache_test: %d checks passed\n", checks);
}
diff --git a/src/core/conversation_snapshot_test.cpp b/src/core/conversation_snapshot_test.cpp
index da95113c6..215ec560d 100644
--- a/src/core/conversation_snapshot_test.cpp
+++ b/src/core/conversation_snapshot_test.cpp
@@ -187,6 +187,43 @@ void full_session(int fmt, int mode, int experts) {
check(conversation_kv_verify(incremental.kv.back(),draft.state,g,70,false,fingerprint,err),"incremental draft authoritative and ring read-back");
ids.resize(65);
}
+ {
+ // a layer split's later stage: the same image WITHOUT the draft layer's K/V (draft == nullptr)
+ check(conversation_snapshot_restore(a,ss,g,draft.state,err)==ConversationRestore::restored,"restore A before stage images");
+ size_t with_draft=0,without=0;
+ check(conversation_snapshot_bytes(view,ss,g,draft.state,with_draft,err) &&
+ conversation_snapshot_bytes(view,ss,g,nullptr,without,err) && without<with_draft,
+ "a stage image's estimate leaves the draft out");
+ SavedConversation stage,stage_b,stage_back;
+ check(conversation_snapshot_save(stage,view,ss,g,nullptr,err),"capture a stage image");
+ check(stage.kv.size()==a.kv.size()-1 && equal(stage.kv[0],a.kv[0]) && stage.live.gdn==a.live.gdn,
+ "a stage image holds the session's own layers, no draft");
+ check(stage.bytes()<a.bytes(),"a stage image is smaller by the draft ring");
+ check(conversation_snapshot_validate(stage,ss,g,nullptr,err),"validate a stage image without a draft");
+ check(!conversation_snapshot_validate(stage,ss,g,draft.state,err),"a stage image is refused where a draft is expected");
+ check(!conversation_snapshot_validate(a,ss,g,nullptr,err),"an image with a draft is refused where none is expected");
+ fill(201);
+ check(conversation_snapshot_save(stage_b,view,ss,g,nullptr,err),"capture another stage state");
+ check(conversation_snapshot_restore(a,ss,g,nullptr,err)==ConversationRestore::invalid,
+ "restoring a draft image as a stage image is refused before any write");
+ check(conversation_snapshot_save(stage_back,view,ss,g,nullptr,err) && stage_back.live.gdn==stage_b.live.gdn &&
+ equal(stage_back.kv[0],stage_b.kv[0]),"the refusal left the stage untouched");
+ check(conversation_snapshot_restore(stage,ss,g,nullptr,err)==ConversationRestore::restored,"restore a stage image");
+ check(conversation_snapshot_save(stage_back,view,ss,g,nullptr,err) && stage_back.live.gdn==stage.live.gdn &&
+ stage_back.live.dead==stage.live.dead && equal(stage_back.kv[0],stage.kv[0]),"stage A/B/A exactness");
+ // its retained K/V: the next park copies only what changed, and equals a full capture
+ ConversationKvReuse reuse{stage.kv,65,65,{}};
+ SavedConversation fresh,incremental;
+ size_t peak=0,reused=0;
+ check(conversation_snapshot_save(fresh,view,ss,g,nullptr,err),"full stage capture reference");
+ check(conversation_snapshot_capture_bytes(reuse,view,ss,g,nullptr,peak,err),"admit an incremental stage capture");
+ check(conversation_snapshot_save(incremental,view,ss,g,nullptr,err,std::move(reuse),&reused),"incremental stage capture");
+ check(reused>0 && incremental.bytes()<=peak && equal(incremental.kv[0],fresh.kv[0]) &&
+ incremental.live.gdn==fresh.live.gdn,"an incremental stage capture reuses pages and equals a full one");
+ ConversationKvReuse wrong{a.kv,65,65,{}};
+ check(!conversation_snapshot_capture_bytes(wrong,view,ss,g,nullptr,peak,err),"a draft image's K/V is not a stage's reuse");
+ }
+ check(conversation_snapshot_restore(a,ss,g,draft.state,err)==ConversationRestore::restored,"restore A after stage images");
check(conversation_checkpoint_restore(a.checkpoints[0],ss,g,err),"restore early running checkpoint");
std::vector<uint8_t> spare(sizes.dead);
cuda_check(cudaMemcpy(spare.data(),main.state.idx_pooled,sizes.dead,cudaMemcpyDeviceToHost));
diff --git a/src/core/conversation_state.cpp b/src/core/conversation_state.cpp
index 3e97827cb..1a45e7f14 100644
--- a/src/core/conversation_state.cpp
+++ b/src/core/conversation_state.cpp
@@ -193,7 +193,7 @@ bool conversation_checkpoint_restore(const ConversationCheckpoint& c, SessionSta
}
bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& ss,
- const ModelGeometry& g, const QsaState& draft, size_t& bytes, std::string& error) {
+ const ModelGeometry& g, const QsaState* draft, size_t& bytes, std::string& error) {
bytes = 0;
if (!view_validate(view, ss, g, error)) return false;
ConversationStateSizes z;
@@ -203,7 +203,7 @@ bool conversation_snapshot_bytes(const ConversationView& view, const SessionStat
if (!product(ids, {view.ids.size(), sizeof(int32_t)}) ||
!product(images, {view.images.size(), sizeof(ConversationImageKey)}) ||
!product(checkpoints, {view.checkpoints.size(), sizeof(ConversationCheckpoint)}) ||
- !product(layers, {qsa + 1, sizeof(ConversationKv)}) ||
+ !product(layers, {qsa + (draft ? 1 : 0), sizeof(ConversationKv)}) ||
!product(tails, {qsa, z.tail}) || !product(dead, {qsa, z.dead}) ||
!product(positions, {qsa, z.block_pos})) return fail(error, "snapshot metadata byte count overflow");
for (size_t n : {ids, images, checkpoints, layers, tails, dead, positions, z.gdn, ss.ple_hist ? z.ple : 0})
@@ -211,8 +211,8 @@ bool conversation_snapshot_bytes(const ConversationView& view, const SessionStat
for (const auto& c : view.checkpoints)
if (!metadata_bytes(c, bytes)) return fail(error, "checkpoint byte count overflow");
const int64_t upto = (int64_t) view.ids.size(); // view_validate bounds this by signed max_cells
- for (uint64_t i = 0; i <= qsa; ++i) {
- const auto& st = i == qsa ? draft : owned(ss, (size_t) i);
+ for (uint64_t i = 0; i < qsa + (draft ? 1 : 0); ++i) {
+ const auto& st = i == qsa ? *draft : owned(ss, (size_t) i);
const size_t n = conversation_kv_bytes(st, g, upto, i != qsa);
if (!n || !add(bytes, n)) return fail(error, "invalid or overflowing K/V byte estimate");
}
@@ -221,16 +221,16 @@ bool conversation_snapshot_bytes(const ConversationView& view, const SessionStat
bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const ConversationView& view,
const SessionState& ss, const ModelGeometry& g,
- const QsaState& draft, size_t& bytes, std::string& error) {
+ const QsaState* draft, size_t& bytes, std::string& error) {
if (!conversation_snapshot_bytes(view, ss, g, draft, bytes, error)) return false;
if (reuse.kv.empty()) return true;
- const size_t layers = owned_qsa(ss) + 1;
+ const size_t layers = owned_qsa(ss) + (draft ? 1 : 0);
if (reuse.kv.size() != layers || reuse.unchanged_tokens < 0 ||
reuse.unchanged_tokens > reuse.captured_tokens || reuse.unchanged_tokens > int64_t(view.ids.size()))
return fail(error, "invalid retained K/V prefix");
for (size_t i = 0; i < layers; ++i) {
- const bool index = i + 1 != layers;
- const auto& st = index ? owned(ss, i) : draft;
+ const bool index = i < owned_qsa(ss);
+ const auto& st = index ? owned(ss, i) : *draft;
if (!conversation_kv_validate(reuse.kv[i], st, g, reuse.captured_tokens, index, error)) return false;
const size_t fresh = conversation_kv_bytes(st, g, int64_t(view.ids.size()), index);
size_t retained = 0;
@@ -246,7 +246,7 @@ bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const
bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view,
const SessionState& ss, const ModelGeometry& g,
- const QsaState& draft, std::string& error,
+ const QsaState* draft, std::string& error,
ConversationKvReuse reuse, size_t* reused_bytes) {
size_t estimate = 0;
if (!conversation_snapshot_capture_bytes(reuse, view, ss, g, draft, estimate, error) || !sync(error)) return false;
@@ -259,7 +259,7 @@ bool conversation_snapshot_save(SavedConversation& image, const ConversationView
const int64_t unchanged = reuse.kv.empty() ? 0 : reuse.unchanged_tokens;
captured.kv = std::move(reuse.kv);
const size_t layers = owned_qsa(ss);
- captured.kv.resize(layers + 1);
+ captured.kv.resize(layers + (draft ? 1 : 0));
if (!conversation_checkpoint_save(captured.live, ss, g, error)) return false;
const int64_t upto = (int64_t) view.ids.size();
for (size_t j = 0; j < layers; ++j)
@@ -267,14 +267,14 @@ bool conversation_snapshot_save(SavedConversation& image, const ConversationView
unchanged, reused_bytes)) return false;
// The draft's final cell may not have been computed when the output cap was
// reached. Refresh that page even when the main prefix continued unchanged.
- if (!conversation_kv_save(captured.kv.back(), draft, g, upto, false, error,
- std::max<int64_t>(0, unchanged - 1), reused_bytes)) return false;
+ if (draft && !conversation_kv_save(captured.kv.back(), *draft, g, upto, false, error,
+ std::max<int64_t>(0, unchanged - 1), reused_bytes)) return false;
image = std::move(captured);
return true;
}
bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& ss,
- const ModelGeometry& g, const QsaState& draft, std::string& error) {
+ const ModelGeometry& g, const QsaState* draft, std::string& error) {
if (!image.live.stage_parts.empty()) return fail(error, "layer-split parking is not supported");
if (image.geometry != geometry_key(g)) return fail(error, "incompatible runtime geometry");
// an image holds exactly one carve's running state and K/V: same layer range or nothing
@@ -283,23 +283,47 @@ bool conversation_snapshot_validate(const SavedConversation& image, const Sessio
const ConversationView view{image.live.ids, image.live.imgs, image.checkpoints, image.cvec};
if (!view_validate(view, ss, g, error) || !conversation_checkpoint_validate(image.live, ss, g, error)) return false;
const size_t layers = owned_qsa(ss);
- if (image.kv.size() != layers + 1) return fail(error, "invalid K/V layer count");
+ if (image.kv.size() != layers + (draft ? 1 : 0)) return fail(error, "invalid K/V layer count");
const int64_t upto = (int64_t) image.live.ids.size();
for (size_t j = 0; j < layers; ++j)
if (!conversation_kv_validate(image.kv[j], owned(ss, j), g, upto, true, error)) return false;
- return conversation_kv_validate(image.kv.back(), draft, g, upto, false, error);
+ return !draft || conversation_kv_validate(image.kv.back(), *draft, g, upto, false, error);
}
ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& ss,
- const ModelGeometry& g, const QsaState& draft, std::string& error) {
+ const ModelGeometry& g, const QsaState* draft, std::string& error) {
if (!conversation_snapshot_validate(image, ss, g, draft, error)) return ConversationRestore::invalid;
if (!sync(error)) return ConversationRestore::transfer_failed;
const int64_t upto = (int64_t) image.live.ids.size();
for (size_t j = 0; j < owned_qsa(ss); ++j)
if (!conversation_kv_restore(image.kv[j], owned(ss, j), g, upto, true, error))
return ConversationRestore::transfer_failed;
- if (!conversation_kv_restore(image.kv.back(), draft, g, upto, false, error) ||
+ if ((draft && !conversation_kv_restore(image.kv.back(), *draft, g, upto, false, error)) ||
!conversation_checkpoint_restore(image.live, ss, g, error)) return ConversationRestore::transfer_failed;
return ConversationRestore::restored;
}
+
+// the draft layer's K/V included (the stage that owns the draft head, or no layer split)
+bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& ss, const ModelGeometry& g,
+ const QsaState& draft, size_t& bytes, std::string& error) {
+ return conversation_snapshot_bytes(view, ss, g, &draft, bytes, error);
+}
+bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const ConversationView& view,
+ const SessionState& ss, const ModelGeometry& g, const QsaState& draft,
+ size_t& bytes, std::string& error) {
+ return conversation_snapshot_capture_bytes(reuse, view, ss, g, &draft, bytes, error);
+}
+bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view, const SessionState& ss,
+ const ModelGeometry& g, const QsaState& draft, std::string& error,
+ ConversationKvReuse reuse, size_t* reused_bytes) {
+ return conversation_snapshot_save(image, view, ss, g, &draft, error, std::move(reuse), reused_bytes);
+}
+bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& ss, const ModelGeometry& g,
+ const QsaState& draft, std::string& error) {
+ return conversation_snapshot_validate(image, ss, g, &draft, error);
+}
+ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& ss,
+ const ModelGeometry& g, const QsaState& draft, std::string& error) {
+ return conversation_snapshot_restore(image, ss, g, &draft, error);
+}
} // namespace strata::core
diff --git a/src/program/generate.cpp b/src/program/generate.cpp
index 295f196dc..6b0f33bcf 100644
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@ -4654,67 +4654,72 @@ int main(int argc, char** argv) {
// addresses change: all parked images live in ordinary host vectors.
auto park_current = [&](size_t held) -> bool {
if (!conversations.enabled() || !live_ok || live.empty()) return true;
- // a split parks every stage; a checkpoint's stage parts go into that stage's image
- const bool split_park = !stages.empty();
- std::vector<ConvCheckpoint> checks0;
- std::vector<std::vector<ConvCheckpoint>> checks_k(stages.size());
- if (split_park) {
- for (const ConvCheckpoint& c : checks) {
- if (c.stage_parts.size() != stages.size()) continue;
- ConvCheckpoint b;
- b.ids = c.ids; b.imgs = c.imgs; b.gdn = c.gdn; b.ple = c.ple; b.tails = c.tails;
- b.dead = c.dead; b.block_pos = c.block_pos; b.used = c.used;
- checks0.push_back(std::move(b));
- for (size_t k = 0; k < stages.size(); ++k) {
- ConvCheckpoint part = c.stage_parts[k];
- part.ids = c.ids; part.imgs = c.imgs; part.used = c.used; part.stage_parts.clear();
- checks_k[k].push_back(std::move(part));
- }
- }
- }
- const strata::core::ConversationView view{live, live_imgs, split_park ? checks0 : checks, cvec_cached};
- size_t stage_estimate = 0;
- for (size_t k = 0; k < stages.size(); ++k) {
+ // #342: before make_room evicts oldest-first, the copies of this conversation a turn back go (they hold
+ // nothing the outgoing chain does not, apart from the tail this conversation rewrote)
+ if (const size_t dropped = conversations.drop_superseded(live, live_imgs, checks, cvec_cached))
+ std::fprintf(stderr, "strata serve: conversation cache: dropped %zu superseded cop%s of this "
+ "conversation; parked=%zu\n", dropped, dropped == 1 ? "y" : "ies", conversations.size());
+ // A layer split parks one image per stage: the first stage's (with the draft layer's K/V) and one per
+ // later stage (without it - the draft ring is saved once). The checkpoints are MOVED apart into their
+ // stage parts for the capture and put back together whichever way this ends (no running state copied).
+ const size_t n_st = stages.size();
+ strata::core::ConversationCheckpointSplit cs;
+ if (n_st > 0) cs = strata::core::conversation_checkpoints_split(std::move(checks), n_st);
+ struct MergeBack {
+ strata::core::ConversationCheckpointSplit& cs; std::vector<ConvCheckpoint>& checks; bool on;
+ ~MergeBack() { if (on && !strata::core::conversation_checkpoints_merge(std::move(cs), checks)) checks.clear(); }
+ } merge_back{cs, checks, n_st > 0};
+ const strata::core::ConversationView view{live, live_imgs, n_st > 0 ? cs.stage0 : checks, cvec_cached};
+ auto reuse = conversations.take_reuse();
+ std::vector<strata::core::ConversationKvReuse> stage_reuse = std::move(reuse.stages);
+ stage_reuse.resize(n_st);
+ reuse.stages.clear();
+ // the later stages' estimates, each with its own retained K/V when it still fits
+ size_t stage_estimate = 0, stage_retained = 0;
+ for (size_t k = 0; k < n_st; ++k) {
auto& st = stages[k];
const strata::core::OnDevice on(st->dev);
- const strata::core::ConversationView view_k{live, live_imgs, checks_k[k], cvec_cached};
+ const strata::core::ConversationView view_k{live, live_imgs, cs.parts[k], cvec_cached};
size_t b = 0;
- if (!strata::core::conversation_snapshot_bytes(view_k, st->ss, g, mtp.kv_state(), b, err)) {
+ if (!strata::core::conversation_snapshot_bytes(view_k, st->ss, g, nullptr, b, err)) {
std::fprintf(stderr, "strata serve: conversation cache: skip parking (stage CUDA%d: %s)\n",
st->dev, err.c_str());
err.clear();
return true;
}
+ if (!stage_reuse[k].kv.empty()) {
+ size_t r = 0;
+ if (strata::core::conversation_snapshot_capture_bytes(stage_reuse[k], view_k, st->ss, g, nullptr,
+ r, err)) {
+ b = r;
+ stage_retained += stage_reuse[k].bytes();
+ } else {
+ stage_reuse[k] = {};
+ err.clear();
+ }
+ }
stage_estimate += b;
}
- auto reuse = conversations.take_reuse();
size_t estimate = 0;
if (!strata::core::conversation_snapshot_bytes(view, ss, g, mtp.kv_state(), estimate, err)) {
std::fprintf(stderr, "strata serve: conversation cache: skip parking (%s)\n", err.c_str());
err.clear(); // A recoverable miss must not poison the batched draft prefill's error channel.
return true;
}
- estimate += stage_estimate;
const size_t fresh_estimate = estimate;
if (!reuse.kv.empty() && !strata::core::conversation_snapshot_capture_bytes(
reuse, view, ss, g, mtp.kv_state(), estimate, err)) {
reuse = {};
estimate = fresh_estimate;
err.clear();
- } else if (!reuse.kv.empty()) {
- estimate += stage_estimate; // the capture estimate covers stage 0 only
}
+ estimate += stage_estimate;
// A park carrying its own retained K/V replaces memory the cache
// already held, so capacity is make_room's call - it runs next either
// way, and put()'s accounting still bounds the budget. The with-reuse
// estimate must stay uncapped: it counts the retained buffers'
// capacity and directories, and put() charges that same true size -
// 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 (they hold
- // nothing the outgoing chain does not, apart from the tail this conversation rewrote)
- if (const size_t dropped = conversations.drop_superseded(live, live_imgs, checks, cvec_cached))
- std::fprintf(stderr, "strata serve: conversation cache: dropped %zu superseded cop%s of this "
- "conversation; parked=%zu\n", dropped, dropped == 1 ? "y" : "ies", conversations.size());
if (!conversations.make_room(estimate, held)) {
std::fprintf(stderr, "strata serve: conversation cache: skip parking (snapshot %zu MiB exceeds available budget)\n",
estimate >> 20);
@@ -4723,7 +4728,8 @@ int main(int argc, char** argv) {
const auto t0 = Clock::now();
try {
const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib * 1024 * 1024;
- const size_t additional = estimate - reuse.bytes();
+ const size_t retained = reuse.bytes() + stage_retained;
+ const size_t additional = estimate > retained ? estimate - retained : 0;
if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(),
additional, floor)) {
std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM admission; need %zu MiB plus %lld MiB floor, or telemetry unavailable)\n",
@@ -4734,13 +4740,14 @@ int main(int argc, char** argv) {
size_t reused_bytes = 0;
if (!strata::core::conversation_snapshot_save(image, view, ss, g, mtp.kv_state(), err,
std::move(reuse), &reused_bytes)) return false;
- for (size_t k = 0; k < stages.size(); ++k) { // the later stages' parts
+ for (size_t k = 0; k < n_st; ++k) { // the later stages, without the draft layer's K/V
auto& st = stages[k];
const strata::core::OnDevice on(st->dev);
if (cudaDeviceSynchronize() != cudaSuccess) { err = "stage sync failed"; return false; }
- const strata::core::ConversationView view_k{live, live_imgs, checks_k[k], cvec_cached};
+ const strata::core::ConversationView view_k{live, live_imgs, cs.parts[k], cvec_cached};
strata::core::SavedConversation part;
- if (!strata::core::conversation_snapshot_save(part, view_k, st->ss, g, mtp.kv_state(), err))
+ if (!strata::core::conversation_snapshot_save(part, view_k, st->ss, g, nullptr, err,
+ std::move(stage_reuse[k]), &reused_bytes))
return false;
image.stage_images.push_back(std::move(part));
}
@@ -5689,7 +5696,7 @@ int main(int argc, char** argv) {
if (incoming) for (size_t i = 0; i < stages.size(); ++i) {
const strata::core::OnDevice on(stages[i]->dev);
if (!strata::core::conversation_snapshot_validate(incoming->stage_images[i], stages[i]->ss, g,
- mtp.kv_state(), err)) {
+ nullptr, err)) { // a later stage's image holds no draft K/V
std::fprintf(stderr, "strata serve: conversation cache: discard invalid stage snapshot (%s)\n",
err.c_str());
incoming.reset();
@@ -5720,7 +5727,7 @@ int main(int argc, char** argv) {
for (size_t i = 0; i < stages.size(); ++i) { // the later stages' parts
const strata::core::OnDevice on(stages[i]->dev);
if (strata::core::conversation_snapshot_restore(incoming->stage_images[i], stages[i]->ss, g,
- mtp.kv_state(), err) != strata::core::ConversationRestore::restored) {
+ nullptr, err) != strata::core::ConversationRestore::restored) {
std::printf("ERR restoring parked conversation (stage CUDA%d): %s\n", stages[i]->dev,
err.c_str());
return 1;
@@ -5741,19 +5748,22 @@ int main(int argc, char** argv) {
}
live = std::move(incoming->live.ids);
live_imgs = std::move(incoming->live.imgs);
- checks = std::move(incoming->checkpoints);
- if (!stages.empty()) { // give each checkpoint back its stage parts
- bool ok = true;
- for (const auto& si : incoming->stage_images) ok = ok && si.checkpoints.size() == checks.size();
- if (!ok) checks.clear();
- else for (size_t j = 0; j < checks.size(); ++j)
- for (auto& si : incoming->stage_images) checks[j].stage_parts.push_back(std::move(si.checkpoints[j]));
+ if (stages.empty()) {
+ checks = std::move(incoming->checkpoints);
+ } else { // give each checkpoint back its stage parts (moved, not copied); none if they do not line up
+ strata::core::ConversationCheckpointSplit cs;
+ cs.stage0 = std::move(incoming->checkpoints);
+ for (auto& si : incoming->stage_images) cs.parts.push_back(std::move(si.checkpoints));
+ if (!strata::core::conversation_checkpoints_merge(std::move(cs), checks)) checks.clear();
}
cvec_cached = incoming->cvec;
resume = parked.tokens;
from_live = parked.live;
- if (std::getenv("STRATA_SNAPSHOT_FULL_CAPTURE") == nullptr)
- conversations.retain(std::move(incoming->kv), int64_t(live.size()));
+ if (std::getenv("STRATA_SNAPSHOT_FULL_CAPTURE") == nullptr) {
+ std::vector<std::vector<strata::core::ConversationKv>> stage_kv; // every stage's, for its next park
+ for (auto& si : incoming->stage_images) stage_kv.push_back(std::move(si.kv));
+ conversations.retain(std::move(incoming->kv), int64_t(live.size()), std::move(stage_kv));
+ }
incoming.reset(); // Running-state/checkpoint copies are no longer needed.
std::fprintf(stderr, "strata serve: conversation cache: restored %lld tokens (%s) in %.1f ms; parked=%zu bytes=%zu\n",
(long long) resume, from_live ? "live" : "checkpoint",
diff --git a/tools/parking_test.py b/tools/parking_test.py
index a62b39c72..cb2129822 100644
--- a/tools/parking_test.py
+++ b/tools/parking_test.py
@@ -47,11 +47,14 @@ def run(a, cfg, tok, with_b):
t0 = time.time()
got, done = gen(eng, out, follow, a.max_new)
dt = time.time() - t0
+ if with_b: # B again: A is parked a second time, from retained K/V (every stage's) - only its new tail copied
+ gen(eng, out, pb, 8)
eng.send("QUIT")
eng.p.wait(timeout=180)
log = open("/tmp/batch_test_engine.log").read()
restored = re.findall(r"restored \d+ tokens[^\n]*", log)
- return len(pa), len(follow), got, done, dt, restored
+ reparked = [int(x) for x in re.findall(r"parked \d+ tokens .*reused_kv_bytes=(\d+)", log)]
+ return len(pa), len(follow), got, done, dt, restored, reparked
def main():
@@ -74,7 +77,9 @@ def main():
first = next((k for k in range(min(len(ref[2]), len(park[2]))) if ref[2][k] != park[2][k]), None)
print("follow-up tokens:", "IDENTICAL" if same else f"DIFFER at {first}", f"({len(ref[2])} / {len(park[2])})")
print(" ", repr(tok.decode(park[2])[:200]))
- return 0 if same and park[5] else 1
+ reused = park[6][-1] if park[6] else 0
+ print(f"second park of A: {reused} bytes of K/V reused (retained from its restore)")
+ return 0 if same and park[5] and reused > 0 else 1
if __name__ == "__main__":