From 0aaa75465679c7d1d5fe1842f282afa612e64eae Mon Sep 17 00:00:00 2001 From: Eddoursul Date: Fri, 25 Sep 2026 00:10:51 +0200 Subject: [PATCH] Prompt cache for --serve A request continues from the longest prefix of its prompt the engine still holds: the live sequence, checkpoints of the fixed-size sequence state (GDN recurrence and conv history, QSA indexer tail, PLE history) in host memory, or a conversation another request replaced, stashed in RAM with its K/V cells. Checkpoints are taken before a prompt's last <|im_start|>, at the prompt's end and every --cache-every cells of a long prompt. Short prompt remainders go through verify windows instead of the batched prompt path. The decode loop no longer verifies past the output limit or a drafted end-of-turn token, so the live state ends where the emitted text does. The server reports reused tokens (OpenAI prompt_tokens_details.cached_tokens, Anthropic cache_read_input_tokens) and drains the engine to DONE inside the request lock. New engine options: --prompt-cache N, --cache-ram MIB, --cache-every N, --feed-max N. --- CMakeLists.txt | 3 +- README.md | 14 +- include/strata/core/mtp.hpp | 2 + include/strata/core/prompt_cache.hpp | 97 +++++++++ include/strata/core/session.hpp | 16 ++ serve/server.py | 44 +++-- src/core/prompt_cache.cpp | 285 +++++++++++++++++++++++++++ src/core/session.cpp | 63 ++++++ src/program/generate.cpp | 163 +++++++++++---- 9 files changed, 635 insertions(+), 52 deletions(-) create mode 100644 include/strata/core/prompt_cache.hpp create mode 100644 src/core/prompt_cache.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 0b17460802..1d56925412 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -236,7 +236,8 @@ if(STRATA_ENABLE_CUDA) # library is the honest shape of the dependency graph: core knows about devices and weights, kernels know # about arithmetic, and this one knows the ORDER the arithmetic happens in. add_library(strata_engine STATIC src/core/layer.cpp src/core/session.cpp src/core/expert_source.cpp - src/core/expert_cache.cpp src/core/native_head.cpp src/core/native_dense.cpp src/core/verify.cpp src/core/mtp.cpp) + src/core/expert_cache.cpp src/core/native_head.cpp src/core/native_dense.cpp src/core/verify.cpp src/core/mtp.cpp + src/core/prompt_cache.cpp) target_include_directories(strata_engine PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) target_link_libraries(strata_engine PUBLIC strata_core strata_kernels strata_kernels_cpu CUDA::cudart) diff --git a/README.md b/README.md index 03db4da847..381fb306c3 100644 --- a/README.md +++ b/README.md @@ -178,15 +178,23 @@ print(r.choices[0].message.content) think briefly, on hard ones `high` thinks longest and is most accurate. - **Chat apps.** Any app with an "OpenAI-compatible" provider works: base URL `http://127.0.0.1:8080/v1`, any API key. - **Context.** Chosen in setup (8K-262K). Requests longer than that are refused, never silently cut. +- **Prompt cache.** A request continues from the longest start of its prompt the engine still holds, so the next turn + of a chat or an agent processes only what is new (a 16K-token conversation: ~0.3 s instead of ~25 s before the first + token). It keeps checkpoints of the sequence state in RAM (at every turn's start and end, and every 16K tokens of a + long prompt: regenerated and edited answers resume from them) and moves a conversation that another request replaces + (a chat app's title request, a subagent) to RAM with its key/value cache, so switching back continues where it was. + Responses report the reused tokens (`usage.prompt_tokens_details.cached_tokens`; Anthropic: + `cache_read_input_tokens`). Engine options: `--prompt-cache N` checkpoints (default 16, ~110 MB each; 0 = off), + `--cache-ram MIB` for replaced conversations (default 16384), `--cache-every N` (default 16384). A changed system + prompt or reasoning effort changes the prompt from its first tokens, so nothing is reused. - **From other devices / the internet.** The server listens on your PC only (`127.0.0.1`). To reach it from elsewhere, put a tunnel in front of it, for example [cloudflared](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/do-more-with-tunnels/trycloudflare/): `cloudflared tunnel --url http://127.0.0.1:8080`. **Set a key first**, or anyone with the link can use your PC: add `"api_key": "some-long-secret"` to `strata-.json` (or set the `STRATA_API_KEY` environment variable); clients then send it as their API key. -**Current limits (v1):** one request at a time; greedy decoding (temperature is ignored); every request processes its -whole prompt again (no conversation cache yet, so long chats have a long time-to-first-token); images only when set up -with them (below); no video. +**Current limits (v1):** one request at a time; greedy decoding (temperature is ignored); requests with images are +not cached; images only when set up with them (below); no video. --- diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hpp index ce2ad113bf..400d79d3f5 100644 --- a/include/strata/core/mtp.hpp +++ b/include/strata/core/mtp.hpp @@ -46,6 +46,8 @@ public: /// The prompt's length: prefill() skips the cells the attention window can never reach again. void set_prompt_len(int64_t n) { prompt_len_ = n; } uint64_t vram_bytes() const { return vram_; } + /// The layer's own K/V cells (the prompt cache stashes them with the model's). + QsaState& kv_state() { return st_; } /// The main model's embedding and head, and the verify window's final residuals (T rows, hc*n_embd each). bool bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err); diff --git a/include/strata/core/prompt_cache.hpp b/include/strata/core/prompt_cache.hpp new file mode 100644 index 0000000000..7d9ed19b45 --- /dev/null +++ b/include/strata/core/prompt_cache.hpp @@ -0,0 +1,97 @@ +// include/strata/core/prompt_cache.hpp - the --serve prompt cache. +// +// A request continues from the longest prefix of its prompt that the engine still holds, instead of processing +// the whole conversation again. Three things hold prefixes: +// +// * the LIVE sequence: the tokens whose cells the session state holds right now; +// * CHECKPOINTS of the live sequence (session_ckpt_*): the fixed-size state at one position. The K/V cells +// are indexed by position, so restoring a checkpoint at `pos` and overwriting the cells from `pos` on +// continues the sequence from there; +// * STASHED sequences: a sequence the live one replaced, kept in host memory with its K/V cells and its +// checkpoints, so a client that alternates between conversations (a chat and its title request, an agent +// and its subagents) does not start over on every switch. +// +// Checkpoint buffers are a shared pool of `max_ckpts`; the least recently used one goes when it is full. The +// stash's K/V copies share a byte budget in the same way. +#pragma once + +#include "strata/core/session.hpp" + +#include +#include +#include +#include + +namespace strata::core { + +class PromptCache { +public: + /// `kv`: every state whose cells a stashed sequence keeps (the QSA layers and the draft layer). + PromptCache(const ModelGeometry& g, SessionState& ss, std::vector kv, void* stream, int max_ckpts, + uint64_t stash_bytes); + ~PromptCache(); + PromptCache(const PromptCache&) = delete; + PromptCache& operator=(const PromptCache&) = delete; + + bool enabled() const { return max_ckpts_ > 0; } + uint64_t ckpt_bytes() const { return ckpt_bytes_; } + + /// Sets the session up for a prompt of `ids`: continues from the longest prefix (at most ids.size() - 1 + /// cells, the last token always goes through a verify window) that the live sequence, a checkpoint or a + /// stashed sequence holds, or zeroes the session. With `cacheable` false (an image request, whose cells the + /// ids do not describe) it zeroes the session and the live sequence is not kept. Returns the cells reused. + int64_t begin(const std::vector& ids, bool cacheable); + /// The cells [pos, pos + n) now hold `tokens`; pos <= live length, and anything after pos is gone. + void set(int64_t pos, const int64_t* tokens, int64_t n); + void set(int64_t pos, const int32_t* tokens, int64_t n); + /// Checkpoints the session, which is at `pos` == the live length. + void checkpoint(int64_t pos); + /// Forgets the live sequence (after an image request). + void forget(); + + /// One line for the log: checkpoints and stashed sequences. + std::string summary() const; + +private: + struct Ckpt { int64_t pos; void* host; uint64_t stamp; }; + struct Seq { + std::vector tokens; + std::vector ckpts; + std::unique_ptr kv; // cells [0, kv_cells) of every K/V state (stashed sequences only) + int64_t kv_cells = 0; + uint64_t kv_bytes = 0; + uint64_t stamp = 0; + }; + + /// One device region of the K/V cells, stored back to back in a stashed sequence's buffer. + struct Part { void* dev; uint64_t bytes; }; + + /// Cells of `seq` a prompt can continue from: the whole sequence when it is a prefix of the prompt (live + /// only: the state is there), else its best checkpoint within the common prefix (its position; -1: none). + int64_t reusable(const Seq& seq, const std::vector& ids, bool live) const; + static Ckpt* find(Seq& seq, int64_t pos); + void* take_buffer(); + void release(Seq& seq, int64_t keep_upto); // frees the checkpoints after `keep_upto` + /// Moves a copy of the live sequence to the stash: its K/V cells, a checkpoint of its end, and its + /// checkpoints after `keep_upto` (the ones before stay with the live sequence, which continues from there). + void stash_live(int64_t keep_upto); + std::vector kv_parts(int64_t cells) const; + bool kv_copy(const std::vector& parts, uint8_t* host, bool to_host); + bool restore(Seq& seq, int64_t pos); // K/V cells (stashed only) and the checkpoint at `pos` + + const ModelGeometry& g_; + SessionState& ss_; + std::vector kv_; + void* stream_; + int max_ckpts_; + uint64_t stash_budget_; + uint64_t ckpt_bytes_; + int allocated_ = 0; + uint64_t clock_ = 0; + Seq live_; + std::vector stash_; + std::vector free_; + std::vector> owned_; // every buffer, and whether it is pinned +}; + +} // namespace strata::core diff --git a/include/strata/core/session.hpp b/include/strata/core/session.hpp index e9c39ced28..3b32942fbd 100644 --- a/include/strata/core/session.hpp +++ b/include/strata/core/session.hpp @@ -83,6 +83,22 @@ uint64_t session_init(const ModelGeometry& g, int64_t max_cells, int64_t k, void /// from the reference's own `zeros()`. void session_zero(SessionState& s, const ModelGeometry& g, const float* R_init, void* stream); +// ================================ prompt-cache checkpoints ================================ +// +// The K/V caches are indexed by position, so the cells before a position stay valid when a later sequence +// overwrites the ones after it. What a position does NOT recover is the state that folds the whole prefix +// into a fixed size: every GDN layer's recurrence and conv history, each QSA indexer's raw block tail (plus +// its spare key, the pooled row of the open block and the block position), and the PLE's conv history and +// token window. A checkpoint is exactly that state at one position; restoring it and overwriting the cells +// from that position on continues the sequence as if it had been processed up to there. + +/// Bytes of one checkpoint (host memory). +uint64_t session_ckpt_bytes(const ModelGeometry& g); +/// Copies the sequence state at `pos` (positions [0, pos) processed) into `host`; synchronous. +bool session_ckpt_save(const SessionState& s, const ModelGeometry& g, int64_t pos, void* host, void* stream); +/// The inverse: the session continues at `pos`. The K/V cells [0, pos) must still hold the same prefix. +bool session_ckpt_load(SessionState& s, const ModelGeometry& g, int64_t pos, const void* host, void* stream); + /// One token: layers 0..47 in order, each a `block_layer`, and the residual is updated in place. /// /// `parts` is (k, n_embd) DEVICE memory, filled by the caller - by the CPU expert pool and the VRAM-resident diff --git a/serve/server.py b/serve/server.py index 91889ee530..82d2f8a009 100644 --- a/serve/server.py +++ b/serve/server.py @@ -85,8 +85,14 @@ class StrataEngine: if self.max_context <= 0: raise RuntimeError("the engine exited before it was ready" + (f" (see {log})" if log else "")) + def _done(self, line): + f = line.split() + self.last = {"generated": int(f[1]), "prompt_tokens": int(f[2]), "prompt_ms": float(f[3]), + "decode_ms": float(f[4]), "finish": f[5], "cached": int(f[6]) if len(f) > 6 else 0} + def generate(self, ids, max_new, sampling, cancel, embeddings=None): head = f"GENI {int(max_new)} {embeddings}" if embeddings else f"GEN {int(max_new)}" + self.last = {} self.proc.stdin.write(f"{head} {','.join(str(int(t)) for t in ids)}\n") self.proc.stdin.flush() done = False @@ -96,9 +102,7 @@ class StrataEngine: if not cancel.is_set(): yield int(line[2:]) elif line.startswith("DONE"): - f = line.split() - self.last = {"generated": int(f[1]), "prompt_tokens": int(f[2]), "prompt_ms": float(f[3]), - "decode_ms": float(f[4]), "finish": f[5]} + self._done(line) done = True return elif line.startswith("ERR"): @@ -108,7 +112,10 @@ class StrataEngine: finally: if not done: # the consumer stopped early: drain to DONE for line in self.proc.stdout: - if line.startswith("DONE") or line.startswith("ERR"): + if line.startswith("DONE"): + self._done(line) + break + if line.startswith("ERR"): break def close(self): @@ -287,19 +294,23 @@ class Service: with self.fifo: gen = self.engine.generate(ids, max_new, sampling, cancel, embeddings=emb) if emb else \ self.engine.generate(ids, max_new, sampling, cancel) - for t in gen: - n += 1 - if t in self.stop_ids: - finish = "stop" - break - for ev in parser.feed(detok.push(t)): - yield "event", ev + try: + for t in gen: + n += 1 + if t in self.stop_ids: + finish = "stop" + break + for ev in parser.feed(detok.push(t)): + yield "event", ev + finally: + gen.close() # drains the engine to DONE before the next request finally: if emb: Path(emb).unlink(missing_ok=True) for ev in parser.finish(): yield "event", ev - yield "done", {"finish": finish, "completion_tokens": n} + yield "done", {"finish": finish, "completion_tokens": n, + "cached_tokens": getattr(self.engine, "last", {}).get("cached", 0)} # ------------------------------------------------------------------------------------------------ OpenAI @@ -328,7 +339,8 @@ def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel finish = "tool_calls" if calls and x["finish"] == "stop" else x["finish"] last = chunk({}, finish) last["usage"] = {"prompt_tokens": len(ids), "completion_tokens": x["completion_tokens"], - "total_tokens": len(ids) + x["completion_tokens"]} + "total_tokens": len(ids) + x["completion_tokens"], + "prompt_tokens_details": {"cached_tokens": x["cached_tokens"]}} yield last @@ -393,7 +405,9 @@ def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, can stop = "tool_use" if used_tool and x["finish"] == "stop" else \ {"stop": "end_turn", "length": "max_tokens"}[x["finish"]] yield "message_delta", {"type": "message_delta", "delta": {"stop_reason": stop, "stop_sequence": None}, - "usage": {"output_tokens": x["completion_tokens"]}} + "usage": {"input_tokens": len(ids) - x["cached_tokens"], + "cache_read_input_tokens": x["cached_tokens"], + "output_tokens": x["completion_tokens"]}} yield "message_stop", {"type": "message_stop"} @@ -414,7 +428,7 @@ def anthropic_collect(events) -> dict: b["input"] = json.loads(d["partial_json"]) elif name == "message_delta": msg["stop_reason"] = e["delta"]["stop_reason"] - msg["usage"]["output_tokens"] = e["usage"]["output_tokens"] + msg["usage"].update(e["usage"]) msg["content"] = blocks return msg diff --git a/src/core/prompt_cache.cpp b/src/core/prompt_cache.cpp new file mode 100644 index 0000000000..01af3bda2d --- /dev/null +++ b/src/core/prompt_cache.cpp @@ -0,0 +1,285 @@ +// src/core/prompt_cache.cpp - the --serve prompt cache (see include/strata/core/prompt_cache.hpp). +#include "strata/core/prompt_cache.hpp" + +#include "strata/kernels/kv_q8.hpp" +#include "strata/kernels/qsa.hpp" + +#include + +#include +#include +#include +#include + +namespace strata::core { + +namespace { + +/// A replaced sequence is stashed when the switch would drop at least this many of its cells. +constexpr int64_t kStashMin = 1024; + +} // namespace + +PromptCache::PromptCache(const ModelGeometry& g, SessionState& ss, std::vector kv, void* stream, + int max_ckpts, uint64_t stash_bytes) + : g_(g), ss_(ss), kv_(std::move(kv)), stream_(stream), max_ckpts_(max_ckpts), stash_budget_(stash_bytes), + ckpt_bytes_(session_ckpt_bytes(g)) {} + +PromptCache::~PromptCache() { + for (const auto& [p, pinned] : owned_) { + if (pinned) cudaFreeHost(p); + else std::free(p); + } +} + +int64_t PromptCache::reusable(const Seq& seq, const std::vector& ids, bool live) const { + const int64_t m = std::min((int64_t) seq.tokens.size(), (int64_t) ids.size() - 1); + int64_t lcp = 0; + while (lcp < m && seq.tokens[(size_t) lcp] == ids[(size_t) lcp]) ++lcp; + if (live && lcp > 0 && lcp == (int64_t) seq.tokens.size()) return lcp; + int64_t best = -1; + for (const Ckpt& c : seq.ckpts) + if (c.pos <= lcp && c.pos > best) best = c.pos; + return best; +} + +PromptCache::Ckpt* PromptCache::find(Seq& seq, int64_t pos) { + for (Ckpt& c : seq.ckpts) + if (c.pos == pos) return &c; + return nullptr; +} + +void* PromptCache::take_buffer() { + if (!free_.empty()) { + void* h = free_.back(); + free_.pop_back(); + return h; + } + if (allocated_ < max_ckpts_) { + void* h = nullptr; + const bool pinned = cudaMallocHost(&h, (size_t) ckpt_bytes_) == cudaSuccess; + if (!pinned) { + (void) cudaGetLastError(); + h = std::malloc((size_t) ckpt_bytes_); // pageable: slower copies, same result + } + if (h != nullptr) { + owned_.emplace_back(h, pinned); + ++allocated_; + } + return h; + } + // the pool is full: the least recently used checkpoint of any sequence goes + Seq* owner = nullptr; + size_t at = 0; + uint64_t oldest = UINT64_MAX; + auto scan = [&](Seq& s) { + for (size_t i = 0; i < s.ckpts.size(); ++i) + if (s.ckpts[i].stamp < oldest) { + oldest = s.ckpts[i].stamp; + owner = &s; + at = i; + } + }; + scan(live_); + for (Seq& s : stash_) scan(s); + if (owner == nullptr) return nullptr; + void* h = owner->ckpts[at].host; + owner->ckpts.erase(owner->ckpts.begin() + (ptrdiff_t) at); + if (owner != &live_ && owner->ckpts.empty()) // a stashed sequence without a checkpoint cannot be resumed + stash_.erase(stash_.begin() + (owner - stash_.data())); + return h; +} + +void PromptCache::release(Seq& seq, int64_t keep_upto) { + for (size_t i = 0; i < seq.ckpts.size();) { + if (seq.ckpts[i].pos > keep_upto) { + free_.push_back(seq.ckpts[i].host); + seq.ckpts.erase(seq.ckpts.begin() + (ptrdiff_t) i); + } else { + ++i; + } + } +} + +std::vector PromptCache::kv_parts(int64_t cells) const { + // [page][kv_head][page_size][head_dim] with an identity page table: the first cells are one prefix of each + // pool. The indexer's pooled rows are one per idx_block cells. + const strata::kernels::QsaShapes sh = strata::kernels::qsa_real_shapes(); + const uint64_t hd = (uint64_t) g_.head_dim, row = (uint64_t) g_.idx_key_dim * sizeof(float); + std::vector parts; + for (QsaState* st : kv_) { + const uint64_t pages = (uint64_t) std::min(st->n_pages, (cells + sh.page_size - 1) / sh.page_size); + const uint64_t c = pages * (uint64_t) g_.n_head_kv * (uint64_t) sh.page_size; + if (st->kv_int8) { + const uint64_t scales = c * (hd / strata::kernels::KV_Q8_GROUP) * sizeof(uint16_t); + parts.push_back({st->k_q, c * hd}); + parts.push_back({st->v_q, c * hd}); + parts.push_back({st->k_scale, scales}); + parts.push_back({st->v_scale, scales}); + } else { + parts.push_back({st->k_pool, c * hd * sizeof(uint16_t)}); + parts.push_back({st->v_pool, c * hd * sizeof(uint16_t)}); + } + const int64_t rows = std::min(cells / sh.idx_block + 2, st->max_cells / sh.idx_block + 2); + parts.push_back({st->idx_pooled, (uint64_t) rows * row}); + } + return parts; +} + +bool PromptCache::kv_copy(const std::vector& parts, uint8_t* host, bool to_host) { + cudaStream_t cs = (cudaStream_t) stream_; + for (const Part& p : parts) { + const cudaError_t e = to_host ? cudaMemcpyAsync(host, p.dev, (size_t) p.bytes, cudaMemcpyDeviceToHost, cs) + : cudaMemcpyAsync(p.dev, host, (size_t) p.bytes, cudaMemcpyHostToDevice, cs); + if (e != cudaSuccess) return false; + host += p.bytes; + } + return cudaStreamSynchronize(cs) == cudaSuccess; +} + +void PromptCache::stash_live(int64_t keep_upto) { + const int64_t L = (int64_t) live_.tokens.size(); + if (stash_budget_ == 0 || L < kStashMin) return; + const std::vector parts = kv_parts(L); + uint64_t bytes = 0; + for (const Part& p : parts) bytes += p.bytes; + if (bytes > stash_budget_) return; + uint64_t used = 0; + for (const Seq& s : stash_) used += s.kv_bytes; + while (!stash_.empty() && used + bytes > stash_budget_) { // the least recently used sequences go + auto lru = std::min_element(stash_.begin(), stash_.end(), + [](const Seq& a, const Seq& b) { return a.stamp < b.stamp; }); + used -= lru->kv_bytes; + release(*lru, 0); + stash_.erase(lru); + } + Seq s; + s.kv.reset(new (std::nothrow) uint8_t[bytes]); + if (!s.kv || !kv_copy(parts, s.kv.get(), true)) return; + checkpoint(L); // the end state: the session is still at L + for (size_t i = 0; i < live_.ckpts.size();) { + if (live_.ckpts[i].pos > keep_upto) { + s.ckpts.push_back(live_.ckpts[i]); + live_.ckpts.erase(live_.ckpts.begin() + (ptrdiff_t) i); + } else { + ++i; + } + } + if (s.ckpts.empty()) return; + s.tokens = live_.tokens; + s.kv_cells = L; + s.kv_bytes = bytes; + s.stamp = ++clock_; + stash_.push_back(std::move(s)); +} + +bool PromptCache::restore(Seq& seq, int64_t pos) { + Ckpt* ck = find(seq, pos); + if (ck == nullptr) return false; + if (seq.kv && !kv_copy(kv_parts(seq.kv_cells), seq.kv.get(), false)) return false; + ck->stamp = ++clock_; + return session_ckpt_load(ss_, g_, pos, ck->host, stream_); +} + +int64_t PromptCache::begin(const std::vector& ids, bool cacheable) { + const int64_t L = (int64_t) live_.tokens.size(); + auto zero = [&]() -> int64_t { + release(live_, 0); + live_.tokens.clear(); + session_zero(ss_, g_, nullptr, stream_); + cudaStreamSynchronize((cudaStream_t) stream_); + return 0; + }; + if (!enabled()) return zero(); + if (!cacheable) { + stash_live(0); + return zero(); + } + int64_t best = reusable(live_, ids, true); + int from = -1; // -1: the live sequence, else a stashed one + for (size_t i = 0; i < stash_.size(); ++i) { + const int64_t r = reusable(stash_[i], ids, false); + if (r > best) { + best = r; + from = (int) i; + } + } + if (best <= 0) { + stash_live(0); + return zero(); + } + if (from < 0) { + // The live sequence continues. When the prompt drops most of it (another conversation that shares a + // prefix), the rest goes to the stash; an edit near the end just overwrites it. + const int64_t dropped = L - best; + if (dropped >= kStashMin && dropped > best) { + if (Ckpt* c = find(live_, best)) c->stamp = ++clock_; // keeps it through the stash's evictions + stash_live(best); + } + if (best < L && !restore(live_, best)) return zero(); + release(live_, best); + live_.tokens.resize((size_t) best); + return best; + } + // Another sequence continues: the live one is stashed and the chosen one becomes live. + Seq chosen = std::move(stash_[(size_t) from]); + stash_.erase(stash_.begin() + from); + stash_live(0); + release(live_, 0); + live_.tokens.clear(); + if (!restore(chosen, best)) { + release(chosen, 0); + return zero(); + } + live_.tokens.assign(chosen.tokens.begin(), chosen.tokens.begin() + best); + live_.ckpts = std::move(chosen.ckpts); + release(live_, best); + return best; +} + +void PromptCache::set(int64_t pos, const int64_t* tokens, int64_t n) { + if (!enabled()) return; + release(live_, pos); + live_.tokens.resize((size_t) pos); + live_.tokens.insert(live_.tokens.end(), tokens, tokens + n); +} + +void PromptCache::set(int64_t pos, const int32_t* tokens, int64_t n) { + if (!enabled()) return; + release(live_, pos); + live_.tokens.resize((size_t) pos); + for (int64_t i = 0; i < n; ++i) live_.tokens.push_back(tokens[i]); +} + +void PromptCache::checkpoint(int64_t pos) { + if (!enabled() || pos <= 0 || pos != (int64_t) live_.tokens.size() || find(live_, pos) != nullptr) return; + void* h = take_buffer(); + if (h == nullptr) return; + cudaDeviceSynchronize(); + if (!session_ckpt_save(ss_, g_, pos, h, stream_)) { + free_.push_back(h); + return; + } + live_.ckpts.push_back({pos, h, ++clock_}); +} + +void PromptCache::forget() { + release(live_, 0); + live_.tokens.clear(); +} + +std::string PromptCache::summary() const { + size_t n = live_.ckpts.size(); + uint64_t kv = 0; + for (const Seq& s : stash_) { + n += s.ckpts.size(); + kv += s.kv_bytes; + } + char buf[192]; + std::snprintf(buf, sizeof buf, "live %lld cells; %zu checkpoints (%.0f MiB); %zu stashed sequences (%.0f MiB)", + (long long) live_.tokens.size(), n, (double) (n * ckpt_bytes_) / 1048576.0, stash_.size(), + (double) kv / 1048576.0); + return buf; +} + +} // namespace strata::core diff --git a/src/core/session.cpp b/src/core/session.cpp index cf0bbde2fe..43fc925770 100644 --- a/src/core/session.cpp +++ b/src/core/session.cpp @@ -129,6 +129,69 @@ void session_zero(SessionState& s, const ModelGeometry& g, const float* R_init, s.ple_token = -1; } +namespace { + +/// One region of a checkpoint: `bytes` of device memory at `dev`, stored back to back in the host buffer. +struct CkptPart { void* dev; uint64_t bytes; }; + +/// The parts of a checkpoint at `pos`, in storage order (the PLE token window follows them on the host). +std::vector ckpt_parts(const SessionState& s, const ModelGeometry& g, int64_t pos) { + strata::kernels::QsaShapes sh = strata::kernels::qsa_real_shapes(); + sh.idx_dim = g.idx_key_dim; + const uint64_t row = (uint64_t) sh.idx_dim * sizeof(float); + std::vector parts; + parts.push_back({s.gdn_state, (uint64_t) g.n_gdn_layers() * gdn_state_floats(g) * sizeof(float)}); + parts.push_back({s.ple_hist, ple_hist_bytes()}); + for (int64_t i = 0; i < g.n_qsa_layers(); ++i) { + const QsaState& st = s.qsa_states[i]; + parts.push_back({st.idx_tail, (uint64_t) (sh.idx_block - 1) * row}); + parts.push_back({st.idx_dead, row}); + parts.push_back({(uint8_t*) st.idx_pooled + (uint64_t) (pos / sh.idx_block) * row, row}); + parts.push_back({st.idx_block_pos, sizeof(int32_t)}); + } + return parts; +} + +constexpr uint64_t kCkptHostInts = 3; // ple_prev[0], ple_prev[1], ple_token + +} // namespace + +uint64_t session_ckpt_bytes(const ModelGeometry& g) { + SessionState probe; // only the sizes are read: null device pointers are never dereferenced here + std::vector qsa((size_t) g.n_qsa_layers()); + probe.qsa_states = qsa.data(); + uint64_t n = kCkptHostInts * sizeof(int32_t); + for (const CkptPart& p : ckpt_parts(probe, g, 0)) n += p.bytes; + return n; +} + +bool session_ckpt_save(const SessionState& s, const ModelGeometry& g, int64_t pos, void* host, void* stream) { + cudaStream_t cs = (cudaStream_t) stream; + uint8_t* h = (uint8_t*) host; + for (const CkptPart& p : ckpt_parts(s, g, pos)) { + if (cudaMemcpyAsync(h, p.dev, (size_t) p.bytes, cudaMemcpyDeviceToHost, cs) != cudaSuccess) return false; + h += p.bytes; + } + const int32_t ints[kCkptHostInts] = {s.ple_prev[0], s.ple_prev[1], s.ple_token}; + std::memcpy(h, ints, sizeof ints); + return cudaStreamSynchronize(cs) == cudaSuccess; +} + +bool session_ckpt_load(SessionState& s, const ModelGeometry& g, int64_t pos, const void* host, void* stream) { + cudaStream_t cs = (cudaStream_t) stream; + const uint8_t* h = (const uint8_t*) host; + for (const CkptPart& p : ckpt_parts(s, g, pos)) { + if (cudaMemcpyAsync(p.dev, h, (size_t) p.bytes, cudaMemcpyHostToDevice, cs) != cudaSuccess) return false; + h += p.bytes; + } + int32_t ints[kCkptHostInts]; + std::memcpy(ints, h, sizeof ints); + s.ple_prev[0] = ints[0]; + s.ple_prev[1] = ints[1]; + s.ple_token = ints[2]; + return cudaStreamSynchronize(cs) == cudaSuccess; +} + /// Sets `s.gdn.state`/`conv_state` for `layer`, which is what makes one layer's GDN state its own. Shared by /// the direct and captured paths so the two cannot disagree about which slice a layer owns. void gdn_point_at(const ModelGeometry& g, int64_t layer, SessionState& s) { diff --git a/src/program/generate.cpp b/src/program/generate.cpp index e116abe52e..d3b07b581c 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -38,6 +38,7 @@ #include "strata/core/native_head.hpp" #include "strata/core/verify.hpp" #include "strata/core/mtp.hpp" +#include "strata/core/prompt_cache.hpp" #include "strata/prefill/prefill.hpp" #include "strata/core/native_dense.hpp" #include "strata/program/logits_selection.hpp" @@ -230,6 +231,16 @@ struct Options { bool serve = false; /// The vision path: keep a per-cell (t, h, w) rotary position table so --serve can take GENI requests. bool vision = false; + /// --serve prompt cache: checkpoints of the sequence state kept in host memory (0 = every request starts + /// from an empty sequence). A request continues from the longest prefix the session or a checkpoint holds. + int prompt_cache = 16; + /// Host memory for sequences the live one replaced (their K/V cells), in MiB. + int64_t cache_ram_mib = 16384; + /// Checkpoint interval inside long prompts (positions that are multiples of it). + int64_t cache_every = 16384; + /// Prompt remainders of up to this many tokens go through verify windows instead of the batched prompt path, + /// which lends and refills expert-cache slots on every call. + int64_t feed_max = 256; int adapt_swaps = 96; }; @@ -288,6 +299,14 @@ void usage() { " --shared-late A/B: shared expert after the CPU pool (default: overlapped with it)\n" " --keep-canonical A/B: also load canonical copies of natively served tensors (more VRAM)\n" " --vision --serve takes images too (GENI requests; embeddings from strata-vision)\n" + " --prompt-cache N --serve: keep N checkpoints of the sequence state in host memory and\n" + " continue each request from the longest cached prefix (default 16;\n" + " 0 = every request starts from an empty sequence)\n" + " --cache-every N checkpoint interval inside long prompts (default 16384)\n" + " --cache-ram MIB --serve: host memory for the K/V cells of sequences a request replaced,\n" + " so switching back to them continues where they were (default 16384)\n" + " --feed-max N --serve: prompt remainders up to N tokens run through verify windows\n" + " instead of the batched prompt path (default 256)\n" " --no-token-graph A/B: two graphs per layer (the host launches each) instead of one per token\n" " --no-fused-gr A/B: the six-kernel hyper-connection read and a separate write (native)\n" " --prefill CHUNK batched prompt processing in chunks of CHUNK tokens (needs --native)\n" @@ -527,6 +546,10 @@ int main(int argc, char** argv) { else if (a == "--pcie-mode") o.pcie_mode = next("--pcie-mode"); else if (a == "--serve") o.serve = true; else if (a == "--vision") o.vision = true; + else if (a == "--prompt-cache") o.prompt_cache = std::max(0, std::atoi(next("--prompt-cache"))); + else if (a == "--cache-every") o.cache_every = std::max(1, std::atoll(next("--cache-every"))); + else if (a == "--cache-ram") o.cache_ram_mib = std::max(0, std::atoll(next("--cache-ram"))); + else if (a == "--feed-max") o.feed_max = std::max(0, std::atoll(next("--feed-max"))); else if (a == "--no-spec-split") o.spec_split = false; else if (a == "--eos-ids") { std::string e; @@ -1852,11 +1875,21 @@ int main(int argc, char** argv) { for (float& v : drive.d.usage) v *= 0.7f; return true; }; + // ---- the prompt cache (strata/core/prompt_cache.hpp) + std::vector kv_states; + for (int64_t i = 0; i < g.n_qsa_layers(); ++i) kv_states.push_back(&ss.qsa_states[i]); + kv_states.push_back(&mtp.kv_state()); + strata::core::PromptCache pcache(g, ss, kv_states, main_cs, o.prompt_cache, (uint64_t) o.cache_ram_mib << 20); + if (pcache.enabled()) + std::fprintf(stderr, "strata serve: prompt cache on: up to %d checkpoints of %.1f MiB, %lld MiB for stashed " + "sequences\n", o.prompt_cache, (double) pcache.ckpt_bytes() / 1048576.0, + (long long) o.cache_ram_mib); std::printf("READY %lld\n", (long long) o.max_context); std::fflush(stdout); std::string line; int64_t rounds = 0; const int S = o.spec; + constexpr int64_t kImStart = 248045; // <|im_start|>: a new turn begins here // The vision path (--vision): GENI carries images. The file is one // or more strata-vision records (int32 'SVE1', n, nx, ny, n_embd, then n x n_embd floats) in prompt order; // each image's rows go to its run of <|image_pad|> tokens, whose M-RoPE positions are mtmd's: t = p, @@ -1971,41 +2004,92 @@ int main(int argc, char** argv) { if (bad) { std::printf("ERR a token id is outside the vocabulary\n"); continue; } cur = ids; const Clock::time_point r0 = Clock::now(); - strata::core::session_zero(ss, g, nullptr, main_cs); - cudaStreamSynchronize(main_stream); + auto report = [&](const std::string& e) { + std::fprintf(stderr, "strata serve: %s\n", e.c_str()); + std::printf("ERR %s\n", e.c_str()); + }; + // ---- the prompt cache: continue from the longest prefix it holds (or start from an empty sequence). + // Image requests are not cached: their cells are not identified by the token ids alone. + const bool track = pcache.enabled() && !geni; + const int64_t reuse = pcache.begin(ids, !geni); mtp.set_prompt_len(n); - std::vector> lent_now; - apply_pending(true); - if (lend_first >= 0) { - for (size_t i = 0; i < host_res.size(); ++i) - if (host_res[i] >= lend_first) { - lent_now.emplace_back((int32_t) i, host_res[i]); - host_res[i] = strata::core::kNotResident; - } - cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); - } - if (n > 1 && !sp.run(ids.data(), n - 1, 0, err)) { - std::fprintf(stderr, "strata serve: %s\n", err.c_str()); - std::printf("ERR %s\n", err.c_str()); - return 1; - } - for (const auto& [i, slot] : lent_now) { - const uint8_t* b = srcp->blob(i / g.n_expert, i % g.n_expert); - if (b == nullptr || !xcache.fill_slot_blocking(slot, b, err, - (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(i / g.n_expert))) { - std::printf("ERR refilling a lent slot failed: %s\n", err.c_str()); - return 1; + std::vector drafts((size_t) S, 0), window((size_t) S), outv((size_t) S); + std::vector dprob((size_t) S, 0.0f); + // ---- the rest of the prompt, [reuse, n - 1). A turn usually shares everything before its prompt's + // last <|im_start|> with the next one (chat templates re-render the answer, e.g. without its + // reasoning), so that position gets a checkpoint, and so do the prompt's end (a regenerated answer) + // and every `cache_every` cells of a long prompt. A short remainder goes through verify windows. + int64_t q = 0; + if (track) + for (int64_t i = n - 2; i > reuse; --i) + if (ids[(size_t) i] == kImStart) { q = i; break; } + int64_t batched_end = reuse; // [reuse, batched_end) through the batched prompt path + if (n - 1 - reuse > o.feed_max) batched_end = (q > reuse && n - 1 - q <= o.feed_max) ? q : n - 1; + if (batched_end > reuse) { + std::vector> lent_now; + apply_pending(true); + if (lend_first >= 0) { + for (size_t i = 0; i < host_res.size(); ++i) + if (host_res[i] >= lend_first) { + lent_now.emplace_back((int32_t) i, host_res[i]); + host_res[i] = strata::core::kNotResident; + } + cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); } - host_res[(size_t) i] = slot; + for (int64_t a0 = reuse; a0 < batched_end;) { + const int64_t b0 = track ? std::min(batched_end, (a0 / o.cache_every + 1) * o.cache_every) + : batched_end; + if (!sp.run(ids.data() + a0, b0 - a0, a0, err)) { report(err); return 1; } + if (track) { + pcache.set(a0, ids.data() + a0, b0 - a0); + if (b0 % o.cache_every == 0 || b0 == q || b0 == n - 1) pcache.checkpoint(b0); + } + a0 = b0; + } + for (const auto& [i, slot] : lent_now) { + const uint8_t* b = srcp->blob(i / g.n_expert, i % g.n_expert); + if (b == nullptr || !xcache.fill_slot_blocking(slot, b, err, + (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(i / g.n_expert))) { + std::printf("ERR refilling a lent slot failed: %s\n", err.c_str()); + return 1; + } + host_res[(size_t) i] = slot; + } + if (!lent_now.empty()) + cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); } - if (!lent_now.empty()) - cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + // prompt tokens through verify windows: each window is committed whole, and the draft layer catches up + // on the same cells (its drafts are not used) + auto feed = [&](int64_t from, int64_t to) -> bool { + for (int64_t j = from; j < to;) { + const int T = (int) std::min(S, to - j); + for (int i = 0; i < T; ++i) window[(size_t) i] = (int32_t) ids[(size_t) (j + i)]; + drive.d.layers = 0; + drive.d.experts = 0; + drive.d.failed = false; + apply_pending(false); + if (!ver.run(T, window.data(), j, &drive_pool_multi, &drive, outv.data(), err) || drive.d.failed) { + if (drive.d.failed && drive.d.fail) err = drive.d.fail; + return false; + } + if (!ver.commit(T, err)) return false; + for (int i = 0; i < T; ++i) outv[(size_t) i] = (int32_t) ids[(size_t) (j + i + 1)]; + if (!mtp.draft(T, outv.data(), j, T - 1, drafts.data(), err, dprob.data(), (float) o.spec_min_p)) + return false; + if (track) pcache.set(j, ids.data() + j, T); + j += T; + } + return true; + }; + const int64_t split = q > batched_end ? q : batched_end; + if (!feed(batched_end, split)) { report(err); return 1; } + if (track && split == q) pcache.checkpoint(q); + if (!feed(split, n - 1)) { report(err); return 1; } + if (track) pcache.checkpoint(n - 1); const double prompt_ms = std::chrono::duration(Clock::now() - r0).count(); // the verify windows: the first holds the last prompt token alone int64_t p = n - 1; int32_t x = (int32_t) ids[(size_t) (n - 1)]; - std::vector drafts((size_t) S, 0), window((size_t) S), outv((size_t) S); - std::vector dprob((size_t) S, 0.0f); bool first_window = true; int64_t produced_n = 0; const char* finish = "length"; @@ -2017,6 +2101,15 @@ int main(int argc, char** argv) { while (T < S && dprob[(size_t) T - 1] >= (float) o.spec_min_p) ++T; } if (first_window) T = 1; + // Never verify past what this request emits: the committed cells then hold exactly the tokens the + // client saw, so its next turn continues from them. So the window stops at the output limit and + // at a drafted end-of-turn token. + T = (int) std::min(T, max_new - produced_n); + for (int i = 1; i < T; ++i) + if (std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) drafts[(size_t) i - 1]) != o.eos_ids.end()) { + T = i + 1; + break; + } if (p + T > o.max_context) break; window[0] = x; for (int i = 1; i < T; ++i) window[(size_t) i] = drafts[(size_t) i - 1]; @@ -2039,6 +2132,7 @@ int main(int argc, char** argv) { std::printf("ERR %s\n", err.c_str()); return 1; } + if (track) pcache.set(p, window.data(), a + 1); // the committed cells p .. p + a first_window = false; bool eos = false; for (int i = 0; i <= a && produced_n < max_new && !eos; ++i) { @@ -2064,12 +2158,15 @@ int main(int argc, char** argv) { p += a + 1; } const double decode_ms = std::chrono::duration(Clock::now() - d0).count(); - std::printf("DONE %lld %lld %.1f %.1f %s\n", (long long) produced_n, (long long) n, prompt_ms, decode_ms, - finish); + std::printf("DONE %lld %lld %.1f %.1f %s %lld\n", (long long) produced_n, (long long) n, prompt_ms, decode_ms, + finish, (long long) reuse); std::fflush(stdout); - std::fprintf(stderr, "strata serve: %lld prompt tokens in %.0f ms (%.1f tok/s), %lld generated in %.0f ms " - "(%.1f tok/s)\n", (long long) n, prompt_ms, prompt_ms > 0 ? 1000.0 * n / prompt_ms : 0.0, - (long long) produced_n, decode_ms, decode_ms > 0 ? 1000.0 * produced_n / decode_ms : 0.0); + const int64_t fresh = n - reuse; + std::fprintf(stderr, "strata serve: %lld prompt tokens (%lld cached) in %.0f ms (%.1f tok/s), %lld generated " + "in %.0f ms (%.1f tok/s)\n", (long long) n, (long long) reuse, prompt_ms, + prompt_ms > 0 ? 1000.0 * fresh / prompt_ms : 0.0, (long long) produced_n, decode_ms, + decode_ms > 0 ? 1000.0 * produced_n / decode_ms : 0.0); + if (pcache.enabled()) std::fprintf(stderr, "strata serve: prompt cache: %s\n", pcache.summary().c_str()); } return 0; }