diff --git a/docs/DETAILS.md b/docs/DETAILS.md index e03693c990..ff4e7d3f06 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1804,7 +1804,7 @@ mean KL from the stock model 0.063 nats (max 4.1), perplexity +15% on code, +2.3 ## Inkling-2-Mini conversation cache on disk (CUDA, opt-in) -`strata-inkling --serve --conversation-cache-dir DIR [--conversation-cache-gb N]` (default cap 8 GB) writes a conversation to a file in `DIR` when another request is about to overwrite its slot and when the engine stops, and the first request that continues it reads it back, also after a restart or an app update: the first turn of an old chat reads only its new text. A file holds the conversation's prompt-end checkpoint and the global K/V of its tokens (about 20 KB per token at the default FP8 K/V, 350 MB at 16K tokens, 613 MB at 32K), bound to the engine version, the model file, the K/V type and layout. A file of another model, engine build or K/V layout, a damaged or cut file is ignored and removed; the folder is capped: room is made before a file is written (so a conversation of about 2.4 GB at 128K tokens never needs the folder to hold the old files and the new one at once), the earlier turns of the same chat go first, then the least recently used files; a conversation larger than the cap is not written, and when the engine stops it writes at most one cap's worth. A chat with pictures is restored only for the same pictures (a SHA-256 of their pixels). With a layer split or the elastic 1M tiers no file is written or read (one log line says so). A hard kill of the engine writes nothing new; the files written earlier stay. Measured on an RTX A6000 (SQ-20 v2): the first token of turn 2 after a restart 0.34 / 0.48 / 0.78 s at 8K / 16K / 32K tokens, against 3.4 / 7.2 / 15.8 s when the engine reads the prompt again. Other backends (HIP, Metal, SYCL) do not export a conversation yet. +`strata-inkling --serve --conversation-cache-dir DIR [--conversation-cache-gb N]` (default cap 8 GB) writes a conversation to a file in `DIR` when it would otherwise be lost and when the engine stops, and the first request that continues it reads it back, also after a restart or an app update: the first turn of an old chat reads only its new text. A file holds the conversation's prompt-end checkpoint and the global K/V of its tokens (about 20 KB per token at the default FP8 K/V, 350 MB at 16K tokens, 613 MB at 32K), bound to the engine version, the model file, the K/V type and layout. A file of another model, engine build or K/V layout, a damaged or cut file is ignored and removed; the folder is capped: room is made before a file is written (so a conversation of about 2.4 GB at 128K tokens never needs the folder to hold the old files and the new one at once), only the newest file of a chat stays (a longer turn of the same chat removes the earlier files at once, and a conversation already covered by such a file is not written again), then the least recently used files go; a conversation larger than the cap is not written, and when the engine stops it writes at most one cap's worth. With `--slot-cache-mib` the conversation first goes to the RAM park cache and to a file only when that cache drops it, when it does not fit there, or when the engine stops, so a title or summary request costs no file write; without a RAM park cache it is written when another request overwrites its slot. A chat with pictures is restored only for the same pictures (a SHA-256 of their pixels). With a layer split or the elastic 1M tiers no file is written or read (one log line says so). A hard kill of the engine writes nothing new; the files written earlier stay. Measured on an RTX A6000 (SQ-20 v2): the first token of turn 2 after a restart 0.34 / 0.48 / 0.78 s at 8K / 16K / 32K tokens, against 3.4 / 7.2 / 15.8 s when the engine reads the prompt again. Other backends (HIP, Metal, SYCL) do not export a conversation yet. ## Conversation cache copies on a slow host link (CUDA, opt-in) diff --git a/engine/src/inkling2/ink_conv_disk.h b/engine/src/inkling2/ink_conv_disk.h index ce0d0d62ff..32326d4cbf 100644 --- a/engine/src/inkling2/ink_conv_disk.h +++ b/engine/src/inkling2/ink_conv_disk.h @@ -108,6 +108,16 @@ public: e.stamp = ++clock_; written_ += e.bytes; entries_.push_back(std::move(e)); + // Only the newest file of a chat stays: the earlier turns (their tokens are a strict prefix of this one, same pictures) go now, not only when the folder is full. + for (size_t i = entries_.size() - 1; i-- > 0;) { + const Entry& o = entries_[i]; + if (o.tokens.size() >= tokens.size() || !std::equal(o.tokens.begin(), o.tokens.end(), tokens.begin())) continue; + const int n = static_cast(o.tokens.size()); + if (!pics_match(o.pics, n, pics) || !pics_match(pics, n, o.pics)) continue; + std::filesystem::remove(o.path, ec); + entries_.erase(entries_.begin() + static_cast(i)); + ++superseded_; + } evict_to(cap_); return true; } @@ -124,6 +134,19 @@ public: return false; } + /// Is this conversation already stored, as its own file or as a prefix of a longer file of the same chat (same pictures)? Then writing it would add nothing: a request that + /// continues it is served by the longer file, which is the newest turn. A hit counts as a use of that file. + bool covered(const std::vector& tokens, const std::vector& pics) { + const int n = static_cast(tokens.size()); + for (Entry& e : entries_) { + if (e.tokens.size() < tokens.size() || !std::equal(tokens.begin(), tokens.end(), e.tokens.begin())) continue; + if (!pics_match(e.pics, n, pics) || !pics_match(pics, n, e.pics)) continue; + e.stamp = ++clock_; + return true; + } + return false; + } + /// `min_prefix`: only conversations longer than this are considered (the caller already has that much from memory). bool load_best(const std::vector& ids, const std::vector& pics, std::vector& payload, int& n_prefix, std::string& note, int min_prefix = 0) { namespace fs = std::filesystem; @@ -249,12 +272,15 @@ private: public: size_t evicted() const { return evicted_; } + /// Files removed because a longer turn of the same chat was written. + size_t superseded() const { return superseded_; } /// Bytes written by save() since the object was made (the serve loop's shutdown pass stops after one cap's worth). uint64_t written_bytes() const { return written_; } private: std::string dir_, identity_; uint64_t cap_ = 0, id_hash_ = 0, clock_ = 0, written_ = 0; + size_t superseded_ = 0; size_t dropped_ = 0, evicted_ = 0; std::vector entries_; }; diff --git a/engine/src/inkling2/ink_conv_disk_test.cpp b/engine/src/inkling2/ink_conv_disk_test.cpp index d3a2fb7f80..53b5b1a769 100644 --- a/engine/src/inkling2/ink_conv_disk_test.cpp +++ b/engine/src/inkling2/ink_conv_disk_test.cpp @@ -44,7 +44,7 @@ int main() { CHECK(!d.load_best(seq(1, 100), {}, out, n, note)); // not shorter than the prompt: nothing to resume CHECK(!d.load_best(seq(2, 120), {}, out, n, note)); // another conversation } - // the longest prefix wins + // the longest prefix wins (the shorter turn of the chat was removed when the longer was written: one file) { ink2::ConvDisk d; CHECK(d.open(root.string(), 1u << 20, ID, err)); @@ -56,7 +56,7 @@ int main() { { ink2::ConvDisk d; CHECK(d.open(root.string(), 1u << 20, "model=abc;build=0.1.74;kv=fp8;win=1024", err)); - CHECK(d.count() == 0 && d.dropped() == 2); + CHECK(d.count() == 0 && d.dropped() == 1); CHECK(only_file(root).empty()); } // damage: a flipped payload byte, then a cut file @@ -147,16 +147,22 @@ int main() { ink2::ConvDisk d; CHECK(d.open(r3.string(), CAP, ID, err)); CHECK(d.save(seq(1, 100), {}, blob(30000, 1).data(), 30000, err)); // turn 1 - CHECK(d.save(seq(1, 150), {}, blob(40000, 2).data(), 40000, err)); // turn 2 (turn 1 is a prefix of it) - CHECK(d.count() == 2); - CHECK(d.has(seq(1, 100), {})); // the shorter file was used last: plain LRU would now evict turn 2 - CHECK(d.save(seq(1, 200), {}, blob(45000, 3).data(), 45000, err)); // turn 3 does not fit next to both - CHECK(d.count() == 2 && d.total_bytes() <= CAP); - CHECK(!d.has(seq(1, 100), {})); // the superseded turn 1 went - CHECK(d.has(seq(1, 150), {}) && d.has(seq(1, 200), {})); // turns 2 and 3 stay + CHECK(d.save(seq(1, 150), {}, blob(40000, 2).data(), 40000, err)); // turn 2 (turn 1 is a prefix of it): turn 1's file goes at once, there is room for both + CHECK(d.count() == 1 && d.superseded() == 1); + CHECK(!d.has(seq(1, 100), {}) && d.has(seq(1, 150), {})); + CHECK(d.covered(seq(1, 100), {}) && d.covered(seq(1, 150), {})); // turn 1 needs no new file: turn 2 serves a request that continues it + CHECK(!d.covered(seq(1, 200), {})); // a longer turn is not covered + CHECK(!d.covered(seq(1, 100), {pic(10, 4, 7)})); // the same tokens with a picture in them are another conversation + CHECK(d.save(seq(1, 200), {}, blob(45000, 3).data(), 45000, err)); // turn 3 + CHECK(d.count() == 1 && d.superseded() == 2 && d.has(seq(1, 200), {}) && !d.has(seq(1, 150), {})); // a different chat does not supersede: its files are only evicted by use CHECK(d.save(seq(700, 100), {}, blob(30000, 4).data(), 30000, err)); - CHECK(d.total_bytes() <= CAP && d.has(seq(700, 100), {})); + CHECK(d.count() == 2 && d.total_bytes() <= CAP && d.has(seq(700, 100), {}) && d.has(seq(1, 200), {})); + // a restart sees the same: one file per chat + ink2::ConvDisk d2; + CHECK(d2.open(r3.string(), CAP, ID, err) && d2.count() == 2); + auto ids = seq(1, 200); ids.push_back(999); + CHECK(d2.load_best(ids, {}, out, n, note) && n == 200 && out == blob(45000, 3)); CHECK(d.written_bytes() > 0); } fs::remove_all(root); diff --git a/engine/src/inkling2/ink_serve.h b/engine/src/inkling2/ink_serve.h index eb7b801290..e94c374206 100644 --- a/engine/src/inkling2/ink_serve.h +++ b/engine/src/inkling2/ink_serve.h @@ -711,12 +711,27 @@ inline int run_serve_loop(const ServeConfig& cfg, InkModelFile& mf, InkBackend& conv_disk.count(), conv_disk.total_bytes() / 1048576.0, conv_disk.cap() / 1048576.0, conv_disk.dropped()); } } + // The conversation goes to a file only when it leaves memory: the RAM park cache drops it, it does not fit that cache, or the engine stops (with no RAM park cache: when its slot is + // overwritten). While the engine runs the RAM park is enough (REPROC's e2e: a write per title or summary request cost 0.5 s and 770 MiB at 43K tokens). A conversation that is already + // in a file, or is a prefix of a longer file of the same chat, is not written again; a longer turn written later removes the shorter files (ConvDisk::save). + auto disk_write = [&](const std::vector& prefix, const std::vector& pics, const InkBackend::ParkedState& st, int slot, const char* why) { + if (!disk_on || conv_disk.covered(prefix, pics)) return; + const double t0 = now_s(); + std::vector bytes; + std::string derr; + if (st.serialize(bytes) && conv_disk.save(prefix, pics, bytes.data(), bytes.size(), derr)) + std::fprintf(stderr, "[ink-serve] slot %d: conversation of %zu tokens written to the conversation cache (%s; %.0f MiB, %.2f s; %zu file(s), %.0f of %.0f MiB)\n", slot, prefix.size(), why, + bytes.size() / 1048576.0, now_s() - t0, conv_disk.count(), conv_disk.total_bytes() / 1048576.0, conv_disk.cap() / 1048576.0); + else + std::fprintf(stderr, "[ink-serve] slot %d: conversation of %zu tokens not written to the conversation cache (%s)%s%s\n", slot, prefix.size(), why, derr.empty() ? "" : ": ", derr.c_str()); + }; auto park_forget = [&](size_t i) { parked_bytes -= parked[i].bytes; parked.erase(parked.begin() + static_cast(i)); }; auto park_make_room = [&](size_t need) { while (!parked.empty() && parked_bytes + need > park_budget) { size_t lru = 0; for (size_t i = 1; i < parked.size(); ++i) if (parked[i].used < parked[lru].used) lru = i; std::fprintf(stderr, "[ink-serve] parked conversation of %zu tokens dropped (the budget is full)\n", parked[lru].prefix.size()); + if (parked[lru].st) disk_write(parked[lru].prefix, parked[lru].pics, *parked[lru].st, -1, "dropped from the RAM park cache"); park_forget(lru); } }; @@ -725,23 +740,17 @@ inline int run_serve_loop(const ServeConfig& cfg, InkModelFile& mf, InkBackend& const int n = static_cast(rq.prompt_ckpt_prefix.size()); if ((park_budget == 0 && !disk_on) || n < kParkMinTokens) return false; for (auto& p : parked) if (p.prefix == rq.prompt_ckpt_prefix && pics_match(p.pics, n, rq.ckpt_pics) && pics_match(rq.ckpt_pics, n, p.pics)) { p.used = now_s(); return false; } // already parked - if (park_budget == 0 && conv_disk.has(rq.prompt_ckpt_prefix, rq.ckpt_pics)) return false; // disk only: already in a file + if (park_budget == 0 && conv_disk.covered(rq.prompt_ckpt_prefix, rq.ckpt_pics)) return false; // disk only: already in a file auto st = backend.park_slot(rq.slot, n); if (!st) return false; - if (disk_on) { // 0.2.25 item 1: the same state, as a file (the cost of a turn that reads a conversation back from here is the file read, not the prompt) - const double t0 = now_s(); - std::vector bytes; - std::string derr; - if (st->serialize(bytes) && conv_disk.save(rq.prompt_ckpt_prefix, rq.ckpt_pics, bytes.data(), bytes.size(), derr)) - std::fprintf(stderr, "[ink-serve] slot %d: conversation of %d tokens written to the conversation cache (%.0f MiB, %.2f s; %zu file(s), %.0f of %.0f MiB)\n", rq.slot, n, - bytes.size() / 1048576.0, now_s() - t0, conv_disk.count(), conv_disk.total_bytes() / 1048576.0, conv_disk.cap() / 1048576.0); - else - std::fprintf(stderr, "[ink-serve] slot %d: conversation of %d tokens not written to the conversation cache%s%s\n", rq.slot, n, derr.empty() ? "" : ": ", derr.c_str()); - if (park_budget == 0) return true; // disk only: the state is not kept in memory (the slot is about to be overwritten, or the engine is stopping) + if (park_budget == 0) { // disk only (no RAM park cache): the file is the only place the conversation can go before its slot is overwritten + disk_write(rq.prompt_ckpt_prefix, rq.ckpt_pics, *st, rq.slot, "slot overwritten"); + return true; } const size_t b = st->bytes(); if (b > park_budget) { std::fprintf(stderr, "[ink-serve] a conversation of %d tokens (%.0f MiB) does not fit the %.0f MiB slot cache: not parked\n", n, b / 1048576.0, park_budget / 1048576.0); + disk_write(rq.prompt_ckpt_prefix, rq.ckpt_pics, *st, rq.slot, "does not fit the RAM park cache"); return false; } park_make_room(b); @@ -1734,7 +1743,15 @@ inline int run_serve_loop(const ServeConfig& cfg, InkModelFile& mf, InkBackend& if (disk_on) { const uint64_t w0 = conv_disk.written_bytes(); for (int s = 0; s < P && conv_disk.written_bytes() - w0 < conv_disk.cap(); ++s) { - if (!reqs[s].active) park_current(reqs[s]); + if (!reqs[s].active) park_current(reqs[s]); // with a RAM park cache this parks it; without one it writes the file + } + // what the RAM park cache holds goes to files now (most recently used first) + std::vector order(parked.size()); + for (size_t i = 0; i < order.size(); ++i) order[i] = i; + std::sort(order.begin(), order.end(), [&](size_t a, size_t b) { return parked[a].used > parked[b].used; }); + for (size_t i : order) { + if (conv_disk.written_bytes() - w0 >= conv_disk.cap()) break; + if (parked[i].st) disk_write(parked[i].prefix, parked[i].pics, *parked[i].st, -1, "engine stopping"); } } return 0; diff --git a/engine/src/inkling2/test_shared_prefix.py b/engine/src/inkling2/test_shared_prefix.py index 99bbe6f0fb..9a125f6fd8 100644 --- a/engine/src/inkling2/test_shared_prefix.py +++ b/engine/src/inkling2/test_shared_prefix.py @@ -653,6 +653,68 @@ class ConversationCacheOnDisk(unittest.TestCase): self.assertEqual(reuse, len(CHAT) - 1) self.assertEqual(tokens, self.cold(follow)) + def test_with_a_ram_park_cache_a_park_writes_no_file_while_the_engine_runs(self): + # REPROC's e2e: a file per title or summary request cost 0.5 s and 770 MiB. The RAM park is enough while the engine runs; files are written when the engine stops. + d = self.newdir() + e = self.eng(d, INK_TEST_SLOT_CACHE_MIB="64") + e.request(CHAT, pin=None) + e.request(HELPER, pin=None) # the chat is parked in RAM + self.assertEqual(self.files(d), [], "no file at a park") + follow = CHAT + [201, 202, 203] + tokens, reuse = e.request(follow, pin=None) # and comes back from RAM + self.assertEqual(reuse, len(CHAT) - 1) + self.assertEqual(tokens, self.cold(follow)) + self.assertEqual(self.files(d), [], "still none: the helper's conversation was parked in RAM too") + e.close() + self.assertEqual(len(self.files(d)), 2, "when the engine stops the chat (in its slot) and the helper (in RAM) are written") + e2 = self.eng(d, INK_TEST_SLOT_CACHE_MIB="64") + self.addCleanup(e2.close) + self.assertEqual(e2.request(HELPER + [301, 302], pin=None)[1], len(HELPER) - 1, "after a restart the helper's file is read back") + + def test_a_conversation_dropped_from_the_ram_park_cache_is_written(self): + d = self.newdir() + e = self.eng(d, INK_TEST_SLOT_CACHE_BYTES="800") # the chat's toy state is 688 bytes, the helper's 368: room for one of them, not for both + self.addCleanup(e.close) + e.request(CHAT, pin=None) + e.request(HELPER, pin=None) # the chat is parked (688 of 800 bytes): no file + self.assertEqual(self.files(d), []) + e.request(OTHER, pin=None) # the helper is parked, the chat (oldest) does not fit beside it and goes: it is written now + self.assertEqual(len(self.files(d)), 1) + follow = CHAT + [201] + tokens, reuse = e.request(follow, pin=None) + self.assertEqual(reuse, len(CHAT) - 1, "read back from the file, not read again") + self.assertEqual(tokens, self.cold(follow)) + + def test_only_the_newest_file_of_a_chat_stays(self): + # REPROC's e2e left 3 files (2.3 GB) for one chat: a longer turn of the same chat removes the shorter files at once + d = self.newdir() + e = self.eng(d) + self.addCleanup(e.close) + e.request(CHAT, pin=None) + e.request(HELPER, pin=None) # no RAM park cache: the chat's first turn is written when its slot is overwritten + self.assertEqual(len(self.files(d)), 1) + first = self.files(d) + turn2 = CHAT + [201, 202, 203] + self.assertEqual(e.request(turn2, pin=None)[1], len(CHAT) - 1) # read back from that file (the helper's conversation, which it overwrote, is written: 2 files) + self.assertEqual(len(self.files(d)), 2) + e.request(HELPER + [9], pin=None) # the slot is overwritten again: turn 2 is written, turn 1's file goes at once + files = self.files(d) + self.assertEqual(len(files), 2, "the helper's file and ONE file for the chat (three without the rule)") + self.assertNotIn(first[0], files, "the chat's first turn is gone, the newer turn took its place") + turn3 = turn2 + [211, 212] + tokens, reuse = e.request(turn3, pin=None) + self.assertEqual(reuse, len(turn2) - 1, "the newest file serves the next turn") + self.assertEqual(tokens, self.cold(turn3)) + + def test_a_different_chat_does_not_remove_another_chats_file(self): + d = self.newdir() + e = self.eng(d) + self.addCleanup(e.close) + e.request(CHAT, pin=None) + e.request(OTHER, pin=None) # CHAT written + e.request(HELPER, pin=None) # OTHER written + self.assertEqual(len(self.files(d)), 2) + def test_a_file_of_another_identity_is_ignored_and_removed(self): d = self.newdir() self.run_first(d, CHAT)