mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-04 23:38:47 +00:00
conversation cache: the SSD tier writes in the background (#5697, P2 step 2c)
Step 2c of P2 in the cache admission design. In 2b (69857af16) a conversation the RAM tier evicted was
written to the SSD tier inside the request that evicted it (about 290-430 ms for a 16-32K conversation),
so the median switch at 4 sessions was slower than without the tier.
- BackgroundWriter (conversation_spill.hpp): one thread writes evicted conversations. One write is in
flight and one waits; a third push waits. Written images are handed back (take_done) and freed or
reused on the serve thread, which owns the cache's allocators; the writer never frees one. The
destructor finishes the write in flight and drops what is queued (the namespace ends with the
process). The thread runs at a lower priority: on Linux nice +10 and the lowest best-effort I/O level
(not the idle class, which steady expert reads could starve), on Windows below normal.
- RAM stays counted: a conversation the writer holds is still allocated, so the physical-RAM gate sees
it, and the RAM tier's byte budget is exceeded by at most the two images the writer holds. The RAM
gate's own evictions wait for the writer and free its result, so the memory reading moves.
- Taken back without a read: a request whose prompt a conversation the writer still holds serves best
takes it from RAM (waiting for that one write if it is in flight) and drops its SSD copy. In the
replays: "took 16587 tokens back from the SSD writer, still in RAM, in 0.1 ms".
- The rest of what the writer finished is freed before each park (spill_reclaim). #879 clears the
writer with the tiers. The capture the RAM floor refuses (entry c) is still written at once.
- ConversationSpill is thread-safe: one lock for the list and the budget; files are written and read
outside it; entries are reached by serial (find, take_serial, drop_serial), since an index can shift
while the writer drops the oldest; entry() returns a copy. conversation_image_prefix gives the prefix
a held image offers a prompt, by the RAM cache's rule. The cost rule's measurements are under a mutex.
Tests:
- conversation_spill_test 74 checks: the writer's order, its push limit, take_done serials (0 for a
failed write), take_queued, the destructor, a SavedConversation through the real tier while the
serve thread matches, the serial API, conversation_image_prefix. ThreadSanitizer: 0 reports
(l620-20261116-1728-93df). p2003 (RTX 3060, CUDA 13, sm_86 + sm_120): the whole conversation test
set, the cache test and the #6059 probe pass, generate.cpp warnings 4 = head (p2003-20261116-1746-c748).
- The release gate for the default (coordinator: 2b + 2c together), replay v6 on l620 (RTX PRO 5000,
IQ3_S, the shared BASE-05 setup), l620-20261116-1755-4c56: tokens compared strictly against a run with
a RAM tier that keeps everything (a request counts when its session had the same reuse and replies
at every earlier turn): equal in all four sets. Wall time per switch, ms, with / without the tier
(4 sessions: 3 runs of each pooled):
short 4: p50 415 / 427, p95 744 / 1,864, sum 10,947 / 15,102
long 4: p50 408 / 415, p95 818 / 3,336, sum 12,833 / 19,648
short 8: p50 589 / 607, p95 797 / 1,886, sum 9,617 / 13,857
long 8: p50 839 / 2,620, p95 1,035 / 6,079, sum 13,492 / 48,503
short = 2K / 8K / short chats, long = 2K / 8K / 16K / 32K contexts in turn.
This commit is contained in:
1 parent
69857af168
commit
64dde763c6
4 files changed
+460
-76
No files matched your search
@@ -238,6 +238,7 @@ if(STRATA_BUILD_CONVERSATION_TESTS)
|
||||
add_executable(conversation_spill_test src/core/conversation_spill_test.cpp src/core/conversation_file.cpp)
|
||||
target_include_directories(conversation_spill_test PRIVATE include)
|
||||
target_compile_features(conversation_spill_test PRIVATE cxx_std_17)
|
||||
target_link_libraries(conversation_spill_test PRIVATE Threads::Threads) # (P2 step 2c: the background writer)
|
||||
add_test(NAME conversation_spill_test COMMAND conversation_spill_test)
|
||||
# #6052: the periodic conversation checkpoints (--prompt-cache-every) on the resumed request's grid (header-only)
|
||||
add_executable(prompt_checkpoint_grid_test src/core/prompt_checkpoint_grid_test.cpp)
|
||||
|
||||
@@ -16,7 +16,14 @@
|
||||
#include "strata/core/conversation_cache.hpp"
|
||||
#include "strata/core/conversation_file.hpp"
|
||||
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
#include <random>
|
||||
@@ -34,6 +41,10 @@
|
||||
#include <fcntl.h>
|
||||
#include <sys/file.h>
|
||||
#include <unistd.h>
|
||||
#if defined(__linux__)
|
||||
#include <sys/resource.h>
|
||||
#include <sys/syscall.h>
|
||||
#endif
|
||||
#endif
|
||||
|
||||
namespace strata::core {
|
||||
@@ -94,6 +105,19 @@ inline LockHandle try_lock(const std::filesystem::path& p) {
|
||||
inline void unlock(LockHandle fd) { if (fd >= 0) ::close(fd); }
|
||||
inline unsigned long own_pid() { return (unsigned long) ::getpid(); }
|
||||
#endif
|
||||
/// The calling thread gives way (the SSD tier's background writer, P2 step 2c): on Linux nice +10 and the lowest best-effort I/O
|
||||
/// level (not the idle class, which a steady stream of expert reads could starve - and a starved writer would hold the serve loop
|
||||
/// at its next push); on Windows a below-normal thread priority; elsewhere nothing. Best effort: a refusal changes nothing.
|
||||
inline void lower_thread_priority() {
|
||||
#if defined(_WIN32)
|
||||
(void) SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
|
||||
#elif defined(__linux__)
|
||||
const long tid = ::syscall(SYS_gettid);
|
||||
(void) ::setpriority(PRIO_PROCESS, (id_t) tid, 10);
|
||||
constexpr int kWhoProcess = 1, kClassBestEffort = 2, kLowest = 7, kClassShift = 13;
|
||||
(void) ::syscall(SYS_ioprio_set, kWhoProcess, (int) tid, (kClassBestEffort << kClassShift) | kLowest);
|
||||
#endif
|
||||
}
|
||||
} // namespace spill_detail
|
||||
|
||||
/// Whether a conversation is worth writing to the SSD tier: reading it back (and writing it first) must cost less than reading its
|
||||
@@ -199,6 +223,9 @@ private:
|
||||
/// checkpoint (no running state, no K/V). put() deletes the oldest entries when the budget needs the room, and never
|
||||
/// leaves a partial file behind; take() reads an entry back under the caller's read limits and removes it either way (a
|
||||
/// file that does not read back is not tried again).
|
||||
/// Thread-safe (P2 step 2c: a background writer puts while the serve loop matches and takes): the entry list and the budget are
|
||||
/// under one lock, a file is written and read outside it, and an entry is reached by its serial (an index can shift when the
|
||||
/// writer drops the oldest). An entry is listed only once its file is complete.
|
||||
class ConversationSpill {
|
||||
public:
|
||||
struct Entry {
|
||||
@@ -211,50 +238,68 @@ public:
|
||||
};
|
||||
|
||||
bool open(const std::filesystem::path& root, uint64_t cap, std::string& error, size_t* cleaned = nullptr) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
entries_.clear();
|
||||
budget_ = SpillBudget{cap, 0, 0};
|
||||
return ns_.open(root, error, cleaned);
|
||||
}
|
||||
bool enabled() const { return ns_.is_open() && budget_.cap > 0; }
|
||||
size_t size() const { return entries_.size(); }
|
||||
uint64_t bytes() const { return budget_.used; }
|
||||
const SpillBudget& budget() const { return budget_; }
|
||||
const Entry& entry(size_t i) const { return entries_.at(i); }
|
||||
const std::filesystem::path& dir() const { return ns_.dir(); }
|
||||
bool enabled() const { std::lock_guard<std::mutex> lk(mu_); return enabled_locked(); }
|
||||
size_t size() const { std::lock_guard<std::mutex> lk(mu_); return entries_.size(); }
|
||||
uint64_t bytes() const { std::lock_guard<std::mutex> lk(mu_); return budget_.used; }
|
||||
SpillBudget budget() const { std::lock_guard<std::mutex> lk(mu_); return budget_; }
|
||||
Entry entry(size_t i) const { std::lock_guard<std::mutex> lk(mu_); return entries_.at(i); }
|
||||
/// the entry `serial` (a copy), if it is still listed
|
||||
std::optional<Entry> find(uint64_t serial) const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
const size_t i = index_locked(serial);
|
||||
return i == SIZE_MAX ? std::nullopt : std::optional<Entry>(entries_[i]);
|
||||
}
|
||||
std::filesystem::path dir() const { std::lock_guard<std::mutex> lk(mu_); return ns_.dir(); }
|
||||
|
||||
/// Writes `image` as an entry. False (with `error`) when the tier is off, the image is larger than the whole tier, or the
|
||||
/// write failed; nothing of this call is then left on the disk.
|
||||
bool put(const SavedConversation& image, const SessionFileIdentity& id, std::string& error) {
|
||||
if (!enabled()) { error = "the SSD tier is off"; return false; }
|
||||
/// Writes `image` as an entry (its serial in `*serial_out`). False (with `error`) when the tier is off, the image is larger
|
||||
/// than the whole tier, or the write failed; nothing of this call is then left on the disk. The file is written outside the
|
||||
/// lock, under a budget reserved for it.
|
||||
bool put(const SavedConversation& image, const SessionFileIdentity& id, std::string& error, uint64_t* serial_out = nullptr) {
|
||||
const uint64_t need = (uint64_t) image.bytes() + (uint64_t(1) << 20); // the payload and the file's own tables
|
||||
if (need > budget_.cap) { error = "larger than the whole SSD tier"; return false; }
|
||||
while (!budget_.reserve(need)) {
|
||||
if (entries_.empty()) { error = "no room in the SSD tier"; return false; }
|
||||
drop(0);
|
||||
uint64_t serial = 0;
|
||||
std::filesystem::path f;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (!enabled_locked()) { error = "the SSD tier is off"; return false; }
|
||||
if (need > budget_.cap) { error = "larger than the whole SSD tier"; return false; }
|
||||
while (!budget_.reserve(need)) {
|
||||
if (entries_.empty()) { error = "no room in the SSD tier"; return false; }
|
||||
drop_locked(0);
|
||||
}
|
||||
serial = next_serial_++;
|
||||
f = ns_.file_for(serial);
|
||||
}
|
||||
const uint64_t serial = next_serial_++;
|
||||
const std::filesystem::path f = ns_.file_for(serial);
|
||||
size_t written = 0;
|
||||
const bool ok = session_file_write(f.string(), image, id, written, error);
|
||||
budget_.finish(need, ok ? written : 0);
|
||||
if (!ok) {
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(f, ec);
|
||||
return false;
|
||||
}
|
||||
Entry e;
|
||||
e.serial = serial; e.file = f; e.bytes = written; e.cvec = image.cvec;
|
||||
e.live = stub(image.live);
|
||||
for (const auto& c : image.checkpoints) e.checkpoints.push_back(stub(c));
|
||||
if (ok) {
|
||||
e.serial = serial; e.file = f; e.bytes = written; e.cvec = image.cvec;
|
||||
e.live = stub(image.live);
|
||||
for (const auto& c : image.checkpoints) e.checkpoints.push_back(stub(c));
|
||||
}
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
budget_.finish(need, ok ? written : 0);
|
||||
if (!ok) return false;
|
||||
entries_.push_back(std::move(e));
|
||||
while (budget_.over() && entries_.size() > 1) drop(0); // (a file larger than its estimate)
|
||||
while (budget_.over() && entries_.size() > 1) drop_locked(0); // (a file larger than its estimate)
|
||||
if (serial_out) *serial_out = serial;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// The entry and the prefix it gives `prompt`, by the RAM cache's rule (ConversationCache::best): its live state or a
|
||||
/// checkpoint, same pictures, same steering; ties prefer the newest.
|
||||
/// checkpoint, same pictures, same steering; ties prefer the newest. Reach it by `serial` (find / take_serial).
|
||||
template <class Token>
|
||||
ConversationCache::Match best(const std::vector<Token>& prompt, const std::vector<ConversationImageKey>& images, bool cvec) const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
ConversationCache::Match m;
|
||||
for (size_t i = entries_.size(); i-- > 0;) {
|
||||
const Entry& e = entries_[i];
|
||||
@@ -269,46 +314,195 @@ public:
|
||||
return m;
|
||||
}
|
||||
|
||||
/// Reads entry `i` back into `out` (bounded by `limits`, the identity checked) and removes the entry. False: `out` is
|
||||
/// unchanged and the entry is gone.
|
||||
bool take(size_t i, const SessionFileIdentity& id, const SessionReadLimits& limits, SavedConversation& out, std::string& error) {
|
||||
if (i >= entries_.size()) { error = "no such SSD entry"; return false; }
|
||||
/// Reads entry `serial` back into `out` (bounded by `limits`, the identity checked) and removes the entry. False: `out` is
|
||||
/// unchanged and the entry is gone (or was not there). The file is read outside the lock: the entry leaves the list first.
|
||||
bool take_serial(uint64_t serial, const SessionFileIdentity& id, const SessionReadLimits& limits, SavedConversation& out,
|
||||
std::string& error) {
|
||||
std::filesystem::path f;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
const size_t i = index_locked(serial);
|
||||
if (i == SIZE_MAX) { error = "no such SSD entry"; return false; }
|
||||
f = entries_[i].file;
|
||||
budget_.drop(entries_[i].bytes);
|
||||
entries_.erase(entries_.begin() + (std::ptrdiff_t) i);
|
||||
}
|
||||
SavedConversation image;
|
||||
size_t read = 0;
|
||||
const bool ok = session_file_read(entries_[i].file.string(), id, image, read, error, limits);
|
||||
drop(i);
|
||||
const bool ok = session_file_read(f.string(), id, image, read, error, limits);
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(f, ec);
|
||||
if (ok) out = std::move(image);
|
||||
return ok;
|
||||
}
|
||||
bool take(size_t i, const SessionFileIdentity& id, const SessionReadLimits& limits, SavedConversation& out, std::string& error) {
|
||||
uint64_t serial = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (i >= entries_.size()) { error = "no such SSD entry"; return false; }
|
||||
serial = entries_[i].serial;
|
||||
}
|
||||
return take_serial(serial, id, limits, out, error);
|
||||
}
|
||||
|
||||
void drop(size_t i) {
|
||||
void drop(size_t i) { std::lock_guard<std::mutex> lk(mu_); drop_locked(i); }
|
||||
/// Drops entry `serial` and its file; false when it was not listed.
|
||||
bool drop_serial(uint64_t serial) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
const size_t i = index_locked(serial);
|
||||
if (i == SIZE_MAX) return false;
|
||||
drop_locked(i);
|
||||
return true;
|
||||
}
|
||||
/// Drops every entry and keeps the tier open (#879: after non-finite logits no parked conversation is kept). Returns how many.
|
||||
size_t clear() {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
const size_t n = entries_.size();
|
||||
while (!entries_.empty()) drop_locked(entries_.size() - 1);
|
||||
return n;
|
||||
}
|
||||
void close() {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
while (!entries_.empty()) drop_locked(entries_.size() - 1);
|
||||
ns_.close();
|
||||
}
|
||||
|
||||
private:
|
||||
bool enabled_locked() const { return ns_.is_open() && budget_.cap > 0; }
|
||||
size_t index_locked(uint64_t serial) const {
|
||||
for (size_t i = 0; i < entries_.size(); ++i)
|
||||
if (entries_[i].serial == serial) return i;
|
||||
return SIZE_MAX;
|
||||
}
|
||||
void drop_locked(size_t i) {
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(entries_.at(i).file, ec);
|
||||
budget_.drop(entries_[i].bytes);
|
||||
entries_.erase(entries_.begin() + (std::ptrdiff_t) i);
|
||||
}
|
||||
/// Drops every entry and keeps the tier open (#879: after non-finite logits no parked conversation is kept). Returns how many.
|
||||
size_t clear() {
|
||||
const size_t n = entries_.size();
|
||||
while (!entries_.empty()) drop(entries_.size() - 1);
|
||||
return n;
|
||||
}
|
||||
void close() {
|
||||
clear();
|
||||
ns_.close();
|
||||
}
|
||||
|
||||
private:
|
||||
static ConversationCheckpoint stub(const ConversationCheckpoint& c) {
|
||||
ConversationCheckpoint s;
|
||||
s.ids = c.ids;
|
||||
s.imgs = c.imgs;
|
||||
return s;
|
||||
}
|
||||
mutable std::mutex mu_;
|
||||
SpillNamespace ns_;
|
||||
SpillBudget budget_;
|
||||
std::vector<Entry> entries_;
|
||||
uint64_t next_serial_ = 1;
|
||||
};
|
||||
|
||||
/// The best prefix a parked image gives `prompt`, by the RAM cache's rule (its live state or a checkpoint, same pictures, same
|
||||
/// steering): for the images the background writer still holds in RAM. {tokens, live}; tokens 0 = none.
|
||||
template <class Token>
|
||||
std::pair<int64_t, bool> conversation_image_prefix(const SavedConversation& s, const std::vector<Token>& prompt,
|
||||
const std::vector<ConversationImageKey>& images, bool cvec) {
|
||||
std::pair<int64_t, bool> m{0, false};
|
||||
if (s.cvec != cvec) return m;
|
||||
const int64_t l = conversation_prefix(s.live, prompt, images);
|
||||
if (l > m.first) m = {l, true};
|
||||
for (const auto& c : s.checkpoints) {
|
||||
const int64_t n = conversation_prefix(c, prompt, images);
|
||||
if (n > m.first) m = {n, false};
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
/// P2 step 2c: writes parked conversations to the SSD tier on its own thread, so a request's park does not wait for the disk.
|
||||
/// At most one image is written at a time and one waits behind it (push() blocks past that): what the writer holds in RAM is at
|
||||
/// most two images over the RAM tier's budget, and the physical-RAM gate sees it (it is still allocated). A written image is not
|
||||
/// freed on the writer thread: it is handed back (take_done) to be freed - or reused, it is still in RAM - on the caller's
|
||||
/// thread, the one that owns the cache's allocators. `write` runs on the writer thread and returns the SSD serial (0: failed).
|
||||
template <class Item>
|
||||
class BackgroundWriter {
|
||||
public:
|
||||
struct Done {
|
||||
Item item;
|
||||
uint64_t serial = 0; // its SSD entry; 0: the write failed (the image is all there is)
|
||||
};
|
||||
/// `on_start`: runs first on the writer thread (the serve loop lowers its priority there: spill_detail::lower_thread_priority)
|
||||
explicit BackgroundWriter(std::function<uint64_t(const Item&)> write, std::function<void()> on_start = {})
|
||||
: write_(std::move(write)), on_start_(std::move(on_start)), th_([this] { if (on_start_) on_start_(); run(); }) {}
|
||||
BackgroundWriter(const BackgroundWriter&) = delete;
|
||||
BackgroundWriter& operator=(const BackgroundWriter&) = delete;
|
||||
/// what is queued is not written (the namespace goes with the process); a write in flight finishes first
|
||||
~BackgroundWriter() {
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
stop_ = true;
|
||||
queue_.clear();
|
||||
}
|
||||
cv_.notify_all();
|
||||
th_.join();
|
||||
}
|
||||
void push(Item&& it) {
|
||||
std::unique_lock<std::mutex> lk(mu_);
|
||||
cv_.wait(lk, [&] { return queue_.empty() || stop_; });
|
||||
if (stop_) return;
|
||||
queue_.push_back(std::move(it));
|
||||
cv_.notify_all();
|
||||
}
|
||||
void wait_idle() {
|
||||
std::unique_lock<std::mutex> lk(mu_);
|
||||
cv_.wait(lk, [&] { return (queue_.empty() && !busy_) || stop_; });
|
||||
}
|
||||
bool idle() const { std::lock_guard<std::mutex> lk(mu_); return queue_.empty() && !busy_; }
|
||||
/// the written ones, to free or reuse on this thread
|
||||
std::vector<Done> take_done() {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
std::vector<Done> out;
|
||||
out.swap(done_);
|
||||
return out;
|
||||
}
|
||||
/// the queued ones (not the one in flight) back, unwritten - #879 clears them with the cache
|
||||
std::vector<Item> take_queued() {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
std::vector<Item> out;
|
||||
for (auto& q : queue_) out.push_back(std::move(q));
|
||||
queue_.clear();
|
||||
cv_.notify_all();
|
||||
return out;
|
||||
}
|
||||
/// f(const Item&) over every image not yet handed back - queued, in flight, written - under the lock (the writer only
|
||||
/// reads an image in flight, so reading it here as well is safe)
|
||||
template <class F>
|
||||
void for_each_held(F f) const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
for (const auto& q : queue_) f(q);
|
||||
if (inflight_) f(*inflight_);
|
||||
for (const auto& d : done_) f(d.item);
|
||||
}
|
||||
|
||||
private:
|
||||
void run() {
|
||||
std::unique_lock<std::mutex> lk(mu_);
|
||||
for (;;) {
|
||||
cv_.wait(lk, [&] { return stop_ || !queue_.empty(); });
|
||||
if (stop_) return;
|
||||
inflight_.emplace(std::move(queue_.front()));
|
||||
queue_.pop_front();
|
||||
busy_ = true;
|
||||
cv_.notify_all(); // (a push waiting for room)
|
||||
lk.unlock();
|
||||
uint64_t serial = 0;
|
||||
try { serial = write_(*inflight_); } catch (...) { serial = 0; }
|
||||
lk.lock();
|
||||
done_.push_back(Done{std::move(*inflight_), serial});
|
||||
inflight_.reset();
|
||||
busy_ = false;
|
||||
cv_.notify_all();
|
||||
}
|
||||
}
|
||||
std::function<uint64_t(const Item&)> write_;
|
||||
std::function<void()> on_start_;
|
||||
mutable std::mutex mu_;
|
||||
std::condition_variable cv_;
|
||||
std::deque<Item> queue_;
|
||||
std::optional<Item> inflight_;
|
||||
std::vector<Done> done_;
|
||||
bool busy_ = false, stop_ = false;
|
||||
std::thread th_; // (last: it starts once the rest exists)
|
||||
};
|
||||
|
||||
} // namespace strata::core
|
||||
@@ -1,7 +1,12 @@
|
||||
// The conversation cache's SSD tier: its folder per engine process and its budget (conversation_spill.hpp). No GPU, no model.
|
||||
#include "strata/core/conversation_spill.hpp"
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <cstdio>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
@@ -169,6 +174,99 @@ int main() {
|
||||
check(slow.worth(2000, 264000000), "on a slower card a 2K conversation is worth the disk");
|
||||
check(!c.worth(0, 1) && !slow.worth(0, 1), "an empty conversation never is");
|
||||
}
|
||||
{ // 2c: the background writer
|
||||
using namespace std::chrono_literals;
|
||||
struct Gate { // holds the writer inside a write until opened
|
||||
std::mutex mu; std::condition_variable cv; bool open = false; int entered = 0;
|
||||
void enter() { std::unique_lock<std::mutex> lk(mu); ++entered; cv.notify_all(); cv.wait(lk, [&] { return open; }); }
|
||||
void release() { { std::lock_guard<std::mutex> lk(mu); open = true; } cv.notify_all(); }
|
||||
void wait_entered(int n) { std::unique_lock<std::mutex> lk(mu); cv.wait_for(lk, 5s, [&] { return entered >= n; }); }
|
||||
};
|
||||
Gate gate;
|
||||
std::vector<int> order;
|
||||
std::mutex order_mu;
|
||||
{
|
||||
BackgroundWriter<int> w([&](const int& v) -> uint64_t {
|
||||
gate.enter();
|
||||
std::lock_guard<std::mutex> lk(order_mu);
|
||||
order.push_back(v);
|
||||
return v == 3 ? 0 : (uint64_t) v * 10; // item 3: a failed write
|
||||
});
|
||||
w.push(1);
|
||||
gate.wait_entered(1);
|
||||
w.push(2); // one waits behind the one in flight
|
||||
std::atomic<bool> third_in{false};
|
||||
std::thread t([&] { w.push(3); third_in = true; });
|
||||
std::this_thread::sleep_for(150ms);
|
||||
check(!third_in.load(), "a third push waits while one is in flight and one is queued");
|
||||
int held = 0;
|
||||
w.for_each_held([&](const int&) { ++held; });
|
||||
check(held == 2 && !w.idle(), "the queued one and the one in flight are held");
|
||||
gate.release();
|
||||
t.join();
|
||||
w.wait_idle();
|
||||
check(third_in.load() && w.idle(), "the queue drains");
|
||||
auto done = w.take_done();
|
||||
check(done.size() == 3 && done[0].item == 1 && done[0].serial == 10 && done[1].item == 2 && done[1].serial == 20 &&
|
||||
done[2].item == 3 && done[2].serial == 0, "written in order, each handed back with its serial (0: failed)");
|
||||
check(order == std::vector<int>({1, 2, 3}) && w.take_done().empty(), "handed back once");
|
||||
}
|
||||
Gate g2;
|
||||
std::vector<int> written;
|
||||
{
|
||||
BackgroundWriter<int> w([&](const int& v) -> uint64_t { g2.enter(); written.push_back(v); return 1; });
|
||||
w.push(7);
|
||||
g2.wait_entered(1);
|
||||
w.push(8);
|
||||
auto queued = w.take_queued();
|
||||
check(queued.size() == 1 && queued[0] == 8, "take_queued gives the queued one back unwritten");
|
||||
w.push(9); // and the writer takes more after it
|
||||
g2.release();
|
||||
} // the destructor: 7 finishes, 9 is not written (queued at the end)
|
||||
check(written == std::vector<int>({7}) || written == std::vector<int>({7, 9}),
|
||||
"the destructor finishes the write in flight and does not hang");
|
||||
// a SavedConversation through the real SSD tier, while the serve thread matches and takes by serial
|
||||
auto img = [](std::vector<int32_t> ids, uint8_t fill) {
|
||||
SavedConversation s;
|
||||
s.live.ids = ids;
|
||||
s.live.gdn.assign(1 << 18, fill);
|
||||
s.cvec = true;
|
||||
return s;
|
||||
};
|
||||
const SessionFileIdentity id{31, 41};
|
||||
ConversationSpill sp;
|
||||
std::string err;
|
||||
check(sp.open(root, uint64_t(64) << 20, err), "a tier for the writer");
|
||||
{
|
||||
BackgroundWriter<SavedConversation> w([&](const SavedConversation& s) -> uint64_t {
|
||||
uint64_t serial = 0;
|
||||
std::string e;
|
||||
return sp.put(s, id, e, &serial) ? serial : 0;
|
||||
});
|
||||
for (int k = 0; k < 6; ++k) w.push(img({k, k + 1, k + 2}, (uint8_t) k));
|
||||
for (int k = 0; k < 200; ++k) { // the serve thread matching while the writer puts
|
||||
const auto m = sp.best(std::vector<int32_t>{2, 3, 4, 9}, {}, true);
|
||||
if (m.tokens > 0) (void) sp.find(m.serial); // (may be gone or not yet listed: it must only not crash or race)
|
||||
}
|
||||
w.wait_idle();
|
||||
auto done = w.take_done();
|
||||
check(done.size() == 6 && sp.size() == 6, "six written, six listed");
|
||||
const auto m = sp.best(std::vector<int32_t>{2, 3, 4, 9}, {}, true);
|
||||
check(m.tokens == 3, "the entry a prompt continues is found");
|
||||
const auto e = sp.find(m.serial);
|
||||
check(e && e->live.ids == std::vector<int32_t>({2, 3, 4}), "found by its serial");
|
||||
SavedConversation back;
|
||||
check(sp.take_serial(m.serial, id, {}, back, err) && back.live.gdn == std::vector<uint8_t>(1 << 18, 2) &&
|
||||
!sp.find(m.serial) && sp.size() == 5, "taken by its serial, byte for byte; it leaves the list");
|
||||
check(!sp.take_serial(m.serial, id, {}, back, err) && !sp.drop_serial(m.serial), "a gone serial: nothing");
|
||||
check(sp.drop_serial(done[0].serial) && sp.size() == 4, "dropped by its serial");
|
||||
// a written image still in RAM: the prefix it gives, by the RAM cache's rule
|
||||
const auto p = conversation_image_prefix(done[5].item, std::vector<int32_t>{5, 6, 7, 1}, {}, true);
|
||||
check(p.first == 3 && p.second, "a held image's live prefix");
|
||||
check(conversation_image_prefix(done[5].item, std::vector<int32_t>{5, 6, 7}, {}, false).first == 0, "other steering: none");
|
||||
}
|
||||
sp.close();
|
||||
}
|
||||
fs::remove_all(root, ec);
|
||||
std::printf("conversation_spill_test: %d checks, %d failed\n", checks, failures);
|
||||
return failures == 0 ? 0 : 1;
|
||||
|
||||
+125
-34
@@ -13191,21 +13191,26 @@ int main(int argc, char** argv) {
|
||||
std::fprintf(stderr, "strata serve: conversation cache: no SSD tier: %s\n", why.c_str());
|
||||
}
|
||||
}
|
||||
// writes one parked conversation to the SSD tier; false: it stays where it was (or is dropped, for a victim). Never throws.
|
||||
auto spill_put = [&](const strata::core::SavedConversation& img, const char* why) -> bool {
|
||||
std::mutex spill_cost_mu; // (the background writer measures writes while the serve loop asks the rule)
|
||||
// On the serve thread: whether `img` goes to the SSD tier at all - the tier is on, one stage, the cost rule says it pays -
|
||||
// and the model's identity is known (it is fingerprinted once, here, never on the writer thread).
|
||||
auto spill_ready = [&](const strata::core::SavedConversation& img, const char* why) -> bool {
|
||||
if (!spill.enabled() || !img.stage_images.empty()) return false;
|
||||
const int64_t tokens = (int64_t) img.live.ids.size();
|
||||
const uint64_t bytes = (uint64_t) img.bytes();
|
||||
if (!spill_cost.worth(tokens, bytes)) {
|
||||
std::fprintf(stderr, "strata serve: conversation cache: not spilling %lld tokens (%s): reading them again "
|
||||
"(about %.0f ms here) costs less than the SSD round trip of %llu MiB (about %.0f ms)\n",
|
||||
(long long) tokens, why, spill_cost.reread_ms(tokens), (unsigned long long) (bytes >> 20),
|
||||
spill_cost.round_trip_ms(bytes));
|
||||
return false;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(spill_cost_mu);
|
||||
if (!spill_cost.worth(tokens, bytes)) {
|
||||
std::fprintf(stderr, "strata serve: conversation cache: not spilling %lld tokens (%s): reading them again "
|
||||
"(about %.0f ms here) costs less than the SSD round trip of %llu MiB (about %.0f ms)\n",
|
||||
(long long) tokens, why, spill_cost.reread_ms(tokens), (unsigned long long) (bytes >> 20),
|
||||
spill_cost.round_trip_ms(bytes));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
try {
|
||||
std::string e;
|
||||
if (!spill_id) {
|
||||
if (!spill_id) {
|
||||
try {
|
||||
std::string e;
|
||||
strata::core::SessionFileIdentity id;
|
||||
if (!session_identity(id, e, {})) {
|
||||
std::fprintf(stderr, "strata serve: conversation cache: no SSD tier from now on: the model cannot be "
|
||||
@@ -13214,27 +13219,73 @@ int main(int argc, char** argv) {
|
||||
return false;
|
||||
}
|
||||
spill_id = id;
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
// Writes one parked conversation to the SSD tier (on either thread, once spill_ready said yes); its SSD serial, 0 when it
|
||||
// could not be written. Never throws.
|
||||
auto spill_write = [&](const strata::core::SavedConversation& img, const char* why) -> uint64_t {
|
||||
try {
|
||||
std::string e;
|
||||
uint64_t serial = 0;
|
||||
const auto t0 = Clock::now();
|
||||
const bool ok = spill.put(img, *spill_id, e);
|
||||
if (ok) spill_cost.saw_write(spill.entry(spill.size() - 1).bytes,
|
||||
std::chrono::duration<double, std::milli>(Clock::now() - t0).count());
|
||||
if (ok)
|
||||
const bool ok = spill_id && spill.put(img, *spill_id, e, &serial);
|
||||
const double ms = std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
|
||||
if (ok) {
|
||||
if (const auto en = spill.find(serial)) {
|
||||
std::lock_guard<std::mutex> lk(spill_cost_mu);
|
||||
spill_cost.saw_write(en->bytes, ms);
|
||||
}
|
||||
std::fprintf(stderr, "strata serve: conversation cache: spilled %zu tokens to the SSD tier (%s) in %.1f ms; "
|
||||
"on SSD %zu, %llu MiB\n", img.live.ids.size(), why,
|
||||
std::chrono::duration<double, std::milli>(Clock::now() - t0).count(), spill.size(),
|
||||
"on SSD %zu, %llu MiB\n", img.live.ids.size(), why, ms, spill.size(),
|
||||
(unsigned long long) (spill.bytes() >> 20));
|
||||
else
|
||||
} else {
|
||||
std::fprintf(stderr, "strata serve: conversation cache: could not spill %zu tokens to the SSD tier (%s): %s\n",
|
||||
img.live.ids.size(), why, e.c_str());
|
||||
return ok;
|
||||
}
|
||||
return ok ? serial : 0;
|
||||
} catch (...) {
|
||||
std::fprintf(stderr, "strata serve: conversation cache: could not spill to the SSD tier (%s): out of memory\n", why);
|
||||
return false;
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
if (spill.enabled())
|
||||
conversations.set_evict_sink([&](strata::core::SavedConversation&& v) { spill_put(v, "evicted from RAM"); });
|
||||
// writes it now, on this thread (the RAM floor after a capture needs the memory back at once)
|
||||
auto spill_put = [&](const strata::core::SavedConversation& img, const char* why) -> bool {
|
||||
return spill_ready(img, why) && spill_write(img, why) != 0;
|
||||
};
|
||||
// P2 step 2c: an evicted conversation is written by a background writer, so the request that evicted it does not wait
|
||||
// for the disk. It stays in RAM (and the physical-RAM gate sees it) until this thread takes it back from the writer:
|
||||
// freed (spill_reclaim), or reused as it is when the next request wants it (the restore below). The RAM gate's own
|
||||
// evictions wait for the writer, so the memory they free shows up in the reading.
|
||||
std::optional<strata::core::BackgroundWriter<strata::core::SavedConversation>> spill_writer;
|
||||
if (spill.enabled()) {
|
||||
spill_writer.emplace([&](const strata::core::SavedConversation& s) { return spill_write(s, "evicted from RAM, written in the background"); },
|
||||
[] { strata::core::spill_detail::lower_thread_priority(); }); // (it gives way to the serve loop)
|
||||
conversations.set_evict_sink([&](strata::core::SavedConversation&& v) {
|
||||
if (spill_ready(v, "evicted from RAM")) spill_writer->push(std::move(v));
|
||||
});
|
||||
}
|
||||
// the writer's written images, freed here (they are on the SSD tier); the bytes freed
|
||||
auto spill_reclaim = [&]() -> size_t {
|
||||
if (!spill_writer) return 0;
|
||||
size_t n = 0;
|
||||
for (auto& d : spill_writer->take_done()) n += d.item.bytes();
|
||||
return n;
|
||||
};
|
||||
// #879: nothing parked is kept - the SSD tier's entries and what the writer holds (queued ones unwritten, the one in
|
||||
// flight once written). How many conversations went.
|
||||
auto spill_clear = [&]() -> size_t {
|
||||
size_t n = 0;
|
||||
if (spill_writer) {
|
||||
n += spill_writer->take_queued().size();
|
||||
spill_writer->wait_idle();
|
||||
for (auto& d : spill_writer->take_done()) n += d.serial == 0 ? 1 : 0; // (a written one is counted below)
|
||||
}
|
||||
return n + spill.clear();
|
||||
};
|
||||
// What a park captures: the main session's conversation (park_current) or an idle batch slot's (park_slot:
|
||||
// the reply it decoded, before an admission overwrites it). One budget / admission / snapshot path for both.
|
||||
struct ParkSource {
|
||||
@@ -13445,6 +13496,10 @@ int main(int argc, char** argv) {
|
||||
[&]() -> size_t {
|
||||
const size_t b = conversations.oldest_evictable_bytes();
|
||||
if (b == 0 || !conversations.evict_oldest()) return 0;
|
||||
if (spill_writer) { // (2c: the victim went to the background writer: its memory is back once written)
|
||||
spill_writer->wait_idle();
|
||||
spill_reclaim();
|
||||
}
|
||||
if (pools_budget.idle_bytes() > 0) pools_budget.shrink((size_t) -1);
|
||||
return b;
|
||||
},
|
||||
@@ -17136,7 +17191,7 @@ int main(int argc, char** argv) {
|
||||
live_ok = true;
|
||||
if (nan_flush) { // #879: the file replaced the poisoned session; the parked ones go (no slots here)
|
||||
nan_flush = false;
|
||||
const size_t n_parked = conversations.clear() + spill.clear(); // (the SSD tier's too)
|
||||
const size_t n_parked = conversations.clear() + spill_clear(); // (the SSD tier's and the writer's too)
|
||||
std::fprintf(stderr, "strata serve: after non-finite logits (#879): the restored session "
|
||||
"replaces the live one; dropped %zu parked conversation%s\n", n_parked,
|
||||
n_parked == 1 ? "" : "s");
|
||||
@@ -17548,7 +17603,7 @@ int main(int argc, char** argv) {
|
||||
live_ok = false;
|
||||
checks.clear();
|
||||
tail_ckpt_len = -1;
|
||||
const size_t n_parked = conversations.clear() + spill.clear(); // (the SSD tier's too)
|
||||
const size_t n_parked = conversations.clear() + spill_clear(); // (the SSD tier's and the writer's too)
|
||||
size_t n_slots = 0, n_running = 0;
|
||||
for (BSlot& sl : bs)
|
||||
if (sl.active) { // a running slot finishes its reply, but is not kept as a cache after it
|
||||
@@ -17681,12 +17736,44 @@ int main(int argc, char** argv) {
|
||||
// and the RAM tier's choice stands. Never borrowed from (it comes back whole).
|
||||
bool from_ssd = false;
|
||||
strata::core::ConversationCache::Match taken = parked; // the match whose image is restored: RAM's, or the SSD tier's
|
||||
if (spill.enabled() && spill.size() > 0 && stages.empty()) {
|
||||
const auto sp = spill.best(ids, req_imgs, want_cvec);
|
||||
if (sp.tokens > std::max({resume, slot_tokens, parked.tokens}) && spill_id) {
|
||||
// 2c: a conversation the background writer still holds is still in RAM: when it serves this prompt best it is taken
|
||||
// back as it is (waiting for the one write in flight, if it is that one) and its SSD copy dropped - no read.
|
||||
if (spill_writer && stages.empty()) {
|
||||
const int64_t floor_tokens = std::max({resume, slot_tokens, parked.tokens});
|
||||
int64_t held = 0;
|
||||
spill_writer->for_each_held([&](const strata::core::SavedConversation& s) {
|
||||
held = std::max(held, strata::core::conversation_image_prefix(s, ids, req_imgs, want_cvec).first);
|
||||
});
|
||||
if (held > floor_tokens) {
|
||||
const auto t0 = Clock::now();
|
||||
const size_t sp_tokens = spill.entry(sp.index).live.ids.size();
|
||||
const uint64_t sp_bytes = spill.entry(sp.index).bytes;
|
||||
spill_writer->wait_idle();
|
||||
auto done = spill_writer->take_done();
|
||||
size_t at = SIZE_MAX;
|
||||
std::pair<int64_t, bool> m{0, false};
|
||||
for (size_t i = 0; i < done.size(); ++i) {
|
||||
const auto mi = strata::core::conversation_image_prefix(done[i].item, ids, req_imgs, want_cvec);
|
||||
if (mi.first > m.first) { m = mi; at = i; }
|
||||
}
|
||||
if (at != SIZE_MAX && m.first > floor_tokens) {
|
||||
if (done[at].serial != 0) spill.drop_serial(done[at].serial);
|
||||
std::fprintf(stderr, "strata serve: conversation cache: took %zu tokens back from the SSD writer, still in "
|
||||
"RAM, in %.1f ms (this prompt starts with %lld of them)\n",
|
||||
done[at].item.live.ids.size(),
|
||||
std::chrono::duration<double, std::milli>(Clock::now() - t0).count(), (long long) m.first);
|
||||
incoming.emplace(std::move(done[at].item));
|
||||
taken = strata::core::ConversationCache::Match{SIZE_MAX, m.first, m.second, 0};
|
||||
from_ssd = true; // (not the RAM tier's: no borrowing, no take from it)
|
||||
}
|
||||
} // (the other written ones are freed here: they are on the SSD tier)
|
||||
}
|
||||
spill_reclaim(); // what the writer finished meanwhile is on the SSD tier: its RAM goes back before this request parks
|
||||
if (!from_ssd && spill.enabled() && spill.size() > 0 && stages.empty()) {
|
||||
const auto sp = spill.best(ids, req_imgs, want_cvec);
|
||||
const auto sp_entry = sp.tokens > 0 ? spill.find(sp.serial) : std::nullopt;
|
||||
if (sp_entry && sp.tokens > std::max({resume, slot_tokens, parked.tokens}) && spill_id) {
|
||||
const auto t0 = Clock::now();
|
||||
const size_t sp_tokens = sp_entry->live.ids.size();
|
||||
const uint64_t sp_bytes = sp_entry->bytes;
|
||||
strata::core::SavedConversation image;
|
||||
std::string why;
|
||||
try {
|
||||
@@ -17703,15 +17790,16 @@ int main(int argc, char** argv) {
|
||||
};
|
||||
if (strata::core::conversation_session_read_limits(limits, ss, g, use_mtp ? &mtp.kv_state() : nullptr,
|
||||
(uint64_t) o.max_context, (uint64_t) std::max(o.prompt_cache, 1), why) &&
|
||||
spill.take(sp.index, *spill_id, limits, image, why))
|
||||
spill.take_serial(sp.serial, *spill_id, limits, image, why))
|
||||
from_ssd = true;
|
||||
else if (sp.index < spill.size() && spill.entry(sp.index).serial == sp.serial)
|
||||
spill.drop(sp.index); // (limits that cannot be formed: the entry cannot be read here either)
|
||||
else
|
||||
spill.drop_serial(sp.serial); // (limits that cannot be formed: the entry cannot be read here either)
|
||||
} catch (const std::bad_alloc&) {
|
||||
why = "not enough RAM to read it";
|
||||
if (sp.index < spill.size() && spill.entry(sp.index).serial == sp.serial) spill.drop(sp.index);
|
||||
spill.drop_serial(sp.serial);
|
||||
}
|
||||
if (from_ssd) {
|
||||
std::lock_guard<std::mutex> lk(spill_cost_mu);
|
||||
spill_cost.saw_read(sp_bytes, std::chrono::duration<double, std::milli>(Clock::now() - t0).count());
|
||||
std::fprintf(stderr, "strata serve: conversation cache: read %zu tokens back from the SSD tier in %.1f ms "
|
||||
"(this prompt starts with %lld of them); on SSD %zu, %llu MiB\n", sp_tokens,
|
||||
@@ -21362,7 +21450,10 @@ int main(int argc, char** argv) {
|
||||
// cancel stopped it part-way (a cancelled request used to be logged and counted as having read them all)
|
||||
const int64_t fresh = n - resume;
|
||||
const int64_t read_n = cancelled ? std::clamp<int64_t>(pp_reached - resume, 0, fresh) : fresh;
|
||||
if (!cancelled) spill_cost.saw_prompt(read_n, read_pass_ms); // (the SSD tier's cost rule learns this engine's prompt speed)
|
||||
if (!cancelled) { // (the SSD tier's cost rule learns this engine's prompt speed)
|
||||
std::lock_guard<std::mutex> lk(spill_cost_mu);
|
||||
spill_cost.saw_prompt(read_n, read_pass_ms);
|
||||
}
|
||||
// DONE <generated> <prompt> <prompt ms> <decode ms> <finish> <drafts accepted> <drafts offered> <reused> [hits] [lookups]
|
||||
// [RAM blobs] [file blobs] [file MB] (CS-T tiers; appended, so an older server reads the rest)
|
||||
// [prompt tokens read] (#471: fewer than <prompt> - <reused> when a cancel stopped the read)
|
||||
|
||||
Reference in new issue
Block a user