From 7f7f88688685d57e088fdd1f994ad3097d051ee4 Mon Sep 17 00:00:00 2001 From: Jeremiah Ritchey <44681828+jeremiahritchey@users.noreply.github.com> Date: Wed, 30 Sep 2026 04:38:41 +0000 Subject: [PATCH] Retain unchanged KV storage across repeated conversation parking Grow snapshot buffers in segments, track the first rewritten token, and charge retained active storage to the existing RAM budget. Refresh running state, partial pages and draft boundary state. Add full-capture versus incremental growth/rewind checks and report snapshot sizes with usable pressure-test budget ranges. --- docs/DETAILS.md | 11 +- include/strata/core/conversation_buffer.hpp | 132 ++++++++++++++ include/strata/core/conversation_cache.hpp | 34 +++- include/strata/core/conversation_snapshot.hpp | 11 +- src/core/conversation_cache_test.cpp | 45 +++++ src/core/conversation_snapshot.cpp | 68 +++++-- src/core/conversation_snapshot_test.cpp | 41 ++++- src/core/conversation_state.cpp | 40 ++++- src/core/conversation_validation_test.cpp | 30 ++++ src/program/generate.cpp | 29 ++- tools/conversation_cache_growth.py | 168 ++++++++++++++++++ tools/conversation_cache_parity.py | 33 +++- tools/test_conversation_cache_growth.py | 77 ++++++++ tools/test_conversation_cache_parity.py | 18 +- 14 files changed, 698 insertions(+), 39 deletions(-) create mode 100644 include/strata/core/conversation_buffer.hpp create mode 100644 tools/conversation_cache_growth.py create mode 100644 tools/test_conversation_cache_growth.py diff --git a/docs/DETAILS.md b/docs/DETAILS.md index b21652cf..45bc63aa 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -386,7 +386,12 @@ reported separately from Linux/CUDA evidence. Snapshots contain running state, checkpoints, used K/V pages, and draft-layer K/V. They add host RAM, not another model or VRAM allocation. The byte budget also counts -an incoming snapshot during a switch; oldest parked entries are evicted first. +an incoming snapshot during a switch. After a restore, unchanged K/V pages can be +retained for the next parking operation; growth appends storage without copying +the existing pages. Rewinds refresh the affected pages, and running state and +checkpoints are captured again. Retained active K/V counts against the same byte +budget and is discarded before evicting parked entries under memory pressure. +Oldest parked entries are evicted first. Oversized snapshots or host allocation failures fall back to ordinary prompt processing. `--conversation-cache-min-free-mib N` (default 2560) additionally requires that physical-RAM headroom remain available: the engine checks before allocation and @@ -399,7 +404,9 @@ The shared snapshot core validates all layers and checkpoints before applying an state. Invalid entries are discarded; transfer/synchronization failure is fatal rather than permission to continue with partial state. Indexer spare keys and the moving spare row are preserved, including checkpoint rewinds. -The engine log reports parking, restoration, bytes and evictions. Snapshots are not +The engine log reports parking, restoration, bytes, evictions, individual snapshot +sizes and K/V bytes reused during capture. `STRATA_SNAPSHOT_FULL_CAPTURE=1` disables +retention for diagnostic comparisons. Snapshots are not persisted across restarts. **Current limits (v1):** one request at a time, and one conversation cached at a time (switching between two chats diff --git a/include/strata/core/conversation_buffer.hpp b/include/strata/core/conversation_buffer.hpp new file mode 100644 index 00000000..a58a38bf --- /dev/null +++ b/include/strata/core/conversation_buffer.hpp @@ -0,0 +1,132 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace strata::core { + +// Snapshot-owned host storage. Appending never relocates existing payloads; +// only the small segment directory can move. No sharing or copy-on-write is +// needed because a parked image and its retained active buffers have one owner. +class ConversationBuffer { +public: + static constexpr size_t segment_bytes = 16 * 1024 * 1024; + ConversationBuffer() = default; + ConversationBuffer(std::initializer_list values) { + resize(values.size()); + visit(0, size(), [&](uint8_t* p, size_t n, size_t at) { + std::memcpy(p, values.begin() + at, n); + return true; + }); + } + ConversationBuffer(const ConversationBuffer&) = default; + ConversationBuffer& operator=(const ConversationBuffer&) = default; + ConversationBuffer(ConversationBuffer&& other) noexcept + : segments_(std::move(other.segments_)), size_(std::exchange(other.size_, 0)) {} + ConversationBuffer& operator=(ConversationBuffer&& other) noexcept { + if (this == &other) return *this; + segments_ = std::move(other.segments_); + size_ = std::exchange(other.size_, 0); + return *this; + } + + size_t size() const { return size_; } + bool empty() const { return size_ == 0; } + size_t bytes() const { + size_t n = segments_.capacity() * sizeof(Segment); + for (const auto& segment : segments_) n += segment.capacity(); + return n; + } + // Includes the old directory while reserve allocates its replacement. + // Saturation makes an overflowing estimate fail admission before resize. + size_t allocation_peak(size_t n) const { + size_t total = bytes(); + if (n <= size_) return total; + const size_t extra = n - size_; + if (!add(total, extra)) return SIZE_MAX; + size_t count = segments_.size(); + if (!add(count, extra / segment_bytes + (extra % segment_bytes != 0))) return SIZE_MAX; + if (count > segments_.capacity() && + (count > SIZE_MAX / sizeof(Segment) || !add(total, count * sizeof(Segment)))) return SIZE_MAX; + return total; + } + void resize(size_t n, uint8_t value = 0) { + if (n > size_) { + const size_t extra = n - size_; + segments_.reserve(segments_.size() + extra / segment_bytes + (extra % segment_bytes != 0)); + while (size_ < n) { + const size_t count = std::min(segment_bytes, n - size_); + segments_.emplace_back(count, value); + size_ += count; + } + } else { + while (!segments_.empty() && size_ - segments_.back().size() >= n) { + size_ -= segments_.back().size(); + segments_.pop_back(); + } + if (size_ > n) segments_.back().resize(segments_.back().size() - (size_ - n)); + size_ = n; + } + } + void pop_back() { resize(size_ - 1); } + + // fn(pointer, count, absolute_offset); false aborts a transfer immediately. + template bool visit(size_t offset, size_t count, Fn fn) { + return visit_impl(*this, offset, count, fn); + } + template bool visit(size_t offset, size_t count, Fn fn) const { + return visit_impl(*this, offset, count, fn); + } + bool read(void* target, size_t offset, size_t count) const { + return visit(offset, count, [&](const uint8_t* p, size_t n, size_t at) { + std::memcpy(static_cast(target) + at - offset, p, n); + return true; + }); + } + bool operator==(const ConversationBuffer& other) const { + if (size_ != other.size_) return false; + size_t a = 0, b = 0, x = 0, y = 0; + while (a < segments_.size() && b < other.segments_.size()) { + const auto& left = segments_[a]; + const auto& right = other.segments_[b]; + const size_t n = std::min(left.size() - x, right.size() - y); + if (std::memcmp(left.data() + x, right.data() + y, n)) return false; + x += n; y += n; + if (x == left.size()) { ++a; x = 0; } + if (y == right.size()) { ++b; y = 0; } + } + return true; + } + +private: + using Segment = std::vector; + static bool add(size_t& n, size_t extra) { + if (extra > SIZE_MAX - n) return false; + n += extra; + return true; + } + template static bool visit_impl(Self& self, size_t offset, size_t count, Fn fn) { + if (offset > self.size_ || count > self.size_ - offset) return false; + size_t begin = 0; + for (auto& segment : self.segments_) { + if (!count) break; + const size_t end = begin + segment.size(); + if (offset < end) { + const size_t n = std::min(count, end - offset); + if (!fn(segment.data() + offset - begin, n, offset)) return false; + offset += n; count -= n; + } + begin = end; + } + return count == 0; + } + std::vector segments_; + size_t size_ = 0; +}; + +} // namespace strata::core diff --git a/include/strata/core/conversation_cache.hpp b/include/strata/core/conversation_cache.hpp index 42409d3d..c1506c91 100644 --- a/include/strata/core/conversation_cache.hpp +++ b/include/strata/core/conversation_cache.hpp @@ -2,6 +2,8 @@ // Token equality, image identity, and steering mode are all required for reuse. #pragma once +#include "strata/core/conversation_buffer.hpp" + #include #include #include @@ -41,9 +43,19 @@ struct ConversationCheckpoint { struct ConversationKv { int format = 0; int64_t cells = 0, heads = 0, head_dim = 0, page_size = 0, pooled_rows = 0, idx_dim = 0; - std::vector k, v, k_scale, v_scale, pooled; + ConversationBuffer k, v, k_scale, v_scale, pooled; size_t bytes() const { - return k.capacity() + v.capacity() + k_scale.capacity() + v_scale.capacity() + pooled.capacity(); + return k.bytes() + v.bytes() + k_scale.bytes() + v_scale.bytes() + pooled.bytes(); + } +}; + +struct ConversationKvReuse { + std::vector kv; + int64_t captured_tokens = 0, unchanged_tokens = 0; + size_t bytes() const { + size_t n = kv.capacity() * sizeof(ConversationKv); + for (const auto& layer : kv) n += layer.bytes(); + return n; } }; @@ -89,10 +101,24 @@ public: ConversationCache(size_t budget, size_t slots) : budget_(budget), slots_(slots) {} bool enabled() const { return budget_ != 0 && slots_ != 0; } - size_t bytes() const { return bytes_; } + size_t bytes() const { return bytes_ + reuse_.bytes(); } size_t size() const { return entries_.size(); } size_t evictions() const { return evictions_; } + // 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&& kv, int64_t tokens) { + reuse_ = {}; + ConversationKvReuse candidate{std::move(kv), 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); + if (reuse_.unchanged_tokens <= 0) reuse_ = {}; + } + ConversationKvReuse take_reuse() { return std::exchange(reuse_, {}); } + size_t retained_bytes() const { return reuse_.bytes(); } + template Match best(const std::vector& prompt, const std::vector& images, bool cvec) const { Match best; @@ -122,6 +148,7 @@ public: // with take() but still alive during the exchange; count it against RAM too. bool make_room(size_t incoming, size_t held = 0) { if (!enabled() || held > budget_ || incoming > budget_ - held) return false; + if (bytes() > budget_ - held - incoming) reuse_ = {}; while (!entries_.empty() && (entries_.size() >= slots_ || bytes_ > budget_ - held - incoming)) { bytes_ -= entries_.front().bytes(); entries_.pop_front(); @@ -141,6 +168,7 @@ public: private: size_t budget_ = 0, slots_ = 0, bytes_ = 0, evictions_ = 0; std::deque entries_; // least recently active first + ConversationKvReuse reuse_; }; } // namespace strata::core diff --git a/include/strata/core/conversation_snapshot.hpp b/include/strata/core/conversation_snapshot.hpp index 550e373a..d75a017b 100644 --- a/include/strata/core/conversation_snapshot.hpp +++ b/include/strata/core/conversation_snapshot.hpp @@ -12,7 +12,10 @@ namespace strata::core { // include_index is false for the draft layer (its attention has no indexer). size_t conversation_kv_bytes(const QsaState& state, const ModelGeometry& g, int64_t upto, bool include_index); bool conversation_kv_save(ConversationKv& image, const QsaState& state, const ModelGeometry& g, - int64_t upto, bool include_index, std::string& error); + int64_t upto, bool include_index, std::string& error, + int64_t unchanged_tokens = 0, size_t* reused_bytes = nullptr); +bool conversation_kv_capture_bytes(const ConversationKv& image, const QsaState& state, const ModelGeometry& g, + int64_t upto, bool include_index, size_t& bytes, std::string& error); // No CUDA calls or destination writes. Used for whole-session prevalidation. bool conversation_kv_validate(const ConversationKv& image, const QsaState& state, const ModelGeometry& g, int64_t upto, bool include_index, std::string& error); @@ -43,11 +46,15 @@ struct ConversationView { }; 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); // Caller admits the estimate before invoking capture. Allocation failures propagate // to the RAM policy; the active session is never modified by capture. bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view, const SessionState& session, const ModelGeometry& g, - const QsaState& draft, std::string& error); + 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); enum class ConversationRestore { restored, invalid, transfer_failed }; diff --git a/src/core/conversation_cache_test.cpp b/src/core/conversation_cache_test.cpp index f6346d90..6b002005 100644 --- a/src/core/conversation_cache_test.cpp +++ b/src/core/conversation_cache_test.cpp @@ -21,6 +21,51 @@ SavedConversation image(std::initializer_list ids, bool cvec = true) { } int main() { + { + ConversationBuffer bytes; + const size_t first = ConversationBuffer::segment_bytes + 17; + const size_t peak = bytes.allocation_peak(first); + bytes.resize(first, 7); + check(bytes.bytes() <= peak, "segmented payload and directory fit admitted bytes"); + uint8_t* original = nullptr; + bytes.visit(0, 1, [&](uint8_t* p, size_t, size_t) { original = p; return true; }); + const size_t grown_peak = bytes.allocation_peak(first + 99); + bytes.resize(first + 99, 9); + bytes.visit(0, 1, [&](uint8_t* p, size_t, size_t) { + check(p == original, "appending preserves existing payload addresses"); return true; + }); + check(bytes.bytes() <= grown_peak, "growth including transient directory fits admission"); + std::vector tail(116); + check(bytes.read(tail.data(), ConversationBuffer::segment_bytes, tail.size()), "read spans segment boundaries"); + check(std::all_of(tail.begin(), tail.begin()+17, [](auto v){return v==7;}) && + std::all_of(tail.begin()+17, tail.end(), [](auto v){return v==9;}), "growth preserves prefix and initializes only suffix"); + auto copy = bytes; + bytes.resize(ConversationBuffer::segment_bytes + 10); + bytes.resize(first, 7); bytes.resize(first + 99, 9); + check(bytes == copy, "equality ignores differing segmentation after rewind and regrowth"); + check(!bytes.read(tail.data(), bytes.size()-1, 2), "range check rejects a truncated payload"); + check(bytes.allocation_peak(SIZE_MAX) == SIZE_MAX, "allocation estimate rejects overflow"); + } + { + ConversationKv layer; + layer.k.resize(400); + std::vector layers; + layers.push_back(std::move(layer)); + const size_t retained = layers.capacity()*sizeof(ConversationKv) + layers[0].bytes(); + const size_t parked = image({1,2,3}).bytes(); + ConversationCache cache(retained + parked, 4); + check(cache.put(image({1,2,3})), "park before retaining active storage"); + cache.retain(std::move(layers), 16); + check(cache.bytes() == retained + parked && cache.size() == 1, "active retained storage consumes bytes but no parked slot"); + cache.limit_reuse(9); cache.limit_reuse(12); + auto reuse = cache.take_reuse(); + check(reuse.unchanged_tokens == 9, "a later continuation cannot undo a rewind's dirty boundary"); + check(cache.bytes() == parked, "taking retained buffers releases their budget accounting"); + cache.retain(std::move(reuse.kv), 16); + check(cache.make_room(parked), "reservation can discard optional active buffers"); + check(cache.retained_bytes() == 0 && cache.size() == 1 && cache.evictions() == 0, + "pressure drops retained storage before evicting parked conversations"); + } const std::vector a = {1, 2, 3, 4}, b = {9, 8, 7, 6}; { ConversationCache cache(1024, 2); diff --git a/src/core/conversation_snapshot.cpp b/src/core/conversation_snapshot.cpp index 3e1254a5..f7bc0988 100644 --- a/src/core/conversation_snapshot.cpp +++ b/src/core/conversation_snapshot.cpp @@ -113,21 +113,40 @@ bool transfer(void* dst, const void* src, size_t n, std::string& error) { } } // namespace -size_t conversation_kv_bytes(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index) { - std::string error; +bool conversation_kv_capture_bytes(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, + int64_t upto, bool index, size_t& bytes, std::string& error) { Layout l{}; - if (!layout(st, g, upto, index, l, error) || !valid(st, l, upto, error)) return 0; - size_t bytes = l.pooled; - for (size_t n : {l.data, l.value_data, l.scales, l.value_scales}) - if (!conversation_detail::add(bytes, n)) return 0; - return bytes; + if (!layout(st, g, upto, index, l, error) || !valid(st, l, upto, error)) return false; + const std::array sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled}; + const std::array buffers = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; + bytes = 0; + for (size_t i = 0; i < buffers.size(); ++i) { + const size_t n = buffers[i]->allocation_peak(sizes[i]); + if (n == SIZE_MAX || !conversation_detail::add(bytes, n)) { + error = "conversation snapshot: segmented K/V allocation overflow"; + return false; + } + } + return true; +} + +size_t conversation_kv_bytes(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index) { + size_t bytes = 0; + std::string error; + return conversation_kv_capture_bytes({}, st, g, upto, index, bytes, error) ? bytes : 0; } bool conversation_kv_save(ConversationKv& image, const QsaState& st, const ModelGeometry& g, - int64_t upto, bool index, std::string& error) { + int64_t upto, bool index, std::string& error, + int64_t unchanged_tokens, size_t* reused_bytes) { Layout l{}; if (!layout(st, g, upto, index, l, error)) return false; if (!valid(st, l, upto, error)) return false; + if (unchanged_tokens < 0 || unchanged_tokens > upto || unchanged_tokens > image.cells) { + error = "conversation snapshot: invalid unchanged prefix"; + return false; + } + const int64_t whole_cells = (unchanged_tokens / l.page_size) * l.page_size; image.format = l.format; image.cells = l.cells; image.heads = g.n_head_kv; @@ -137,10 +156,18 @@ bool conversation_kv_save(ConversationKv& image, const QsaState& st, const Model image.idx_dim = g.idx_key_dim; const auto src = pools(st); const std::array sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled}; - const std::array*,5> dst = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; + const std::array dst = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; for (size_t i = 0; i < dst.size(); ++i) { + // Recopy the partial page and the indexer's moving spare row. Completed + // pages/rows strictly before the first rewritten token remain identical. + const size_t keep = i == 4 ? (index ? size_t(unchanged_tokens / strata::kernels::qsa_real_shapes().idx_block) * g.idx_key_dim * 4 : 0) + : l.cells ? (sizes[i] / size_t(l.cells)) * size_t(whole_cells) : 0; + if (keep > dst[i]->size()) { error = "conversation snapshot: missing reusable prefix"; return false; } dst[i]->resize(sizes[i]); - if (!transfer(dst[i]->data(), src[i], sizes[i], error)) return false; + if (!dst[i]->visit(keep, sizes[i] - keep, [&](uint8_t* p, size_t n, size_t at) { + return transfer(p, src[i] ? static_cast(src[i]) + at : nullptr, n, error); + })) return false; + if (reused_bytes) *reused_bytes += keep; } return true; } @@ -151,7 +178,7 @@ bool conversation_kv_validate(const ConversationKv& image, const QsaState& st, c if (!layout(st, g, upto, index, l, error)) return false; if (!valid(st, l, upto, error)) return false; const std::array sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled}; - const std::array*,5> src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; + const std::array src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; if (image.format != l.format || image.cells != l.cells || image.heads != g.n_head_kv || image.head_dim != g.head_dim || image.page_size != l.page_size || image.pooled_rows != l.pooled_rows || image.idx_dim != g.idx_key_dim) { @@ -169,10 +196,12 @@ bool conversation_kv_validate(const ConversationKv& image, const QsaState& st, c bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, int64_t upto, bool index, std::string& error) { if (!conversation_kv_validate(image, st, g, upto, index, error)) return false; - const std::array*,5> src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; + const std::array src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; const auto dst = pools(st); for (size_t i = 0; i < src.size(); ++i) - if (!transfer(dst[i], src[i]->data(), src[i]->size(), error)) return false; + if (!src[i]->visit(0, src[i]->size(), [&](const uint8_t* p, size_t n, size_t at) { + return transfer(static_cast(dst[i]) + at, p, n, error); + })) return false; // VRAM slots still contain the outgoing conversation. Resolve must refill // them from the restored authoritative pools before any attention reads. if (st.kv_mode == 1) strata::kernels::kv_stream_reset(st.map, nullptr); @@ -207,10 +236,12 @@ bool conversation_kv_verify(const ConversationKv& image, const QsaState& st, con } return true; }; - const std::array*, 5> saved = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; + const std::array saved = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; const auto authoritative = pools(st); for (size_t i = 0; i < saved.size(); ++i) - if (!compare(authoritative[i], saved[i]->data(), saved[i]->size(), true)) return false; + if (!saved[i]->visit(0, saved[i]->size(), [&](const uint8_t* p, size_t n, size_t at) { + return compare(static_cast(authoritative[i]) + at, p, n, true); + })) return false; if (st.kv_mode == 2 && image.cells > 0) { const auto resident = pools(st, true); const int64_t end = image.cells / image.page_size; @@ -219,8 +250,11 @@ bool conversation_kv_verify(const ConversationKv& image, const QsaState& st, con if (saved[i]->empty()) continue; const size_t page_bytes = saved[i]->size() / size_t(end); for (int64_t page = begin; page < end; ++page) - if (!compare(static_cast(resident[i]) + size_t(page % st.n_slots) * page_bytes, - saved[i]->data() + size_t(page) * page_bytes, page_bytes, false)) return false; + if (!saved[i]->visit(size_t(page) * page_bytes, page_bytes, + [&](const uint8_t* p, size_t n, size_t at) { + const size_t offset = size_t(page % st.n_slots) * page_bytes + at - size_t(page) * page_bytes; + return compare(static_cast(resident[i]) + offset, p, n, false); + })) return false; } } fingerprint = hash; diff --git a/src/core/conversation_snapshot_test.cpp b/src/core/conversation_snapshot_test.cpp index 515a6408..f298978d 100644 --- a/src/core/conversation_snapshot_test.cpp +++ b/src/core/conversation_snapshot_test.cpp @@ -90,6 +90,14 @@ struct Fixture { if (!data.empty()) cuda_check(cudaMemcpy(sources[i],data.data(),data.size(),cudaMemcpyDefault)); } } + void fill_after(uint8_t salt, int64_t first_dirty) { + for (size_t i=0;i offset) + cuda_check(cudaMemset(static_cast(sources[i])+offset, salt, sizes[i]-offset)); + } + } ~Fixture() { for (void* p:device) cudaFree(p); for (void* p:host) cudaFreeHost(p); } }; bool equal(const ConversationKv& a,const ConversationKv& b) { @@ -149,6 +157,35 @@ void full_session(int fmt, int mode, int experts) { restored.live.dead==a.live.dead && restored.live.block_pos==a.live.block_pos && equal(restored.kv[0],a.kv[0]) && equal(restored.kv[1],a.kv[1]),"whole-session A/B/A exactness including spare key"); check(ss.ple_prev[0]==64 && ss.ple_prev[1]==65,"PLE token window reconstructed"); + for (int64_t dirty : {65, 3, 0}) { + check(conversation_snapshot_restore(a,ss,g,draft.state,err)==ConversationRestore::restored,"restore growth fixture base"); + ConversationKvReuse reuse{a.kv,65,dirty}; + const uint8_t* original = nullptr; + reuse.kv[0].k.visit(0,1,[&](const uint8_t* p,size_t,size_t){original=p;return true;}); + main.fill_after(91,dirty); draft.fill_after(91,std::max(0,dirty-1)); + cuda_check(cudaMemset(ss.gdn_state,91,sizes.gdn)); + ids.resize(70); + for (size_t i=65;i=4)==(reused>0),"only complete unchanged pages or rows are retained"); + incremental.kv[0].k.visit(0,1,[&](const uint8_t* p,size_t,size_t){ + check(p==original,"growth never reallocates the retained payload");return true; + }); + check(conversation_snapshot_restore(incremental,ss,g,draft.state,err)==ConversationRestore::restored,"restore segmented incremental snapshot"); + uint64_t fingerprint=0; + check(conversation_kv_verify(incremental.kv.back(),draft.state,g,70,false,fingerprint,err),"incremental draft authoritative and ring read-back"); + ids.resize(65); + } check(conversation_checkpoint_restore(a.checkpoints[0],ss,g,err),"restore early running checkpoint"); std::vector spare(sizes.dead); cuda_check(cudaMemcpy(spare.data(),main.state.idx_pooled,sizes.dead,cudaMemcpyDeviceToHost)); @@ -214,7 +251,9 @@ int main() { std::vector got(code_block); for (int64_t page=b0;page expected(code_block); + check(a.k.read(expected.data(), page*code_block, code_block),"read segmented expected draft page"); + check(got == expected,"draft ring contains restored pages"); } } auto bad=a; bad.head_dim++; diff --git a/src/core/conversation_state.cpp b/src/core/conversation_state.cpp index 4841d8ed..b819acca 100644 --- a/src/core/conversation_state.cpp +++ b/src/core/conversation_state.cpp @@ -202,22 +202,54 @@ bool conversation_snapshot_bytes(const ConversationView& view, const SessionStat return true; } +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) { + if (!conversation_snapshot_bytes(view, ss, g, draft, bytes, error)) return false; + if (reuse.kv.empty()) return true; + const size_t layers = size_t(g.n_qsa_layers()) + 1; + 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 ? ss.qsa_states[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; + if (!conversation_kv_capture_bytes(reuse.kv[i], st, g, int64_t(view.ids.size()), index, retained, error)) return false; + bytes -= fresh; + if (!add(bytes, retained)) return fail(error, "retained K/V allocation overflow"); + } + size_t directory = 0; + if (!product(directory, {reuse.kv.capacity() - layers, sizeof(ConversationKv)}) || !add(bytes, directory)) + return fail(error, "retained K/V directory overflow"); + return true; +} + 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_bytes(view, ss, g, draft, estimate, error) || !sync(error)) return false; + if (!conversation_snapshot_capture_bytes(reuse, view, ss, g, draft, estimate, error) || !sync(error)) return false; // Build into a new object so a failure cannot publish a partial snapshot. SavedConversation captured; captured.geometry = geometry_key(g); captured.live.ids = view.ids; captured.live.imgs = view.images; captured.cvec = view.cvec; captured.checkpoints = view.checkpoints; + const int64_t unchanged = reuse.kv.empty() ? 0 : reuse.unchanged_tokens; + captured.kv = std::move(reuse.kv); captured.kv.resize((size_t) g.n_qsa_layers() + 1); if (!conversation_checkpoint_save(captured.live, ss, g, error)) return false; const int64_t upto = (int64_t) view.ids.size(); for (int64_t i = 0; i < g.n_qsa_layers(); ++i) - if (!conversation_kv_save(captured.kv[(size_t) i], ss.qsa_states[i], g, upto, true, error)) return false; - if (!conversation_kv_save(captured.kv.back(), draft, g, upto, false, error)) return false; + if (!conversation_kv_save(captured.kv[(size_t) i], ss.qsa_states[i], g, upto, true, error, + 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(0, unchanged - 1), reused_bytes)) return false; image = std::move(captured); return true; } diff --git a/src/core/conversation_validation_test.cpp b/src/core/conversation_validation_test.cpp index 3676b93d..5e4bb83e 100644 --- a/src/core/conversation_validation_test.cpp +++ b/src/core/conversation_validation_test.cpp @@ -15,9 +15,11 @@ // host-backend fault injection, not a claim of hardware-failure recovery. namespace { int copy_calls = 0, sync_calls = 0, fail_copy = 0, fail_sync = 0; +size_t copied_bytes = 0; } extern "C" cudaError_t __wrap_cudaMemcpy(void* dst, const void* src, size_t n, cudaMemcpyKind) { if (++copy_calls == fail_copy) return cudaErrorInvalidValue; + copied_bytes += n; std::memcpy(dst, src, n); return cudaSuccess; } @@ -178,6 +180,34 @@ void fixture(int format, int experts, bool zero_qsa, bool ple) { draft.data[0][0] ^= 1; fail_copy = copy_calls + 1; check(!conversation_kv_verify(image.kv.back(),draft.st,g,9,false,fingerprint,error), "read-back transfer failure is not a successful fingerprint"); + reset(); copied_bytes = 0; + const ConversationView view{image.live.ids,image.live.imgs,image.checkpoints,true}; + SavedConversation full,incremental; + check(conversation_snapshot_save(full,view,ss,g,draft.st,error), "full capture through host transfer backend"); + const size_t full_copies = copied_bytes; + ConversationKvReuse reuse{full.kv,9,9}; + size_t peak = 0, reused = 0; + check(conversation_snapshot_capture_bytes(reuse,view,ss,g,draft.st,peak,error), "incremental capture admission without transfers"); + copied_bytes = 0; + const bool saved_incrementally = conversation_snapshot_save(incremental,view,ss,g,draft.st,error,std::move(reuse),&reused); + if (!saved_incrementally) std::fprintf(stderr,"capture error: %s\n",error.c_str()); + check(saved_incrementally, "incremental capture through host backend"); + check(reused > 0 && copied_bytes + reused == full_copies, "reused byte count measures transfers actually omitted"); + check(incremental.bytes() <= peak && incremental.live.gdn == full.live.gdn, "running state refreshed within admitted allocation"); + for (size_t i=0;i bool { if (!conversations.enabled() || !live_ok || live.empty()) return true; const strata::core::ConversationView view{live, live_imgs, checks, cvec_cached}; + 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; } + 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(); + } + if (!conversations.make_room(estimate, held) && !reuse.kv.empty()) { + reuse = {}; // Optional retained storage must not prevent a full capture. + estimate = fresh_estimate; + } if (!conversations.make_room(estimate, held)) { std::fprintf(stderr, "strata serve: conversation cache: skip parking (snapshot %zu MiB exceeds available budget)\n", estimate >> 20); @@ -3278,22 +3290,26 @@ 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; - if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(), estimate, floor)) { + if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(), + estimate - reuse.bytes(), floor)) { std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM admission; need %zu MiB plus %lld MiB floor, or telemetry unavailable)\n", estimate >> 20, (long long) o.conversation_cache_min_free_mib); return true; } strata::core::SavedConversation image; - if (!strata::core::conversation_snapshot_save(image, view, ss, g, mtp.kv_state(), err)) return false; + 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; if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(), 0, floor)) { std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM floor after capture, or telemetry unavailable)\n"); return true; } + const size_t snapshot_bytes = image.bytes(); const bool stored = conversations.put(std::move(image), held); - std::fprintf(stderr, "strata serve: conversation cache: %s %zu tokens in %.1f ms; parked=%zu bytes=%zu evictions=%zu\n", + std::fprintf(stderr, "strata serve: conversation cache: %s %zu tokens in %.1f ms; parked=%zu bytes=%zu evictions=%zu snapshot_bytes=%zu reused_kv_bytes=%zu\n", stored ? "parked" : "skipped", live.size(), std::chrono::duration(Clock::now() - t0).count(), - conversations.size(), conversations.bytes(), conversations.evictions()); + conversations.size(), conversations.bytes(), conversations.evictions(), snapshot_bytes, reused_bytes); } catch (const std::bad_alloc&) { // The active state has not been touched. Continue with normal // prompt processing rather than killing a serving process. @@ -3885,7 +3901,9 @@ int main(int argc, char** argv) { cvec_cached = incoming->cvec; resume = parked.tokens; from_live = parked.live; - incoming.reset(); // release the transfer image before prompt processing + if (std::getenv("STRATA_SNAPSHOT_FULL_CAPTURE") == nullptr) + conversations.retain(std::move(incoming->kv), int64_t(live.size())); + 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", std::chrono::duration(Clock::now() - t0).count(), @@ -3952,6 +3970,7 @@ int main(int argc, char** argv) { tr("request", n, geni ? 1 : 0); mtp.set_prompt_len(n); const int64_t read_from = reread_to > 0 ? 0 : resume; + conversations.limit_reuse(read_from); pp_total = n; pp_from = read_from; pp_t0 = r0; diff --git a/tools/conversation_cache_growth.py b/tools/conversation_cache_growth.py new file mode 100644 index 00000000..9a455d4a --- /dev/null +++ b/tools/conversation_cache_growth.py @@ -0,0 +1,168 @@ +"""Compare full and incremental snapshot capture during growth and rewind. + +Private engines run sequentially; dry-run is the default. Both arms enable the +same conversation cache. The reference forces full capture for every parking. +""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import sys +import threading + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT), str(ROOT / 'tools')] +from conversation_cache_parity import STATE_KEYS, load_tokenizer, require, state_hashes +from conversation_cache_disabled import SETTINGS, common_args +from conversation_cache_soak import answer_text +from serve.frontend import ChatTemplate +from serve.server import StrataEngine, child_env + +NAMES = ['A', 'B-0', 'A-grow-0', 'B-1', 'A-grow-1', 'B-2', 'A-grow-2', + 'B-rewind', 'A-rewind', 'B-branch', 'A-branch', 'B-final'] +SECRET = 'SAPPHIRE' + + +def verify(results): + full, incremental = results['arms'] + require(full['name'] == 'full' and incremental['name'] == 'incremental', 'incorrect comparison arms') + requests = results['requests'] + require([r['name'] for r in requests] == NAMES, 'incomplete growth/rewind requests') + digest = hashlib.sha256(json.dumps(requests, sort_keys=True).encode()).hexdigest() + require(digest == results['request_digest'], 'request evidence changed') + for arm in (full, incremental): + require(arm['request_digest'] == digest and arm['args'] == full['args'], 'inputs or arguments differ') + require([r['name'] for r in arm['records']] == NAMES, 'incomplete growth/rewind outputs') + for key in (*SETTINGS, 'conversation_cache_mib', 'conversation_cache_slots'): + require(key in arm['info'] and arm['info'][key] == full['info'][key], f'engine setting differs: {key}') + require(arm['info']['conversation_cache_mib'] > 0, 'cache is not enabled') + budget = arm['info']['conversation_cache_mib'] * 1024 * 1024 + require(arm['parks'] and all(0 < p['snapshot_bytes'] <= p['bytes'] <= budget and + 0 <= p['reused_kv_bytes'] <= p['snapshot_bytes'] for p in arm['parks']), 'invalid allocation/reuse evidence') + require(arm['draft_verifications'] >= 4, 'missing restored draft read-back') + for request, reference, record in zip(requests, full['records'], arm['records']): + require(record['ids'] and record['finish'] in ('stop', 'length'), 'incomplete generation') + require(record['ids'] == reference['ids'], f'{record["name"]}: output differs') + require(set(STATE_KEYS) <= record['state'].keys() and record['state'] == reference['state'], + f'{record["name"]}: state differs or is incomplete') + require(record['reused'] == reference['reused'], 'prefix reuse differs') + require(record['prompt_tokens'] == len(request['ids']), 'prompt length differs') + if record['name'].startswith('A-'): + require(answer_text(record['text']) == SECRET.casefold(), 'known answer differs') + require(record['reused'] > 0, 'conversation was not restored') + require(all(p['reused_kv_bytes'] == 0 for p in full['parks']), 'reference did not force full captures') + require(sum(p['reused_kv_bytes'] > 0 for p in incremental['parks']) >= 3, 'repeated parking did not reuse KV bytes') + sizes = {r['name']: len(r['ids']) for r in requests} + require(sizes['A'] < sizes['A-grow-0'] < sizes['A-grow-1'] < sizes['A-grow-2'], 'conversation did not grow') + require(sizes['A-rewind'] == sizes['A-grow-0'] < sizes['A-grow-2'], 'missing rewind') + require(sizes['A-branch'] > sizes['A-rewind'], 'missing growth after rewind') + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument('--config', type=Path, required=True) + ap.add_argument('--engine', type=Path, required=True) + ap.add_argument('--output', type=Path, required=True, help='new output directory') + ap.add_argument('--paragraphs', type=int, default=128) + ap.add_argument('--spec', type=int, choices=(1, 4), default=1) + ap.add_argument('--cache-mib', type=int, default=8192) + ap.add_argument('--run', action='store_true') + a = ap.parse_args() + if a.paragraphs < 1 or a.cache_mib < 1: + ap.error('paragraphs and cache-mib must be positive') + if not a.run: + print('Dry run: paired full/incremental captures; growth, interruption, rewind and branch; no model loaded.') + return + cfg = json.loads(a.config.read_text()) + tok_path = Path(cfg['tokenizer']) + tok = load_tokenizer(tok_path) + template = ChatTemplate(tok_path / 'chat_template.jinja') + def encode(text): + return tok.encode(text, parse_special=True) + def prompt(text): + return encode(template.render([{'role': 'user', 'content': text}], enable_thinking=False)) + text = f'Remember the secret code {SECRET}.\n' + text += '\n'.join(f'Record {i}: blue square, green triangle, red circle.' for i in range(a.paragraphs)) + initial = prompt(text + f'\nThe secret code is {SECRET}. Reply OK.') + other = prompt('Unrelated worker. Reply HELLO.') + end = encode('<|im_end|>') + def continuation(ids, output, step): + close = [] if output[-len(end):] == end else end + filler = '\n'.join(f'Additional record {step}-{i}: blue square and green triangle.' for i in range(24)) + return ids + output + close + encode('\n<|im_start|>user\n' + filler + + '\nWhat is the secret code? Reply with only that word.<|im_end|>\n' + '<|im_start|>assistant\n\n\n\n\n') + args = common_args(cfg, a.spec) + ['--conversation-cache-mib', str(a.cache_mib), '--conversation-cache-slots', '4'] + env = child_env(cfg) + env['STRATA_STATE_HASH'] = '1' + env['STRATA_SNAPSHOT_VERIFY'] = '1' + env['STRATA_MTP_BATCH'] = '1' + a.output.mkdir(mode=0o700, parents=False, exist_ok=False) + results = {'requests': [], 'arms': [], 'spec': a.spec, 'paragraphs': a.paragraphs} + for name in ('full', 'incremental'): + current_env = dict(env) + if name == 'full': + current_env['STRATA_SNAPSHOT_FULL_CAPTURE'] = '1' + else: + current_env.pop('STRATA_SNAPSHOT_FULL_CAPTURE', None) + print('START', name, flush=True) + log = a.output / (name + '.log') + engine = StrataEngine(str(a.engine.resolve()), args, cwd=cfg.get('cwd'), log=str(log), env=current_env) + arm = {'name': name, 'args': args, 'info': dict(engine.info), 'records': []} + with a.engine.open('rb') as source: + arm['exe_sha256'] = hashlib.file_digest(source, 'sha256').hexdigest() + def generate(request): + ids = [x for x in engine.generate(request['ids'], request['max_new'], {'temperature': 0}, + threading.Event()) if x is not None] + arm['records'].append({'name': request['name'], 'ids': ids, 'text': tok.decode(ids), **engine.last}) + return ids + try: + if name == 'full': + def add(label, ids, count, expected=False): + request = {'name': label, 'ids': ids, 'max_new': count, 'expected': expected} + results['requests'].append(request) + return generate(request) + ids = initial + output = add('A', ids, 1) + first_growth = None + for step in range(3): + add(f'B-{step}', other, 1) + ids = continuation(ids, output, step) + if step == 0: + first_growth = list(ids) + output = add(f'A-grow-{step}', ids, 16, True) + add('B-rewind', other, 1) + output = add('A-rewind', first_growth, 16, True) + add('B-branch', other, 1) + add('A-branch', continuation(first_growth, output, 'branch'), 16, True) + add('B-final', other, 1) + results['request_digest'] = hashlib.sha256(json.dumps(results['requests'], sort_keys=True).encode()).hexdigest() + else: + for request in results['requests']: + generate(request) + finally: + engine.close() + engine.proc.wait(timeout=30) + engine.log.close() + log_text = log.read_text() + hashes = state_hashes(log_text) + require(len(hashes) == len(arm['records']), 'missing state fingerprints') + for record, state in zip(arm['records'], hashes): + record['state'] = state + parks = re.findall(r'conversation cache: parked (\d+) tokens in ([\d.]+) ms; parked=\d+ bytes=(\d+) ' + r'evictions=\d+ snapshot_bytes=(\d+) reused_kv_bytes=(\d+)', log_text) + arm['parks'] = [dict(tokens=int(p[0]), ms=float(p[1]), bytes=int(p[2]), snapshot_bytes=int(p[3]), + reused_kv_bytes=int(p[4])) for p in parks] + arm['draft_verifications'] = log_text.count('SNAPSHOT_VERIFY draft=') + arm['request_digest'] = hashlib.sha256(json.dumps(results['requests'], sort_keys=True).encode()).hexdigest() + results['arms'].append(arm) + (a.output / 'results.json').write_text(json.dumps(results, indent=2) + '\n') + print('DONE', name, flush=True) + verify(results) + (a.output / 'passed.json').write_text(json.dumps({'passed': True, 'request_digest': results['request_digest']}) + '\n') + print('PASS: growth and rewind preserve output/state; repeated captures reuse unchanged KV bytes') + + +if __name__ == '__main__': + main() diff --git a/tools/conversation_cache_parity.py b/tools/conversation_cache_parity.py index 80c467d2..cea5fc59 100644 --- a/tools/conversation_cache_parity.py +++ b/tools/conversation_cache_parity.py @@ -49,6 +49,25 @@ def engine_args(cfg, budget, spec): '--mtp-max-t', str(spec), '--suffix-draft', '0', '--spec-min-p', '0'] +def pressure_budget_hint(results, budget_mib): + sizes = [p['snapshot_bytes'] for p in results['pressure']['parks'] if p.get('snapshot_bytes', 0) > 0] + message = f'Configured --cache-mib {budget_mib}.' + if not sizes: + return message + ' No snapshot sizes recorded; use an engine that reports snapshot_bytes.' + mib = 1024 * 1024 + message += ' Observed snapshots: ' + ', '.join(f'{n / mib:.2f} MiB ({n} bytes)' for n in sizes) + '.' + if len(sizes) < 2: + return message + ' Need at least two captured snapshots to determine a pressure budget.' + # Fit every individual image but no adjacent pair in the A/B/C sequence. + low = (max(sizes) + mib - 1) // mib + high = (min(a + b for a, b in zip(sizes, sizes[1:])) - 1) // mib + if low <= high: + message += f' Use --cache-mib {low}..{high} to fit each snapshot but not two adjacent snapshots.' + else: + message += ' No whole-MiB budget fits every snapshot while excluding each adjacent pair; use similarly sized prompts.' + return message + + def verify_pressure(results, budget_mib, oversized=False): """Require actual byte-pressure evidence, not just correct output on misses.""" baseline, candidate = results['baseline'], results['candidate'] @@ -59,7 +78,9 @@ def verify_pressure(results, budget_mib, oversized=False): require(len(before['ids']) == len(after['ids']) == 1, 'missing pressure output') require(before['finish'] in ('length', 'stop') and after['finish'] in ('length', 'stop'), 'pressure request did not finish normally') - require(before['reused'] == after['reused'] == 0, 'pressure did not force a cache miss') + require(before['reused'] == after['reused'] == 0, + 'pressure did not force a cache miss; this run did not exercise the required fallback. ' + + pressure_budget_hint(results, budget_mib)) require(before['ids'] == after['ids'], 'pressure output differs') keys = set(STATE_KEYS) require(keys <= before['state'].keys() and keys <= after['state'].keys(), 'missing pressure state') @@ -78,7 +99,8 @@ def verify_pressure(results, budget_mib, oversized=False): else: require(evidence['skips'] == 0 and len(parks) == 3, 'snapshots must fit individually') require(all(0 < p['parked'] < 4 for p in parks), 'slot pressure confounds byte-pressure test') - require(parks[-1]['evictions'] > 0, 'no byte-pressure eviction observed; reduce --cache-mib') + require(parks[-1]['evictions'] > 0, 'no byte-pressure eviction observed. ' + + pressure_budget_hint(results, budget_mib)) def verify_results(results, prompt_tokens, spec): @@ -202,12 +224,15 @@ def main(): results[label] = records if label == 'candidate' and a.scenario != 'reuse': log_text = log.read_text() - parks = re.findall(r'conversation cache: parked \d+ tokens .*?parked=(\d+) bytes=(\d+) evictions=(\d+)', log_text) + parks = re.findall(r'conversation cache: parked \d+ tokens .*?parked=(\d+) bytes=(\d+) evictions=(\d+)(?: snapshot_bytes=(\d+))?', log_text) results['pressure'] = { - 'parks': [dict(zip(('parked', 'bytes', 'evictions'), map(int, p))) for p in parks], + 'parks': [dict(zip(('parked', 'bytes', 'evictions', 'snapshot_bytes'), + (int(value) if value else 0 for value in p))) for p in parks], 'skips': log_text.count('conversation cache: skip parking (snapshot '), 'memory_skips': log_text.count('conversation cache: skip parking (physical RAM admission;')} (a.output / 'results.json').write_text(json.dumps(results, indent=2) + '\n') + if a.scenario == 'pressure': + print(pressure_budget_hint(results, a.cache_mib), flush=True) if a.scenario == 'admission': verify_admission(results, a.cache_mib, a.min_free_mib) print('PASS: physical-memory admission denial, output and byte-exact main-model state') diff --git a/tools/test_conversation_cache_growth.py b/tools/test_conversation_cache_growth.py new file mode 100644 index 00000000..73b3d336 --- /dev/null +++ b/tools/test_conversation_cache_growth.py @@ -0,0 +1,77 @@ +"""Negative controls for the incremental capture model gate.""" +import copy +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +from tools.conversation_cache_growth import NAMES, SECRET, SETTINGS, STATE_KEYS, verify + + +def fixture(): + lengths = [8, 2, 12, 2, 16, 2, 20, 2, 12, 2, 15, 2] + requests = [dict(name=name, ids=[1]*n, max_new=16, expected=name.startswith('A-')) + for name, n in zip(NAMES, lengths)] + digest = hashlib.sha256(json.dumps(requests, sort_keys=True).encode()).hexdigest() + full = dict(name='full', args=['--conversation-cache-mib','1'], request_digest=digest, + info={key: 1 for key in SETTINGS}, draft_verifications=4, + parks=[dict(bytes=100,snapshot_bytes=100,reused_kv_bytes=0) for _ in range(3)], + records=[dict(name=name, ids=[1], text=SECRET, finish='stop', reused=1, + prompt_tokens=n, state={k:'abc' for k in STATE_KEYS}) for name,n in zip(NAMES,lengths)]) + full['info'].update(conversation_cache_mib=1,conversation_cache_slots=4) + incremental = copy.deepcopy(full) + incremental['name'] = 'incremental' + for p in incremental['parks']: + p['reused_kv_bytes'] = 50 + return dict(arms=[full,incremental],requests=requests,request_digest=digest) + + +class GrowthGate(unittest.TestCase): + def test_complete_evidence(self): + verify(fixture()) + + def test_incomplete_or_incorrect_evidence_fails(self): + mutations = [ + lambda r:r['requests'].pop(), + lambda r:r['requests'][0]['ids'].append(2), + lambda r:r['arms'][1]['records'].pop(), + lambda r:r['arms'][1]['records'][2].update(ids=[2]), + lambda r:r['arms'][1]['records'][2].update(text='wrong'), + lambda r:r['arms'][1]['records'][2].update(reused=0), + lambda r:r['arms'][1]['records'][2].update(finish='cancel'), + lambda r:r['arms'][1]['records'][2]['state'].pop('kv'), + lambda r:r['arms'][1]['info'].update(expert_slots=2), + lambda r:r['arms'][1].update(draft_verifications=0), + lambda r:r['arms'][0]['parks'][0].update(reused_kv_bytes=1), + lambda r:[p.update(reused_kv_bytes=0) for p in r['arms'][1]['parks']], + lambda r:r['arms'][1]['parks'][0].update(bytes=2*1024*1024), + lambda r:r['arms'][1]['parks'][0].update(reused_kv_bytes=101), + ] + for i, mutate in enumerate(mutations): + with self.subTest(case=i): + result = fixture() + mutate(result) + with self.assertRaises(AssertionError): + verify(result) + + def test_optimized_python_rejects_missing_reuse(self): + code = ('from tools.test_conversation_cache_growth import fixture,verify; ' + 'r=fixture(); [p.update(reused_kv_bytes=0) for p in r["arms"][1]["parks"]]; verify(r)') + run = subprocess.run([sys.executable,'-O','-c',code],capture_output=True,text=True) + self.assertNotEqual(run.returncode,0) + self.assertIn('did not reuse KV bytes',run.stderr) + + def test_dry_run_leaves_server_and_output_alone(self): + with tempfile.TemporaryDirectory() as tmp: + output = Path(tmp)/'absent' + run = subprocess.run([sys.executable,'tools/conversation_cache_growth.py','--config','/absent', + '--engine','/absent','--output',str(output)],capture_output=True,text=True) + self.assertEqual(run.returncode,0,run.stderr) + self.assertFalse(output.exists()) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/test_conversation_cache_parity.py b/tools/test_conversation_cache_parity.py index 15c9cc40..3f950ebd 100644 --- a/tools/test_conversation_cache_parity.py +++ b/tools/test_conversation_cache_parity.py @@ -6,7 +6,7 @@ import sys import tempfile import unittest -from tools.conversation_cache_parity import STATE_KEYS, engine_args, verify_admission, verify_exchange, verify_pressure, verify_results +from tools.conversation_cache_parity import STATE_KEYS, engine_args, pressure_budget_hint, verify_admission, verify_exchange, verify_pressure, verify_results def fixture(): @@ -89,6 +89,22 @@ def pressure_fixture(): class PressureGate(unittest.TestCase): + def test_pressure_budget_hint_uses_individual_sizes(self): + data = pressure_fixture() + for park in data['pressure']['parks']: + park['snapshot_bytes'] = 266 * 1024 * 1024 + self.assertIn('--cache-mib 266..531', pressure_budget_hint(data, 600)) + data['candidate'][-1]['reused'] = 100 + with self.assertRaisesRegex(AssertionError, r'Configured --cache-mib 600.*266\.00 MiB.*266\.\.531'): + verify_pressure(data, 600) + + def test_pressure_budget_hint_handles_missing_or_incompatible_sizes(self): + data = pressure_fixture() + self.assertIn('No snapshot sizes', pressure_budget_hint(data, 600)) + for park, size in zip(data['pressure']['parks'], [1, 2, 10]): + park['snapshot_bytes'] = size * 1024 * 1024 + self.assertIn('No whole-MiB budget', pressure_budget_hint(data, 600)) + def test_physical_memory_admission_evidence(self): data = pressure_fixture() data['pressure'] = {'memory_skips': 3, 'skips': 0, 'parks': []}