diff --git a/control-plane/src/app.rs b/control-plane/src/app.rs index 03a90359..e63f3262 100644 --- a/control-plane/src/app.rs +++ b/control-plane/src/app.rs @@ -43,6 +43,8 @@ pub struct AppState { pub mcp: Option>, /// The resident image encoder (`vision` in the config); `None`: this server cannot read images. pub vision: Option>, + /// The engine's prefix-cache summary for a pool router (`GET /v1/status`, `POST /v1/prefix_match`). + pub prefix_cache: Arc, } impl Default for AppState { @@ -65,6 +67,7 @@ impl Default for AppState { chat_template: None, mcp: None, vision: None, + prefix_cache: Arc::new(Default::default()), } } } @@ -95,6 +98,7 @@ pub fn router(state: AppState) -> Router { .route("/props", get(crate::server_api::props)) .route("/slots", get(crate::server_api::slots)) .route("/v1/status", get(crate::server_api::v1_status)) + .route("/v1/prefix_match", post(crate::server_api::v1_prefix_match)) .route("/mcp", get(crate::server_api::mcp_status)) .route( "/settings", diff --git a/control-plane/src/backend_worker.rs b/control-plane/src/backend_worker.rs index 10ee8fed..b62bd6b1 100644 --- a/control-plane/src/backend_worker.rs +++ b/control-plane/src/backend_worker.rs @@ -72,6 +72,8 @@ pub struct BackendWorkerConfig { /// How long a cancelled generation may take to produce its terminal event before the engine /// is treated as lost. pub cancel_drain_timeout: Duration, + /// Where the engine's prefix-cache summary is copied (health tick and after every request); `None` = not shown. + pub prefix_view: Option>, } type Engine = Arc>>; @@ -307,6 +309,7 @@ pub async fn run_backend_worker( update(&status, WorkerState::Failed, None).await; continue 'attach; } + refresh_prefix_view(&engine, &config).await; } message = control.recv(), if !control_closed => match message { Some(Control::Load { reply }) => { @@ -335,6 +338,7 @@ pub async fn run_backend_worker( { Served::Done => { status.write().await.last_activity = Some(Instant::now()); + refresh_prefix_view(&engine, &config).await; } Served::Shutdown => { update(&status, WorkerState::Stopping, None).await; @@ -352,6 +356,14 @@ pub async fn run_backend_worker( } } +/// Copy the engine's prefix-cache summary into the view the status endpoint reads. +async fn refresh_prefix_view(engine: &Engine, config: &BackendWorkerConfig) { + if let Some(view) = &config.prefix_view { + let summary = on_engine(engine, |backend| backend.prefix_cache_summary()).await.ok().flatten(); + view.set(summary); + } +} + async fn trigger_cancel(engine: &Engine, request_id: &str) { let id = request_id.to_owned(); // The engine may already have finished; "not active" is not an error here. diff --git a/control-plane/src/lib.rs b/control-plane/src/lib.rs index ec7734ea..d744c2e9 100644 --- a/control-plane/src/lib.rs +++ b/control-plane/src/lib.rs @@ -48,6 +48,7 @@ pub mod metrics; pub mod model; pub mod model_pipeline; pub mod models_api; +pub mod prefix_view; pub mod mtp_fetch; pub mod mtp_pack; pub mod native_model; diff --git a/control-plane/src/main.rs b/control-plane/src/main.rs index 8114e165..fe97e42b 100644 --- a/control-plane/src/main.rs +++ b/control-plane/src/main.rs @@ -982,6 +982,7 @@ async fn serve(config_path: Option<&Path>) -> Result<(), Box>, +} + +/// Why a query was refused. +#[derive(Debug, PartialEq, Eq)] +pub enum QueryError { + TooManyHashes, + BadHash, +} + +impl PrefixView { + /// Replace the stored summary (`None`: the engine has no prefix cache, or is unreachable). + pub fn set(&self, summary: Option) { + let value = summary.and_then(|text| serde_json::from_str::(&text).ok()).filter(Value::is_object); + if let Ok(mut latest) = self.latest.write() { + *latest = value.map(|value| (value, Instant::now())); + } + } + + /// The summary for `GET /v1/status`, with its age; `null` when there is none. + pub fn status(&self) -> Value { + let Ok(latest) = self.latest.read() else { return Value::Null }; + match latest.as_ref() { + Some((value, at)) => { + let mut value = value.clone(); + value["age_ms"] = json!(at.elapsed().as_millis() as u64); + value + } + None => Value::Null, + } + } + + /// Tokens of the longest cached prefix of a prompt whose block chain values (hex, one per full block, in order) + /// are `hashes`. `namespace`, when given, must equal the engine's or nothing matches (a different model, block + /// size or chain version). + pub fn prefix_match(&self, namespace: Option<&str>, hashes: &[String]) -> Result { + if hashes.len() > MAX_HASHES { + return Err(QueryError::TooManyHashes); + } + if hashes.iter().any(|h| h.len() != 16 || !h.bytes().all(|b| b.is_ascii_hexdigit())) { + return Err(QueryError::BadHash); + } + let Ok(latest) = self.latest.read() else { return Ok(json!({"available": false, "cached_tokens": 0})) }; + let Some((summary, at)) = latest.as_ref() else { return Ok(json!({"available": false, "cached_tokens": 0})) }; + let engine_namespace = summary["namespace"].as_str().unwrap_or_default(); + let compatible = namespace.is_none_or(|wanted| wanted.eq_ignore_ascii_case(engine_namespace)); + let heads: HashMap<&str, u64> = summary["heads"] + .as_array() + .map(|heads| heads.iter().filter_map(|h| Some((h["h"].as_str()?, h["tokens"].as_u64()?))).collect()) + .unwrap_or_default(); + let cached = if compatible { + hashes.iter().rev().find_map(|h| heads.get(h.to_ascii_lowercase().as_str()).copied()).unwrap_or(0) + } else { + 0 + }; + Ok(json!({ + "available": true, + "compatible": compatible, + "namespace": engine_namespace, + "block_tokens": summary["block_tokens"], + "cached_tokens": cached, + "truncated": summary["truncated"], + "age_ms": at.elapsed().as_millis() as u64, + })) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn summary() -> String { + json!({ + "version": 1, "chain_version": 1, "namespace": "00000000000000ab", "block_tokens": 2048, + "budget_bytes": 1u64 << 30, "used_bytes": 1u64 << 20, "nodes": 2, "blocks": 6, "truncated": false, + "heads": [{"h": "00000000000000a1", "tokens": 4096}, {"h": "00000000000000a2", "tokens": 12288}], + "stats": {"requests": 3, "hits": 1, "shared_hits": 1, "misses": 2, "reused_tokens": 4096, "prompt_tokens": 9000, "admitted": 2, "rejected": 0, "evicted": 0}, + }) + .to_string() + } + fn hashes(list: &[&str]) -> Vec { + list.iter().map(|h| (*h).to_owned()).collect() + } + + #[test] + fn the_deepest_known_head_of_the_chain_wins() { + let view = PrefixView::default(); + assert_eq!(view.status(), Value::Null); + assert_eq!(view.prefix_match(None, &hashes(&["00000000000000a1"])).unwrap()["available"], false); + view.set(Some(summary())); + let status = view.status(); + assert_eq!(status["namespace"], "00000000000000ab"); + assert!(status["age_ms"].is_u64()); + let chain = hashes(&["00000000000000a1", "00000000000000ff", "00000000000000a2", "00000000000000ee"]); + let reply = view.prefix_match(Some("00000000000000AB"), &chain).unwrap(); + assert_eq!((reply["cached_tokens"].as_u64(), reply["block_tokens"].as_u64(), reply["compatible"].as_bool()), (Some(12288), Some(2048), Some(true))); + // a router that only knows the first blocks gets the shallow head + assert_eq!(view.prefix_match(None, &chain[..2]).unwrap()["cached_tokens"], 4096); + // an unknown prefix matches nothing + assert_eq!(view.prefix_match(None, &hashes(&["00000000000000ee"])).unwrap()["cached_tokens"], 0); + assert_eq!(view.prefix_match(None, &[]).unwrap()["cached_tokens"], 0); + } + + #[test] + fn another_namespace_matches_nothing_and_malformed_queries_are_refused() { + let view = PrefixView::default(); + view.set(Some(summary())); + let reply = view.prefix_match(Some("00000000000000cd"), &hashes(&["00000000000000a2"])).unwrap(); + assert_eq!((reply["compatible"].as_bool(), reply["cached_tokens"].as_u64()), (Some(false), Some(0))); + assert_eq!(view.prefix_match(None, &hashes(&["xyz"])), Err(QueryError::BadHash)); + assert_eq!(view.prefix_match(None, &hashes(&["00000000000000gg"])), Err(QueryError::BadHash)); + assert_eq!(view.prefix_match(None, &vec!["00000000000000a1".to_owned(); MAX_HASHES + 1]), Err(QueryError::TooManyHashes)); + } + + #[test] + fn a_missing_or_malformed_summary_clears_the_view() { + let view = PrefixView::default(); + view.set(Some(summary())); + assert!(view.status().is_object()); + view.set(Some("not json".into())); + assert_eq!(view.status(), Value::Null); + view.set(Some(summary())); + view.set(None); + assert_eq!(view.status(), Value::Null); + } +} diff --git a/control-plane/src/server_api.rs b/control-plane/src/server_api.rs index 954cbd3f..e2b9525a 100644 --- a/control-plane/src/server_api.rs +++ b/control-plane/src/server_api.rs @@ -268,6 +268,29 @@ pub async fn slots(State(state): State) -> Response { ) } +/// `POST /v1/prefix_match`: how many tokens of a prompt this runtime's prefix cache holds, for a pool router. +/// Body `{"block_hashes": ["<16 hex>", ...], "namespace": "<16 hex>"}`: the chain values of the prompt's full blocks in order +/// (see `docs/prefix-cache.md`); `namespace` is optional. The answer comes from the engine's last summary. +pub async fn v1_prefix_match(State(state): State, body: Bytes) -> Response { + let parsed: Result = serde_json::from_slice(&body); + let Ok(request) = parsed else { + return reply(StatusCode::BAD_REQUEST, json!({"error": {"message": "the body must be a JSON object", "type": "invalid_request"}})); + }; + let hashes: Option> = request["block_hashes"] + .as_array() + .and_then(|list| list.iter().map(|h| h.as_str().map(str::to_owned)).collect()); + let Some(hashes) = hashes else { + return reply(StatusCode::BAD_REQUEST, json!({"error": {"message": "block_hashes must be an array of hex strings", "type": "invalid_request"}})); + }; + match state.prefix_cache.prefix_match(request["namespace"].as_str(), &hashes) { + Ok(answer) => reply(StatusCode::OK, answer), + Err(error) => reply( + StatusCode::BAD_REQUEST, + json!({"error": {"message": format!("{error:?}: at most {} lowercase-hex 16-digit chain values", crate::prefix_view::MAX_HASHES), "type": "invalid_request"}}), + ), + } +} + /// `GET /v1/status`: what this server is and does, for a client that would rather ask than guess. pub async fn v1_status(State(state): State) -> Response { reply(StatusCode::OK, status_value(&state).await) @@ -319,6 +342,7 @@ async fn status_value(state: &AppState) -> Value { "last_request_at": last_at}, "last_timings": timings, "machine": {"at": now_s(), "gpu": null, "ram": null}, + "prefix_cache": state.prefix_cache.status(), }) } diff --git a/control-plane/tests/backend_worker_http.rs b/control-plane/tests/backend_worker_http.rs index 5f9d1c91..265ee6c8 100644 --- a/control-plane/tests/backend_worker_http.rs +++ b/control-plane/tests/backend_worker_http.rs @@ -125,6 +125,7 @@ impl Stack { stall_timeout: None, attach_retry: Duration::from_millis(20), cancel_drain_timeout: Duration::from_secs(5), + prefix_view: None, }; tune(&mut config); let status = Arc::new(RwLock::new(WorkerStatus::default())); @@ -966,6 +967,7 @@ async fn a_prompt_that_is_not_the_canonical_encoding_is_refused() { stall_timeout: None, attach_retry: Duration::from_millis(20), cancel_drain_timeout: Duration::from_secs(1), + prefix_view: None, }; tokio::spawn(run_backend_worker( Box::new(engine), diff --git a/control-plane/tests/prefix_match_http.rs b/control-plane/tests/prefix_match_http.rs new file mode 100644 index 00000000..afb82dbb --- /dev/null +++ b/control-plane/tests/prefix_match_http.rs @@ -0,0 +1,71 @@ +//! The pool routing surface of the prefix cache over HTTP: `GET /v1/status` carries the engine's summary and +//! `POST /v1/prefix_match` answers from it (`docs/prefix-cache.md`, "Pool protocol"). + +use std::sync::Arc; + +use serde_json::{Value, json}; +use strata_control::{ + app::{AppState, router}, + prefix_view::PrefixView, +}; + +fn summary() -> String { + json!({ + "version": 1, "chain_version": 1, "namespace": "00000000000000ab", "block_tokens": 2048, + "budget_bytes": 1u64 << 30, "used_bytes": 1u64 << 20, "nodes": 2, "blocks": 6, "truncated": false, + "heads": [{"h": "00000000000000a1", "tokens": 4096}, {"h": "00000000000000a2", "tokens": 12288}], + "stats": {"requests": 3, "hits": 1, "shared_hits": 1, "misses": 2, "reused_tokens": 4096, "prompt_tokens": 9000, "admitted": 2, "rejected": 0, "evicted": 0}, + }) + .to_string() +} + +async fn get_json(client: &reqwest::Client, url: &str) -> Value { + serde_json::from_str(&client.get(url).send().await.unwrap().text().await.unwrap()).unwrap() +} + +async fn post_json(client: &reqwest::Client, url: &str, body: Value) -> Value { + let text = client.post(url).body(body.to_string()).send().await.unwrap().text().await.unwrap(); + serde_json::from_str(&text).unwrap() +} + +async fn serve(view: Arc) -> String { + let state = AppState { prefix_cache: view, ..Default::default() }; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, router(state)).await }); + url +} + +#[tokio::test] +async fn status_shows_the_summary_and_prefix_match_answers_from_it() { + let view = Arc::new(PrefixView::default()); + let url = serve(view.clone()).await; + let client = reqwest::Client::new(); + + // no cache reported: null, and an honest "not available" + let status: Value = get_json(&client, &format!("{url}/v1/status")).await; + assert_eq!(status["prefix_cache"], Value::Null); + let none = post_json(&client, &format!("{url}/v1/prefix_match"), json!({"block_hashes": ["00000000000000a1"]})).await; + assert_eq!((none["available"].as_bool(), none["cached_tokens"].as_u64()), (Some(false), Some(0))); + + view.set(Some(summary())); + let status: Value = get_json(&client, &format!("{url}/v1/status")).await; + assert_eq!(status["prefix_cache"]["namespace"], "00000000000000ab"); + assert_eq!(status["prefix_cache"]["heads"].as_array().unwrap().len(), 2); + + let answer = post_json( + &client, + &format!("{url}/v1/prefix_match"), + json!({"namespace": "00000000000000ab", "block_hashes": ["00000000000000a1", "00000000000000ff", "00000000000000a2"]}), + ) + .await; + assert_eq!(answer["cached_tokens"], 12288); + assert_eq!(answer["block_tokens"], 2048); + assert_eq!(answer["compatible"], true); + + // refusals: not JSON, not hashes, a hash of the wrong shape + for body in ["not json", r#"{"block_hashes": 5}"#, r#"{"block_hashes": ["zz"]}"#] { + let response = client.post(format!("{url}/v1/prefix_match")).body(body.to_owned()).send().await.unwrap(); + assert_eq!(response.status().as_u16(), 400, "{body}"); + } +} diff --git a/crates/backend-api/src/lib.rs b/crates/backend-api/src/lib.rs index efea2370..c3531ec5 100644 --- a/crates/backend-api/src/lib.rs +++ b/crates/backend-api/src/lib.rs @@ -257,6 +257,12 @@ pub trait Backend: Send { ) -> Result; fn cancel(&mut self, request_id: &str) -> Result<(), BackendError>; fn unload(&mut self, model: LoadedModel) -> Result<(), BackendError>; + /// JSON summary of the backend's cross-session prefix cache for a pool router (`docs/prefix-cache.md`, + /// "Pool protocol"): the checkpoint heads it holds as block-hash-chain values with the tokens each covers. + /// `None`: no such cache (the default), or nothing to report yet. Cheap and non-blocking by contract. + fn prefix_cache_summary(&self) -> Option { + None + } } #[derive(Clone, Debug, Eq, PartialEq)] diff --git a/crates/backend-api/src/scripted.rs b/crates/backend-api/src/scripted.rs index 51243e42..b162824d 100644 --- a/crates/backend-api/src/scripted.rs +++ b/crates/backend-api/src/scripted.rs @@ -127,6 +127,8 @@ struct Shared { cancels: Mutex>, loads: Mutex>, active: Mutex>, + /// What `prefix_cache_summary` reports (a pool summary as JSON). + prefix_summary: Mutex>, } struct ActiveGeneration { @@ -160,6 +162,7 @@ impl ScriptedEngine { cancels: Mutex::new(Vec::new()), loads: Mutex::new(Vec::new()), active: Mutex::new(None), + prefix_summary: Mutex::new(None), }); ( Self { @@ -209,6 +212,11 @@ impl ScriptedHandle { self.shared.loads.lock().unwrap().clone() } + /// The engine reports this prefix-cache summary (JSON) from now on; `None` = it has no such cache. + pub fn set_prefix_summary(&self, summary: Option) { + *self.shared.prefix_summary.lock().unwrap() = summary; + } + pub fn is_ready(&self) -> bool { self.shared.ready.load(Ordering::Acquire) } @@ -256,6 +264,10 @@ impl Backend for ScriptedEngine { } } + fn prefix_cache_summary(&self) -> Option { + self.shared.prefix_summary.lock().unwrap().clone() + } + fn capabilities(&self) -> BackendCapabilities { let d = &self.shared.descriptor; BackendCapabilities { diff --git a/crates/cuda-driver/src/qsa_mapped_journal.rs b/crates/cuda-driver/src/qsa_mapped_journal.rs index 6f677219..13bb8827 100644 --- a/crates/cuda-driver/src/qsa_mapped_journal.rs +++ b/crates/cuda-driver/src/qsa_mapped_journal.rs @@ -285,6 +285,54 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx>{ } } +/// Prefix-cache transfer of the host K/V image (`docs/prefix-cache.md`). The host image is the authority for every +/// reachable cell (every writer writes it), so a prefix parked in host RAM is a byte copy of whole 4-cell pages +/// and putting it back is a byte copy plus one invalidation of the VRAM resident window. +/// +/// A span of `n` pages is stored run-major, exactly like the image itself: `[K codes n*2048 | V codes n*2048 | +/// K scales n*64 | V scales n*64]` = `n * HOST_PAGE_BYTES` bytes. +impl<'ctx> OriginalQsaMappedJournal<'ctx>{ + /// Bytes of one 4-cell page of the host image (1056 B per cell). + pub const HOST_PAGE_BYTES:usize=QSA_PROMPT_HOST_PAGE_BYTES; + /// Copy the pages `first_page..first_page + pages` of the reachable prefix out of the host image. + pub fn export_pages(&self,first_page:usize,pages:usize,out:&mut Vec)->Result<()>{ + self.validate_context(self.owner.context)?; + if pages==0||first_page.checked_add(pages).is_none_or(|e|e>self.end/4){return Err(Error::InvalidQwenShape)} + // the GPU wrote these cells through the mapped alias; every public writer drains, this keeps the read ordered after it + self.owner.context.synchronize()?; + out.clear();out.try_reserve_exact(pages*Self::HOST_PAGE_BYTES).map_err(|_|Error::HostAllocation)?;out.resize(pages*Self::HOST_PAGE_BYTES,0); + let m=self.owner.mapped.as_ref().ok_or(Error::ContextPoisoned)?;let offsets=super::offsets()?;let mut at=0; + for(i,&page)in super::PAGE.iter().enumerate(){let n=pages*page;m.read(offsets[i]+first_page*page,&mut out[at..at+n])?;at+=n;} + Ok(()) + } + /// Put parked spans `(first_page, bytes)` back into the host image and make the journal's reachable prefix end at + /// `end` cells: the cells below `end` that no span names must already hold the prefix (the caller's live-prefix + /// bookkeeping). Any written cell may have a stale copy in the VRAM resident window, so the resolver is reset + /// (as `QsaPromptKv::restore` does); with no span nothing is written and nothing is reset. The epoch does not + /// change: prefixes minted before are fenced by the new coverage, exactly as after `rollback`. + pub fn import_pages(&mut self,w:&mut NativeBatchWorkspace<'ctx>,spans:&[(usize,&[u8])],end:usize)->Result{ + self.validate_context(self.owner.context)?;w.validate_context(self.owner.context)?; + if end>crate::serving_context::geometry().cells(){return Err(Error::InvalidQwenShape)} + let page_limit=crate::serving_context::geometry().pages(); + for(first,bytes)in spans{ + if bytes.is_empty()||bytes.len()%Self::HOST_PAGE_BYTES!=0||first.checked_add(bytes.len()/Self::HOST_PAGE_BYTES).is_none_or(|e|e>page_limit)||(first+bytes.len()/Self::HOST_PAGE_BYTES)*4>end.div_ceil(4)*4{return Err(Error::InvalidQwenShape)} + } + // no CPU host write may race a stream use of the old cells + self.owner.context.synchronize().map_err(|e|{self.failed=true;e})?; + if !spans.is_empty(){ + let offsets=super::offsets()?;let m=self.owner.mapped.as_mut().ok_or(Error::ContextPoisoned)?; + for(first,bytes)in spans{let pages=bytes.len()/Self::HOST_PAGE_BYTES;let mut at=0; + for(i,&page)in super::PAGE.iter().enumerate(){let n=pages*page;m.write(offsets[i]+first*page,&bytes[at..at+n]).map_err(|e|{self.failed=true;e})?;at+=n;}} + let table=self.owner.pools.table()?; + self.owner.resolver.as_mut().ok_or(Error::ContextPoisoned)?.reset(w,table).map_err(|e|{self.failed=true;e})?; + self.resolver_ready=true; + } + self.owner.current=None;self.owner.mapped_current=None; + self.coverage.end.set(self.coverage.end.get().min(end));self.coverage=Rc::new(Coverage{end:Cell::new(end)});self.end=end; + Ok(self.prefix()) + } +} + /// Model-free GPU proof of the one-token-prompt fix: a journal no prompt append has touched refuses the window /// capture until `ensure_resolver`, which initialises the resolver WITHOUT changing the epoch (prefixes minted /// before stay valid, unlike `reset`) and is idempotent. @@ -326,3 +374,105 @@ mod resolver_tests { context.close().unwrap(); } } + +/// Model-free GPU proof of the prefix-cache transfer (`docs/prefix-cache.md`): parked host K/V pages and index rows +/// written back into a journal / index come out byte for byte, the ends and coverage follow, the resolver is reset +/// when cells were written, and a span can be written back in pieces. +#[cfg(all(test, feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))] +mod parked_tests { + use super::*; + use crate::OriginalQsaResidentIndex; + + fn bytes(seed: u64, n: usize) -> Vec { + let mut state = seed; + (0..n) + .map(|_| { + state = state.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (state >> 56) as u8 + }) + .collect() + } + + /// The run-major bytes of pages `from..to` of a run-major span covering pages `0..pages`. + fn sub_span(all: &[u8], pages: usize, from: usize, to: usize) -> Vec { + let mut out = Vec::new(); + let mut at = 0; + for page in super::PAGE { + out.extend_from_slice(&all[at + from * page..at + to * page]); + at += pages * page; + } + out + } + + #[test] + #[ignore = "GPU: one bounded context, no model"] + fn parked_pages_and_index_rows_round_trip_through_the_owners() { + let driver = crate::Driver::load().unwrap(); + let device = driver.device(0).unwrap(); + let context = device.create_context(4 << 30).unwrap(); + { + let mut ws = context.native_batch_workspace().unwrap(); + let mut journal = context.qsa_prompt_kv().unwrap().into_original_mapped_journal().unwrap(); + let mut index = context.original_qsa_resident_index().unwrap(); + let (cells, pages) = (2048usize, 512usize); + let kv = bytes(1, pages * QSA_PROMPT_HOST_PAGE_BYTES); + + // nothing reachable yet: nothing to export + let mut out = Vec::new(); + assert!(journal.export_pages(0, 1, &mut out).is_err()); + // write everything back at once + let prefix = journal.import_pages(&mut ws, &[(0, &kv)], cells).unwrap(); + assert_eq!((journal.next_position(), prefix.next_position()), (cells, cells)); + journal.validate_prefix(&prefix).unwrap(); + journal.export_pages(0, pages, &mut out).unwrap(); + assert_eq!(out, kv, "the whole span comes back byte for byte"); + // a sub-range exports the matching sub-span + journal.export_pages(100, 50, &mut out).unwrap(); + assert_eq!(out, sub_span(&kv, pages, 100, 150)); + // beyond the reachable end is refused + assert!(journal.export_pages(500, 13, &mut out).is_err()); + + // roll back, then write it back in two pieces (the second at an offset), as a restore of a partly live buffer does + let empty = journal.empty_prefix(); + let _ = empty; + journal.import_pages(&mut ws, &[], 1000).unwrap(); + assert_eq!(journal.next_position(), 1000, "no span: only the end moves (the cells are the caller's claim)"); + let head = sub_span(&kv, pages, 0, 256); + let tail = sub_span(&kv, pages, 256, 512); + let prefix = journal.import_pages(&mut ws, &[(0, &head), (256, &tail)], cells).unwrap(); + journal.validate_prefix(&prefix).unwrap(); + journal.export_pages(0, pages, &mut out).unwrap(); + assert_eq!(out, kv, "two pieces make the same image"); + // malformed spans are refused and touch nothing + assert!(journal.import_pages(&mut ws, &[(0, &kv[..100])], cells).is_err()); + assert!(journal.import_pages(&mut ws, &[(pages, &head)], cells).is_err(), "a span beyond the end"); + journal.export_pages(0, pages, &mut out).unwrap(); + assert_eq!(out, kv); + + // the index: pooled rows below end/4 plus a 2564-byte tail + let rows = bytes(2, (cells / 4) * OriginalQsaResidentIndex::ROW_BYTES); + let tail_bytes = bytes(3, OriginalQsaResidentIndex::TAIL_BYTES); + assert!(index.export_rows(0, 1, &mut out).is_err(), "an empty image has no rows"); + let checkpoint = index.import(&mut ws, &[(0, &rows)], &tail_bytes, cells).unwrap(); + assert_eq!((index.next_position(), checkpoint.next_position()), (cells, cells)); + index.validate_checkpoint(&checkpoint).unwrap(); + index.export_rows(0, cells / 4, &mut out).unwrap(); + assert_eq!(out, rows, "the pooled rows come back"); + assert_eq!(index.export_tail(&checkpoint).unwrap(), tail_bytes, "the tail round-trips through the image"); + // partial write-back: only the second half of the rows, on top of an image that already holds the first + let second = rows[(cells / 8) * OriginalQsaResidentIndex::ROW_BYTES..].to_vec(); + let checkpoint2 = index.import(&mut ws, &[(cells / 8, &second)], &tail_bytes, cells).unwrap(); + index.export_rows(0, cells / 4, &mut out).unwrap(); + assert_eq!(out, rows); + assert_eq!(index.export_tail(&checkpoint2).unwrap(), tail_bytes); + // a restore to the minted checkpoint works like any other + index.restore(&mut ws, &checkpoint2).unwrap(); + assert!(index.import(&mut ws, &[(cells / 4, &second)], &tail_bytes, cells).is_err(), "rows beyond end / 4 are refused"); + + journal.close().unwrap(); + drop(index); + drop(ws); + } + context.close().unwrap(); + } +} diff --git a/crates/cuda-driver/src/qsa_prompt_host_ffi.rs b/crates/cuda-driver/src/qsa_prompt_host_ffi.rs index f5f7ac83..e257b6fa 100644 --- a/crates/cuda-driver/src/qsa_prompt_host_ffi.rs +++ b/crates/cuda-driver/src/qsa_prompt_host_ffi.rs @@ -118,6 +118,14 @@ mod enabled { } Ok(()) } + /// Copy `out.len()` bytes of the mapped host image starting at `o` (the prefix-cache export of K/V cells). + pub(crate) fn read(&self, o: usize, out: &mut [u8]) -> Result<()> { + let p = self.range(o, out.len())?; + unsafe { + std::ptr::copy_nonoverlapping(p as *const u8, out.as_mut_ptr(), out.len()); + } + Ok(()) + } pub(crate) fn close(&mut self) -> Result<()> { if let Some(p) = self.host { check("cuMemFreeHost", unsafe { (self.free)(p as *mut c_void) })?; @@ -164,6 +172,9 @@ impl MappedAllocation { pub(crate) fn address(&self, _: usize, _: usize) -> Result { Err(Error::UnsupportedPlatform) } + pub(crate) fn read(&self, _: usize, _: &mut [u8]) -> Result<()> { + Err(Error::UnsupportedPlatform) + } pub(crate) fn write(&mut self, _: usize, _: &[u8]) -> Result<()> { Err(Error::UnsupportedPlatform) } diff --git a/crates/cuda-driver/src/qsa_resident_index.rs b/crates/cuda-driver/src/qsa_resident_index.rs index 511da200..ffb54c87 100644 --- a/crates/cuda-driver/src/qsa_resident_index.rs +++ b/crates/cuda-driver/src/qsa_resident_index.rs @@ -122,6 +122,41 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx>{ } } impl Drop for OriginalQsaResidentIndex<'_>{fn drop(&mut self){let _=self.close_inner();}} +/// Prefix-cache transfer of the index image (`docs/prefix-cache.md`): the pooled key rows (512 B per 4-cell block) +/// below the checkpoint's end are plain device bytes, and the checkpoint carries the rest (the running pooling state +/// and the tail row). A parked prefix is therefore `rows` bytes plus `CHECKPOINT_BYTES` of tail, and importing one +/// mints a checkpoint of THIS image's lineage (a parked one belongs to no lineage). +impl<'ctx> OriginalQsaResidentIndex<'ctx>{ + /// Bytes of one pooled key row (four cells). + pub const ROW_BYTES:usize=512; + /// Bytes of a checkpoint's tail (`export_tail`). + pub const TAIL_BYTES:usize=CHECKPOINT_BYTES; + /// Copy the pooled key rows `first_row..first_row + rows` (all below the current end / 4) to the host. + pub fn export_rows(&self,first_row:usize,rows:usize,out:&mut Vec)->Result<()>{ + self.validate()?;if self.in_flight||self.unpublished{return Err(Error::InvalidQwenShape)} + if rows==0||first_row.checked_add(rows).is_none_or(|e|e>self.end/4){return Err(Error::InvalidQwenShape)} + out.clear();out.try_reserve_exact(rows*Self::ROW_BYTES).map_err(|_|Error::HostAllocation)?;out.resize(rows*Self::ROW_BYTES,0); + self.image[0].as_ref().ok_or(Error::ContextPoisoned)?.copy_to_range(first_row*Self::ROW_BYTES,out) + } + /// The bytes of a checkpoint of this lineage: everything `import` needs besides the rows below its end. + pub fn export_tail(&self,s:&OriginalQsaIndexCheckpoint<'ctx>)->Result>{ + self.validate()?;self.validate_checkpoint(s)?; + let mut out=vec![0u8;CHECKPOINT_BYTES];s.0.bytes.copy_to_range(0,&mut out)?;Ok(out) + } + /// Write the parked spans `(first_row, bytes)` and the tail `tail` (exported at position `end`), set the image's end + /// and return a fresh checkpoint of it. The rows below `end / 4` that no span names must already hold the prefix. + pub fn import(&mut self,ws:&mut NativeBatchWorkspace<'ctx>,spans:&[(usize,&[u8])],tail:&[u8],end:usize)->Result>{ + self.validate()?;if self.in_flight{return Err(Error::InvalidQwenShape)} + if tail.len()!=CHECKPOINT_BYTES||end>crate::serving_context::geometry().cells(){return Err(Error::InvalidQwenShape)} + for(first,bytes)in spans{if bytes.is_empty()||bytes.len()%Self::ROW_BYTES!=0||first+bytes.len()/Self::ROW_BYTES>end/4{return Err(Error::InvalidQwenShape)}} + for(first,bytes)in spans{self.image[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(first*Self::ROW_BYTES,bytes)?;} + let mut b=self.checkpoint_buffer()?; + if let Err(e)=b.copy_from(tail){if self.context.is_poisoned(){std::mem::forget(b)}else{let _=b.release();}return Err(e)} + let parked=OriginalQsaIndexCheckpoint(Rc::new(Saved{origin:self.origin.clone(),epoch:self.epoch,coverage:Rc::new(Coverage{end:Cell::new(end)}),end,bytes:b,pool:Rc::downgrade(&self.pool)})); + self.restore_private(ws,&parked)?;drop(parked); + self.save(ws) + } +} /// Actual pending index batch. Forgetting it leaves owner in-flight/refusing new /// use; dropping without an explicit replay likewise refuses publication. pub struct OriginalQsaIndexBatch<'index,'weights,'ctx>{pub(super) owner:&'index mut OriginalQsaResidentIndex<'ctx>,pub(super) start:OriginalQsaIndexCheckpoint<'ctx>,pub(super) raw:Option>,pub(super) gamma:&'weights DeviceBuffer<'ctx>,pub(super) rows:usize} diff --git a/crates/leleka-runtime/src/backend.rs b/crates/leleka-runtime/src/backend.rs index 19bcd1ee..8279691b 100644 --- a/crates/leleka-runtime/src/backend.rs +++ b/crates/leleka-runtime/src/backend.rs @@ -4,7 +4,7 @@ pub(crate) mod original_prompt; #[path = "backend_original_serve.rs"] mod original_serve; -pub use original_serve::{ExpertSource, OriginalServeChoice, OriginalServeMode, OriginalServeOptions}; +pub use original_serve::{ExpertSource, OriginalServeChoice, OriginalServeMode, OriginalServeOptions, PrefixCacheOptions}; use crate::experimental::{self as experimental_modes, ExperimentalConfig}; use crate::model_binding::kar_expert_source::KarExpertSource; pub use crate::model_binding::kar_expert_source::{ @@ -761,6 +761,12 @@ impl Backend for Proxy { supports_tool_call_streaming: false, } } + fn prefix_cache_summary(&self) -> Option { + if !self.shared.ready.load(Ordering::Acquire) || self.shared.shutdown.load(Ordering::Acquire) { + return None; + } + original_serve::published_prefix_summary() + } fn load( &mut self, model: ModelDescriptor, @@ -3475,6 +3481,9 @@ mod singleload_proof; #[path = "backend_original_serve_smoke.rs"] mod original_serve_smoke; #[cfg(all(test, target_os = "linux", target_arch = "x86_64"))] +#[path = "backend_original_serve_prefix_smoke.rs"] +mod original_serve_prefix_smoke; +#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))] #[path = "backend_original_serve_laptop.rs"] mod original_serve_laptop; #[cfg(all(test, target_os = "linux", target_arch = "x86_64"))] diff --git a/crates/leleka-runtime/src/backend_original_prompt.rs b/crates/leleka-runtime/src/backend_original_prompt.rs index e874ba63..bf53fe40 100644 --- a/crates/leleka-runtime/src/backend_original_prompt.rs +++ b/crates/leleka-runtime/src/backend_original_prompt.rs @@ -19,6 +19,10 @@ pub(crate) struct PromptOptions { pub force_batched: bool, pub verify_width: usize, pub auto_max: usize, + /// Prefix cache: every batched chunk ends on a multiple of `grid` (0 = off, the Original's cuts). The state + /// after such a chunk is a pure function of the tokens before it, whichever request read them, so it can be + /// shared between sessions and a request resumed from it reads exactly the chunks a full read would. + pub grid: usize, } impl PromptOptions { pub(crate) const fn original_mode17(context_tokens: usize) -> Self { @@ -31,6 +35,7 @@ impl PromptOptions { force_batched: false, verify_width: 4, auto_max: 8192, + grid: 0, } } } @@ -130,6 +135,7 @@ impl<'a> PromptPlan<'a> { || !(1..=4).contains(&options.verify_width) || embedding_rows.is_some_and(|rows| rows.len() != prompt.len()) || reread_to.is_some_and(|end| end == 0 || end > resume) + || (options.grid != 0 && (options.grid % 256 != 0 || options.grid > admitted_capacity)) { return Err(PlanError::InvalidInput); } @@ -193,7 +199,10 @@ impl Iterator for PromptPlan<'_> { PromptPath::Verify => self.options.verify_width, PromptPath::FinalSeed => unreachable!("seed is outside conditioning segments"), }; - let count = width.min(self.end - self.position); + let mut count = width.min(self.end - self.position); + if self.options.grid != 0 && matches!(path, PromptPath::Batched { .. }) { + count = count.min(self.options.grid - self.position % self.options.grid); + } let first = self.position; self.position += count; return Some(PromptAction { @@ -461,3 +470,60 @@ mod tests { assert!(r.log.is_empty()); } } + +#[cfg(test)] +mod grid_tests { + use super::*; + + fn cuts(tokens: &[u32], resume: usize, o: PromptOptions, capacity: usize) -> Vec<(usize, usize)> { + PromptPlan::new(tokens, resume, None, None, o, capacity) + .unwrap() + .filter(|a| a.path != PromptPath::FinalSeed) + .map(|a| (a.first, a.count)) + .collect() + } + + #[test] + fn a_grid_puts_every_chunk_end_but_the_last_on_a_multiple_and_a_resume_on_the_grid_reads_the_same_chunks() { + let o = PromptOptions { grid: 512, prompt_cache: false, turn_token: None, root_min: 0, force_batched: true, ..PromptOptions::original_mode17(262144) }; + let mut tokens = vec![7u32; 5000]; + // turn tokens must not add cuts (the prefix cache has no turn/root cuts) + tokens[300] = 248_045; + tokens[3000] = 248_045; + for capacity in [512, 1024, 2048, 8192] { + let full = cuts(&tokens, 0, o, capacity); + let (last, rest) = full.split_last().unwrap(); + assert!(rest.iter().all(|(first, count)| (first + count) % 512 == 0), "{capacity}: {full:?}"); + assert_eq!(last.0 + last.1, 4999); + assert!(full.iter().all(|(_, count)| *count <= capacity.min(512))); + // contiguous + assert!(full.windows(2).all(|w| w[0].0 + w[0].1 == w[1].0)); + // resuming on any grid point reads exactly the remaining chunks of the full read + for resume in [512usize, 1024, 2560, 4608] { + let read = cuts(&tokens, resume, o, capacity); + let expected: Vec<_> = full.iter().copied().filter(|(first, _)| *first >= resume).collect(); + assert_eq!(read, expected, "capacity {capacity} resume {resume}"); + } + } + // a prompt that ends inside a block has a short last chunk, and a short prompt a single one + assert_eq!(cuts(&tokens[..700], 0, o, 2048), vec![(0, 512), (512, 187)]); + assert_eq!(cuts(&tokens[..100], 0, o, 2048), vec![(0, 99)]); + } + + #[test] + fn a_grid_must_be_a_multiple_of_256_within_the_admitted_capacity() { + let tokens = vec![1u32; 3000]; + for (grid, capacity, ok) in [(0, 1024, true), (256, 1024, true), (1024, 1024, true), (2048, 1024, false), (300, 2048, false), (512, 256, false)] { + let o = PromptOptions { grid, force_batched: true, ..PromptOptions::original_mode17(262144) }; + assert_eq!(PromptPlan::new(&tokens, 0, None, None, o, capacity).is_ok(), ok, "grid {grid} capacity {capacity}"); + } + } + + #[test] + fn grid_zero_is_the_originals_plan() { + let o = PromptOptions { force_batched: true, ..PromptOptions::original_mode17(262144) }; + let tokens = vec![3u32; 5000]; + assert_eq!(cuts(&tokens, 0, o, 2048), vec![(0, 2048), (2048, 2048), (4096, 903)]); + assert_eq!(cuts(&tokens, 1000, o, 2048), vec![(1000, 2048), (3048, 1951)]); + } +} diff --git a/crates/leleka-runtime/src/backend_original_serve.rs b/crates/leleka-runtime/src/backend_original_serve.rs index 3d139e58..34f32306 100644 --- a/crates/leleka-runtime/src/backend_original_serve.rs +++ b/crates/leleka-runtime/src/backend_original_serve.rs @@ -65,6 +65,24 @@ impl ExpertSource { } } +/// The prefix cache's pool summary (JSON), published by the owner thread after every request and read by whichever thread answers +/// a status query. One backend per process, so one cell. +static PREFIX_SUMMARY: std::sync::Mutex> = std::sync::Mutex::new(None); + +/// The last published pool summary of the prefix cache, if the cache is on. +pub(super) fn published_prefix_summary() -> Option { + PREFIX_SUMMARY.lock().ok().and_then(|cell| cell.clone()) +} + +/// `--prefix-cache-mib` / `--prefix-cache-block`: the cross-session prefix cache (`docs/prefix-cache.md`). +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct PrefixCacheOptions { + /// Host-RAM budget in bytes: `None` = auto from the memory available when the stack opens, `Some(0)` = off. + pub budget_bytes: Option, + /// Tokens per block and per chunk-grid step (a multiple of 256, at most the prefill capacity); 0 = the prefill capacity. + pub block_tokens: usize, +} + /// Operator choices of the Original path. Nothing here enters an RPC. #[derive(Clone, Debug)] pub struct OriginalServeOptions { @@ -91,6 +109,9 @@ pub struct OriginalServeOptions { pub turn_token: Option, /// `--expert-source resident|mapped`: how the routed-expert bank is admitted before the stack opens. pub expert_source: ExpertSource, + /// `--prefix-cache-mib`: the cross-session prefix cache. `None` leaves the conversation cache above in charge; + /// `Some` replaces it (the prompt is then read on a token grid, `docs/prefix-cache.md`). + pub prefix_cache: Option, } impl Default for OriginalServeOptions { fn default() -> Self { @@ -106,6 +127,7 @@ impl Default for OriginalServeOptions { prompt_cache_root: 2048, turn_token: Some(crate::qwen_forward::original_serve_stack::TURN_TOKEN), expert_source: ExpertSource::default(), + prefix_cache: None, } } } @@ -114,7 +136,8 @@ impl OriginalServeOptions { let capacity_ok = self.prefill_capacity.is_none_or(|c| [256, 512, 1024, 2048, 3072, 4096, 6144, 8192].contains(&c)); let directory_ok = self.mtp_rt_directory.as_ref().is_none_or(|d| !d.as_os_str().is_empty()); let cache_ok = self.prompt_cache <= 64 && self.turn_token.is_none_or(|t| t < 248_320); - if !capacity_ok || !directory_ok || !cache_ok || !self.spec_min_p.is_finite() || !(0.0..=1.0).contains(&self.spec_min_p) { + let prefix_ok = self.prefix_cache.as_ref().is_none_or(|p| p.block_tokens % 256 == 0 && p.block_tokens <= 8192); + if !capacity_ok || !directory_ok || !cache_ok || !prefix_ok || !self.spec_min_p.is_finite() || !(0.0..=1.0).contains(&self.spec_min_p) { return Err(super::invalid("invalid Original serve options")); } Ok(()) @@ -234,7 +257,7 @@ mod runner { GenerationFailure, GenerationSink, GenerationTerminal, LoadPhase, LoadedModel, ModelBinding, Reply, Shared, Tokenizer, Usage, Utf8Pending, BACKPRESSURE_TIMEOUT, GENERATION_TIMEOUT, QUEUE, }; - use super::{context_fits, OriginalServeOptions}; + use super::{context_fits, OriginalServeOptions, PREFIX_SUMMARY}; use crate::qwen_forward::{ contract::Error as ForwardError, original_serve_engine::ServeStop, @@ -280,6 +303,20 @@ mod runner { BackendError { code, message, retryable: false } } + /// Number of checkpoint heads a pool summary carries. + const PREFIX_SUMMARY_HEADS: usize = 512; + + /// Hand the prefix cache's summary to the threads that answer status queries (the stack stays on this thread). + fn publish_prefix_summary(stack: &OriginalServeStack<'_, '_>, _shared: &Shared) { + if let Some(summary) = stack.prefix_summary(PREFIX_SUMMARY_HEADS) { + if let Ok(json) = serde_json::to_string(&summary) { + if let Ok(mut cell) = PREFIX_SUMMARY.lock() { + *cell = Some(json); + } + } + } + } + fn emit_event( sink: &GenerationSink, cancelled: &dyn Fn() -> bool, @@ -441,6 +478,18 @@ mod runner { config.kv_resident = cells; } config.conversation = options.conversation(); + if let Some(prefix) = options.prefix_cache.as_ref() { + use crate::qwen_forward::original_serve_stack::{PrefixBudget, PrefixConfig}; + config.prefix = Some(PrefixConfig { + budget: match prefix.budget_bytes { + None => PrefixBudget::Auto, + Some(0) => PrefixBudget::Off, + Some(bytes) => PrefixBudget::Bytes(bytes), + }, + block_tokens: prefix.block_tokens, + ..PrefixConfig::auto() + }); + } // The VRAM expert tier (off unless LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS / _EXPERT_PROFILE select it). config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() .map_err(|_| load_failure(LoadPhase::OriginalStack, invalid("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting")))?; @@ -449,6 +498,7 @@ mod runner { let _ = writeln!(std::io::stderr().lock(), "leleka-serve open: {}", failure.describe()); load_failure(LoadPhase::OriginalStack, open_error(&failure)) })?; + publish_prefix_summary(&stack, shared); let mut stack = Some(stack); if shared.shutdown.load(Ordering::Acquire) { if let Some(stack) = stack.take() { @@ -530,6 +580,7 @@ mod runner { }, }; let _ = emit_terminal(&sink, terminal); + publish_prefix_summary(owner, shared); if let Some(lost) = owner.health() { // a lost physical owner cannot be repaired in place: stop serving, keep the process // alive for an orderly unload diff --git a/crates/leleka-runtime/src/backend_original_serve_prefix_smoke.rs b/crates/leleka-runtime/src/backend_original_serve_prefix_smoke.rs new file mode 100644 index 00000000..73f0014b --- /dev/null +++ b/crates/leleka-runtime/src/backend_original_serve_prefix_smoke.rs @@ -0,0 +1,447 @@ +//! Opt-in GPU measurement and proof of the cross-session prefix cache (`docs/prefix-cache.md`) on the real model. +//! +//! One process loads the pinned model once and serves a scripted workload of agent-shaped sessions, interleaved: +//! every session starts with the same system + tools + repository prefix, then has its own task and a growing history +//! of tool calls and tool outputs; the requests of the sessions alternate (`A1 B1 C1 A2 B2 C2 ...`) the way a pool of +//! agents behind one runtime does. Per request it prints one `PFX` line: prompt tokens, tokens reused, tokens read +//! again, TTFT (first committed round), prompt and decode milliseconds, decode rate, host memory. +//! +//! Inputs are the other serve smokes' (`LELEKA_STRA169_*`, `LELEKA_ORIGINAL_SERVE_*` incl. the expert tier) plus: +//! * `LELEKA_PFX_SMOKE=yes` opt-in; +//! * `LELEKA_PFX_MODE` `legacy` (the conversation cache of the Original: 6 checkpoints, one live buffer) or +//! `prefix` (the prefix cache; default). `off` = no cache at all; +//! * `LELEKA_PFX_SCENARIO` `grid` (default: `SESSIONS` x `TURNS`, fixed sizes) or `agent` (a synthetic +//! Codex-like trace: random interleaving, heavy-tailed tool outputs, growth from +//! `START` to `END` tokens); +//! * `LELEKA_PFX_SHARED` (8000) tokens of the common prefix; `_SESSIONS` (3); `_TURNS` (3) requests per session; +//! `_START` (2000) private tokens of the first request; `_GROW` (2500) tokens added per turn (`grid`); +//! `_END` (40000) total tokens of a session's last request (`agent`); `_MAX_NEW` (16); +//! * `LELEKA_PFX_VERIFY` `none` | `last` (the last request of every session) | `every` (every request that +//! was served from the cache): the same prompt is read again with the cache bypassed +//! (a full read on the same chunk grid) and the greedy ids must be identical; +//! * `LELEKA_PFX_CANCEL=yes` after the workload: a request cancelled during the prefill, one cancelled after the +//! first round, then the same prompt served and verified; +//! * `LELEKA_PFX_MIB` (`auto` | N | 0) budget of the prefix cache; `LELEKA_PFX_BLOCK` block/grid tokens (0 = auto); +//! * `LELEKA_PFX_CAPACITY` (2048) prompt chunk; `LELEKA_ORIGINAL_SERVE_MAX_CONTEXT` (262144), +//! `LELEKA_ORIGINAL_SERVE_KV_RESIDENT` (20480). +//! +//! * `LELEKA_PFX_LAPTOP=yes` the laptop profile (docs/laptop-profile.md): the KAR archive as a read-only file +//! (`LELEKA_LAPTOP_KAR_FILE`, else the sealed memfd), the routed experts mapped from the shard instead of copied into RAM, +//! `LELEKA_LAPTOP_CPU_WORKERS` (7), the `auto` prefix budget of the laptop profile, `LELEKA_LAPTOP_CELLS` (a smaller process geometry). +//! +//! Run: `cargo test -p leleka-runtime -- --ignored --exact backend::original_serve_prefix_smoke::original_serve_prefix_cache_smoke`. +use super::*; +use crate::qwen_forward::{ + original_serve_request::{ServeError, ServeRequest}, + original_serve_stack::{OriginalServeStack, PrefixBudget, PrefixConfig, StackConfig}, +}; +use crate::qwen_forward::original_serve_stack::dbg_el; +use std::env; + +fn required_path(name: &str) -> PathBuf { + env::var_os(name).map(PathBuf::from).unwrap_or_else(|| panic!("missing operator-owned smoke input {name}")) +} +fn number(name: &str, default: usize) -> usize { + env::var(name).ok().map(|v| v.parse().unwrap_or_else(|_| panic!("{name} must be a count"))).unwrap_or(default) +} +fn text(name: &str, default: &str) -> String { + env::var(name).unwrap_or_else(|_| default.to_owned()) +} + +/// A small deterministic generator (the workload must be identical across runs and modes). +struct Rng(u64); +impl Rng { + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + self.0 >> 11 + } + fn unit(&mut self) -> f64 { + (self.next() % 1_000_000) as f64 / 1_000_000.0 + } +} + +fn mem_available_mib() -> u64 { + crate::conversation::memory::available_memory().map_or(0, |b| b >> 20) +} +fn rss_mib() -> u64 { + std::fs::read_to_string("/proc/self/status") + .ok() + .and_then(|s| s.lines().find_map(|l| l.strip_prefix("VmRSS:")?.split_whitespace().next()?.parse::().ok())) + .map_or(0, |kb| kb >> 10) +} + +/// Deterministic text of `kind` encoded to exactly `tokens` ids (code-like or log-like lines). +fn filler(tokenizer: &Tokenizer, rng: &mut Rng, kind: u8, tokens: usize) -> Vec { + let mut ids: Vec = Vec::with_capacity(tokens + 256); + let mut line = 0usize; + while ids.len() < tokens { + let mut chunk = String::new(); + for _ in 0..24 { + let (a, b, c) = (rng.next() % 997, rng.next() % 64, rng.next() % 9973); + match kind { + 0 => chunk.push_str(&format!( + " let v{b} = table[{a}].checked_add({c}).ok_or(Error::Overflow)?; // step {line}\n if v{b} > limit_{a} {{ return Err(Error::Range({b})); }}\n" + )), + _ => chunk.push_str(&format!( + "[{:02}:{:02}:{:02}] worker-{b} ok job={c} bytes={} path=src/mod_{a}/file_{line}.rs\n", + a % 24, b % 60, c % 60, a * 31 + c + )), + } + line += 1; + } + ids.extend(tokenizer.encode(&chunk, false).expect("tokenization failed")); + } + ids.truncate(tokens); + ids +} + +struct Session { + /// The prompt of the next request: everything so far (history + the assistant header). + prompt: Vec, + turn: usize, +} + +/// What one request returned. +struct Served { + tokens: Vec, + ttft_ms: f64, + total_ms: f64, + prompt_ms: f64, + decode_ms: f64, + reused: usize, +} + +fn serve_one( + stack: &mut OriginalServeStack<'_, '_>, + prompt: &[u32], + max_new: usize, + eos: u32, + cancel_probes: Option, + cancel_rounds: Option, +) -> Result { + let request = ServeRequest::new(prompt.iter().map(|&t| t as i32).collect(), max_new, None, 7, 0.0, vec![eos as i32]); + let started = std::time::Instant::now(); + let first = std::cell::Cell::new(None::); + let rounds = std::cell::Cell::new(0usize); + let probes = std::cell::Cell::new(0usize); + let mut tokens = Vec::new(); + let outcome = stack.serve( + &request, + &mut |round| { + if first.get().is_none() { + first.set(Some(started.elapsed().as_secs_f64() * 1e3)); + } + rounds.set(rounds.get() + 1); + tokens.extend_from_slice(round); + Ok(()) + }, + &mut || { + probes.set(probes.get() + 1); + cancel_probes.is_some_and(|n| probes.get() >= n) || cancel_rounds.is_some_and(|n| rounds.get() >= n) + }, + )?; + assert_eq!(outcome.produced, tokens.len()); + let (prompt_ms, decode_ms) = stack.last_timing(); + Ok(Served { + tokens, + ttft_ms: first.get().unwrap_or(f64::NAN), + total_ms: started.elapsed().as_secs_f64() * 1e3, + prompt_ms, + decode_ms, + reused: stack.reused_tokens(), + }) +} + +fn ids(tokens: &[i32]) -> String { + tokens.iter().map(|t| t.to_string()).collect::>().join(",") +} + +#[test] +#[ignore = "one explicitly scheduled inherited KAR+MTP load and GPU; long prompts"] +fn original_serve_prefix_cache_smoke() { + let _ = dbg_el(); + assert!(env::var("LELEKA_PFX_SMOKE").is_ok_and(|v| v == "yes"), "explicit prefix-cache smoke opt-in required"); + let mode = text("LELEKA_PFX_MODE", "prefix"); + let scenario = text("LELEKA_PFX_SCENARIO", "grid"); + let verify = text("LELEKA_PFX_VERIFY", "none"); + let (shared_n, sessions_n, turns_n) = (number("LELEKA_PFX_SHARED", 8000), number("LELEKA_PFX_SESSIONS", 3), number("LELEKA_PFX_TURNS", 3)); + let (start_n, grow_n, end_n) = (number("LELEKA_PFX_START", 2000), number("LELEKA_PFX_GROW", 2500), number("LELEKA_PFX_END", 40_000)); + let max_new = number("LELEKA_PFX_MAX_NEW", 16); + let capacity = number("LELEKA_PFX_CAPACITY", 2048); + let max_context = number("LELEKA_ORIGINAL_SERVE_MAX_CONTEXT", 262_144); + let resident = number("LELEKA_ORIGINAL_SERVE_KV_RESIDENT", 20_480); + + let laptop = env::var("LELEKA_PFX_LAPTOP").is_ok_and(|v| v == "yes"); + let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0).expect("pinned shard0 verification failed"); + let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 verification failed"); + let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); + let metadata = artifact.tokenizer(); + let tokenizer = Tokenizer::from_vocabulary( + &metadata.model, + &metadata.pre, + metadata.tokens.clone(), + metadata.merges.clone(), + metadata.token_types.clone(), + ) + .expect("verified tokenizer construction failed"); + let eos = *metadata.special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); + let provenance = required_path("LELEKA_STRA169_KAR_PROVENANCE"); + let inherited = match env::var_os("LELEKA_LAPTOP_KAR_FILE") { + Some(path) if laptop => InheritedKarArchive::open_read_only_file(std::path::Path::new(&path), provenance).expect("read-only KAR admission failed"), + _ => { + let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").expect("missing inherited sealed archive descriptor").parse().expect("invalid descriptor"); + InheritedKarArchive::open(fd, provenance).expect("inherited KAR admission failed") + } + }; + let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( + artifact, + &inherited, + &required_path("LELEKA_STRA169_MTP_PACK"), + &required_path("LELEKA_STRA169_MTP_STAGING"), + ) + .expect("actual pinned KAR+MTP binding failed"); + if laptop { + binding.load_mapped_expert_source().expect("mapped expert source load failed"); + if let Ok(cells) = env::var("LELEKA_LAPTOP_CELLS") { + let cells: usize = cells.parse().expect("LELEKA_LAPTOP_CELLS must be a count"); + leleka_cuda_driver::configure_serving_context(cells, &Default::default()).expect("serving context refused"); + eprintln!("PFX config: process geometry {cells} cells (experimental)"); + } + } else { + binding.load_resident_expert_source().expect("resident expert source load failed"); + } + let budget_gib = number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", if laptop { 15 } else { 28 }); + let driver = Driver::load().expect("CUDA driver load failed"); + let device = driver.device(0).expect("CUDA device 0 unavailable"); + let context = Rc::new(device.create_context(budget_gib << 30).expect("bounded Context unavailable")); + + // ---- the workload (identical for every mode) ---- + let mut rng = Rng(0x5eed_1234_abcd_0001); + let tok = |s: &str, special: bool| tokenizer.encode(s, special).expect("tokenization failed"); + let t0 = std::time::Instant::now(); + let mut system = tok("<|im_start|>system\nYou are a coding agent. Tools: shell, apply_patch, read_file, search. Repository notes follow.\n", true); + system.extend(filler(&tokenizer, &mut rng, 0, shared_n.saturating_sub(system.len() + 4))); + system.extend(tok("<|im_end|>\n", true)); + let mut sessions: Vec = Vec::new(); + for s in 0..sessions_n { + let mut prompt = system.clone(); + prompt.extend(tok(&format!("<|im_start|>user\nTask {s}: fix the failing tests in module {s}.\n"), true)); + prompt.extend(filler(&tokenizer, &mut rng, 1, start_n)); + prompt.extend(tok("<|im_end|>\n<|im_start|>assistant\n", true)); + sessions.push(Session { prompt, turn: 0 }); + } + // the order of requests and the size each turn adds + let mut order: Vec = Vec::new(); + let mut grow: Vec> = vec![Vec::new(); sessions_n]; + if scenario == "agent" { + // `turns_n` requests per session, random interleaving; tool outputs are heavy tailed and scaled so a session's + // last request is about `end_n` tokens long + let first_len = sessions[0].prompt.len(); + let total_grow = end_n.saturating_sub(first_len); + for g in grow.iter_mut() { + let raw: Vec = (1..turns_n).map(|_| 0.05 + rng.unit().powi(3) * 6.0).collect(); + let sum: f64 = raw.iter().sum(); + *g = raw.iter().map(|r| ((r / sum) * total_grow as f64) as usize).map(|x| x.max(64)).collect(); + } + let mut left = vec![turns_n; sessions_n]; + while left.iter().any(|&l| l > 0) { + let s = (rng.next() as usize) % sessions_n; + if left[s] > 0 { + left[s] -= 1; + order.push(s); + } + } + } else { + for g in grow.iter_mut() { + *g = vec![grow_n; turns_n.saturating_sub(1)]; + } + for _ in 0..turns_n { + order.extend(0..sessions_n); + } + } + eprintln!( + "PFX workload: mode={mode} scenario={scenario} sessions={sessions_n} turns={turns_n} shared={} first_prompt={} requests={} built_in={:.1}s", + system.len(), + sessions[0].prompt.len(), + order.len(), + t0.elapsed().as_secs_f64() + ); + + // ---- the stack ---- + let mut config = StackConfig::new(max_context as i64); + config.capacity = capacity; + config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from); + config.kv_resident = resident; + if laptop { + config.cpu_workers = number("LELEKA_LAPTOP_CPU_WORKERS", 7) as i32; + } + match mode.as_str() { + "prefix" => { + let budget = match text("LELEKA_PFX_MIB", "auto").as_str() { + "auto" => PrefixBudget::Auto, + other => PrefixBudget::Bytes(other.parse::().expect("LELEKA_PFX_MIB: auto or MiB") << 20), + }; + config.prefix = Some(PrefixConfig { budget, block_tokens: number("LELEKA_PFX_BLOCK", 0), laptop, ..PrefixConfig::auto() }); + } + "legacy" => {} + "off" => config.conversation = None, + other => panic!("LELEKA_PFX_MODE: legacy | prefix | off, not {other}"), + } + config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() + .expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); + eprintln!("PFX stack: capacity={capacity} kv_resident={resident} max_context={max_context} expert tier {:?}", config.expert_tier); + let mut stack = match OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config) { + Ok(stack) => stack, + Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), + }; + eprintln!("PFX host memory after open: available_mib={} rss_mib={}", mem_available_mib(), rss_mib()); + + // ---- serve ---- + let mut failed: Vec = Vec::new(); + let mut decode_rates: Vec = Vec::new(); + let mut reused_total = 0usize; + let mut prompt_total = 0usize; + let mut ttft_sum = 0.0; + let last_of: Vec = (0..sessions_n).map(|s| order.iter().rposition(|&o| o == s).unwrap_or(0)).collect(); + // the previous prompt of each session, to attribute a request's tokens + for (i, &s) in order.iter().enumerate() { + if sessions[s].turn > 0 { + // the agent's next step: the (synthetic) reply, then a tool output + let t = sessions[s].turn; + let kind = (t % 2) as u8; + let size = grow[s][t - 1]; + let mut next = std::mem::take(&mut sessions[s].prompt); + next.extend(tok(&format!("shell {{\"cmd\": \"cargo test -p mod_{s} --lib\"}}<|im_end|>\n<|im_start|>user\n\n"), true)); + next.extend(filler(&tokenizer, &mut rng, kind, size)); + next.extend(tok("\n<|im_end|>\n<|im_start|>assistant\n", true)); + sessions[s].prompt = next; + } + sessions[s].turn += 1; + let prompt = sessions[s].prompt.clone(); + let served = serve_one(&mut stack, &prompt, max_new, eos, None, None) + .unwrap_or_else(|e| panic!("PFX request {i} failed: {e:?} health={:?}", stack.health())); + assert_eq!(stack.health(), None); + let n = prompt.len(); + let read = (n - 1).saturating_sub(served.reused); + let rate = if served.decode_ms > 0.0 { served.tokens.len() as f64 * 1e3 / served.decode_ms } else { 0.0 }; + decode_rates.push(rate); + reused_total += served.reused; + prompt_total += n - 1; + ttft_sum += served.ttft_ms; + eprintln!( + "PFX req={i} session={} turn={} n={n} reused={} read={read} ttft_ms={:.1} prompt_ms={:.1} decode_ms={:.1} decode_tok_s={rate:.1} total_ms={:.1} avail_mib={} rss_mib={} out={}", + (b'A' + s as u8) as char, + sessions[s].turn, + served.reused, + served.ttft_ms, + served.prompt_ms, + served.decode_ms, + served.total_ms, + mem_available_mib(), + rss_mib(), + ids(&served.tokens) + ); + let wants_check = match verify.as_str() { + "every" => served.reused > 0, + "last" => i == last_of[s], + _ => false, + }; + if wants_check && mode == "prefix" { + stack.prefix_bypass(true); + let full = serve_one(&mut stack, &prompt, max_new, eos, None, None) + .unwrap_or_else(|e| panic!("PFX verify {i} failed: {e:?} health={:?}", stack.health())); + stack.prefix_bypass(false); + let equal = full.tokens == served.tokens; + eprintln!( + "PFX-VERIFY req={i} session={} n={n} cached_reused={} equal={equal} ttft_cached_ms={:.1} ttft_full_ms={:.1} full_out={}", + (b'A' + s as u8) as char, + served.reused, + served.ttft_ms, + full.ttft_ms, + ids(&full.tokens) + ); + if !equal { + failed.push(format!("verify req {i}")); + // localise: where the ids first differ, and whether each arm is repeatable on its own + let at = served.tokens.iter().zip(&full.tokens).position(|(a, b)| a != b); + let cached_again = serve_one(&mut stack, &prompt, max_new, eos, None, None).expect("repeat cached read failed"); + stack.prefix_bypass(true); + let full_again = serve_one(&mut stack, &prompt, max_new, eos, None, None).expect("repeat full read failed"); + stack.prefix_bypass(false); + eprintln!( + "PFX-VERIFY-DIAG req={i} first_difference_at={at:?} cached_repeat_equal_cached={} (reused {}) full_repeat_equal_full={} cached_repeat_equal_full={}", + cached_again.tokens == served.tokens, + cached_again.reused, + full_again.tokens == full.tokens, + cached_again.tokens == full.tokens + ); + } + } + if let Some(line) = stack.prefix_metrics() { + eprintln!("PFX-STATS after req={i}: {line}"); + } + } + eprintln!( + "PFX-SUMMARY mode={mode} scenario={scenario} requests={} prompt_tokens={prompt_total} reused_tokens={reused_total} read_tokens={} reuse_pct={:.1} mean_ttft_ms={:.1} mean_decode_tok_s={:.2}", + order.len(), + prompt_total - reused_total, + 100.0 * reused_total as f64 / prompt_total.max(1) as f64, + ttft_sum / order.len().max(1) as f64, + decode_rates.iter().sum::() / decode_rates.len().max(1) as f64 + ); + + // ---- the pool protocol on the live cache ---- + if let Some(summary) = stack.prefix_summary(512) { + let json = serde_json::to_string(&summary).expect("summary json"); + eprintln!("PFX-POOL summary: namespace={} nodes={} blocks={} heads={} json_bytes={} truncated={}", summary.namespace, summary.nodes, summary.blocks, summary.heads.len(), json.len(), summary.truncated); + for s in 0..sessions_n { + let chain = crate::prefix_cache::chain(&sessions[s].prompt.iter().map(|&t| t as i32).collect::>(), summary.block_tokens as usize); + let started = std::time::Instant::now(); + let from_summary = summary.match_tokens(&chain); + let query = stack.prefix_match(&chain).map_or(0, |m| m.cached_tokens); + eprintln!( + "PFX-POOL match session={} prompt={} blocks_hashed={} summary_match={from_summary} query_match={query} us={:.0}", + (b'A' + s as u8) as char, + sessions[s].prompt.len(), + chain.len(), + started.elapsed().as_secs_f64() * 1e6 + ); + } + } + + // ---- cancellation safety ---- + if env::var("LELEKA_PFX_CANCEL").is_ok_and(|v| v == "yes") && mode == "prefix" { + let s = 0usize; + let mut next = sessions[s].prompt.clone(); + next.extend(tok("shell {\"cmd\": \"ls\"}<|im_end|>\n<|im_start|>user\n\n", true)); + next.extend(filler(&tokenizer, &mut rng, 1, 3 * capacity.min(2048))); + next.extend(tok("\n<|im_end|>\n<|im_start|>assistant\n", true)); + let cancelled_prefill = serve_one(&mut stack, &next, max_new, eos, Some(3), None); + let ok1 = matches!(cancelled_prefill, Err(ServeError::Cancelled)) && stack.health().is_none(); + eprintln!("PFX-CANCEL prefill cancelled={ok1}"); + let cancelled_decode = serve_one(&mut stack, &next, 64, eos, None, Some(1)); + let ok2 = matches!(cancelled_decode, Err(ServeError::Cancelled)) && stack.health().is_none(); + eprintln!("PFX-CANCEL decode cancelled={ok2}"); + let after = serve_one(&mut stack, &next, max_new, eos, None, None).expect("request after cancellation failed"); + stack.prefix_bypass(true); + let full = serve_one(&mut stack, &next, max_new, eos, None, None).expect("verification read failed"); + stack.prefix_bypass(false); + let equal = after.tokens == full.tokens; + eprintln!("PFX-CANCEL after reused={} equal_full={equal} out={}", after.reused, ids(&after.tokens)); + if !(ok1 && ok2 && equal) { + failed.push("cancel".into()); + } + // a switch to another session right after a cancelled request + let other = sessions[1 % sessions_n].prompt.clone(); + let switched = serve_one(&mut stack, &other, max_new, eos, None, None).expect("switch after cancellation failed"); + eprintln!("PFX-CANCEL switch reused={} out={}", switched.reused, ids(&switched.tokens)); + } + if let Some(line) = stack.prefix_metrics() { + eprintln!("PFX-FINAL {line}"); + } + eprintln!("PFX host memory at end: available_mib={} rss_mib={}", mem_available_mib(), rss_mib()); + eprintln!("PFX-RESULT failed={failed:?}"); + stack.close().expect("stack cleanup failed"); + Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed"); + assert!(failed.is_empty(), "prefix-cache checks failed: {failed:?}"); +} diff --git a/crates/leleka-runtime/src/lib.rs b/crates/leleka-runtime/src/lib.rs index 1a0cb96a..54cb0d2a 100644 --- a/crates/leleka-runtime/src/lib.rs +++ b/crates/leleka-runtime/src/lib.rs @@ -19,6 +19,7 @@ pub(crate) use bringup_trace; pub mod backend; pub use leleka_context::{context_policy, memory_plan, rope_scaling}; pub mod conversation; +pub mod prefix_cache; pub mod experimental; pub use backend::spawn_backend_observed_native_integer_iq3_windowed256_retained_gr; diff --git a/crates/leleka-runtime/src/prefix_cache/budget.rs b/crates/leleka-runtime/src/prefix_cache/budget.rs new file mode 100644 index 00000000..78f9fddf --- /dev/null +++ b/crates/leleka-runtime/src/prefix_cache/budget.rs @@ -0,0 +1,113 @@ +//! The prefix cache's host-RAM budget (`--prefix-cache-mib`, default auto). +//! +//! The cache lives in ordinary (pageable) host memory next to the pinned K/V image, the resident expert source +//! and the sealed KAR archive. `MemAvailable` already excludes the sealed memfd (it is shmem) and every page the +//! process pinned, so a fraction of what is available when the stack opens is the right ceiling; a second, +//! dynamic guard ([`admit_growth`]) re-checks the live `MemAvailable` before every insertion so a co-tenant +//! that grew in the meantime is respected. + +const MIB: u64 = 1 << 20; +const GIB: u64 = 1 << 30; + +/// What `auto` needs to know. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AutoBudget { + /// `MemAvailable` right now; `None` (unknown telemetry) disables the cache under `auto`. + pub mem_available: Option, + /// Memory that must stay available for everything else (page cache pressure, the next request's buffers). + pub floor: u64, + /// Share of what is left above the floor that the cache may take, in percent. + pub percent: u64, + /// Hard ceiling. + pub cap: u64, + /// Below this a cache cannot hold even one useful entry and is disabled. + pub min_useful: u64, +} + +impl AutoBudget { + /// The server profile: keep 4 GiB available, take 75% of the rest, never more than 96 GiB. (On the 5090 server the + /// sealed KAR memfd, the resident expert source and the pinned K/V leave only ~14 GiB available when the stack opens, + /// so a generous floor would switch the cache off exactly where it is wanted.) + pub const fn server(mem_available: Option) -> Self { + Self { mem_available, floor: 4 * GIB, percent: 75, cap: 96 * GIB, min_useful: GIB } + } + /// The laptop profile: the same shares, never more than 24 GiB. + pub const fn laptop(mem_available: Option) -> Self { + Self { mem_available, floor: 4 * GIB, percent: 75, cap: 24 * GIB, min_useful: GIB } + } + /// Budget in bytes; `0` = the cache is off. + pub fn bytes(&self) -> u64 { + let Some(available) = self.mem_available else { return 0 }; + let free = available.saturating_sub(self.floor); + let budget = (u128::from(free) * u128::from(self.percent.min(100)) / 100) as u64; + let budget = budget.min(self.cap) / MIB * MIB; + if budget < self.min_useful { 0 } else { budget } + } +} + +/// Whether the host can take `additional` more bytes without dropping below `floor` of available memory. +/// Unknown telemetry fails closed (as the conversation cache's admission does). +pub fn admit_growth(mem_available: Option, additional: u64, floor: u64) -> bool { + crate::conversation::memory::memory_admit(mem_available, additional, floor) +} + +/// Parse the operator value of `--prefix-cache-mib`: `auto`, `off`/`0`, or a size in MiB. +pub fn parse_mib(value: &str) -> Result, &'static str> { + match value { + "auto" => Ok(None), + "off" | "0" => Ok(Some(0)), + other => other + .parse::() + .ok() + .filter(|mib| *mib <= (1 << 30)) + .map(|mib| Some(mib * MIB)) + .ok_or("invalid_prefix_cache_mib"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn auto_takes_a_share_of_what_is_left_above_the_floor() { + // the 5090 server after the sealed KAR memfd and the resident expert source (job 915: ~14-19 GiB available) + let b = AutoBudget::server(Some(14 * GIB)).bytes(); + assert_eq!(b, 10 * GIB * 75 / 100); + // the same server with a mapped expert source: much more is available + assert_eq!(AutoBudget::server(Some(67 * GIB)).bytes(), 63 * GIB * 75 / 100 / MIB * MIB); + // plenty of memory: capped + assert_eq!(AutoBudget::server(Some(1000 * GIB)).bytes(), 96 * GIB); + // the laptop profile: 31 GiB available in WSL + assert_eq!(AutoBudget::laptop(Some(31 * GIB)).bytes(), 27 * GIB * 75 / 100 / MIB * MIB); + assert_eq!(AutoBudget::laptop(Some(60 * GIB)).bytes(), 24 * GIB, "the laptop ceiling"); + assert_eq!(AutoBudget::laptop(Some(10 * GIB)).bytes(), 6 * GIB * 75 / 100 / MIB * MIB); + } + + #[test] + fn auto_is_off_when_nothing_useful_fits_or_telemetry_is_missing() { + assert_eq!(AutoBudget::server(None).bytes(), 0); + assert_eq!(AutoBudget::server(Some(4 * GIB)).bytes(), 0); + assert_eq!(AutoBudget::server(Some(5 * GIB)).bytes(), 0, "750 MiB is below the useful minimum"); + assert_eq!(AutoBudget::laptop(Some(3 * GIB)).bytes(), 0); + assert!(AutoBudget::server(Some(6 * GIB)).bytes() >= GIB); + } + + #[test] + fn the_dynamic_guard_keeps_the_floor_and_fails_closed() { + assert!(admit_growth(Some(20 * GIB), 4 * GIB, 16 * GIB)); + assert!(!admit_growth(Some(20 * GIB), 5 * GIB, 16 * GIB)); + assert!(!admit_growth(None, 1, 0)); + } + + #[test] + fn the_operator_value_parses() { + assert_eq!(parse_mib("auto"), Ok(None)); + assert_eq!(parse_mib("0"), Ok(Some(0))); + assert_eq!(parse_mib("off"), Ok(Some(0))); + assert_eq!(parse_mib("2048"), Ok(Some(2048 * MIB))); + assert!(parse_mib("-1").is_err()); + assert!(parse_mib("lots").is_err()); + assert!(parse_mib("99999999999999").is_err()); + } +} diff --git a/crates/leleka-runtime/src/prefix_cache/hash.rs b/crates/leleka-runtime/src/prefix_cache/hash.rs new file mode 100644 index 00000000..1215afbe --- /dev/null +++ b/crates/leleka-runtime/src/prefix_cache/hash.rs @@ -0,0 +1,95 @@ +//! The block hash chain of the prefix cache (`docs/prefix-cache.md`, "Protocol"). +//! +//! A prompt is cut into blocks of `block_tokens` tokens; the chain value after block `j` covers tokens +//! `0 .. (j + 1) * block_tokens` and depends on every one of them, so two prompts have the same value at block `j` +//! exactly when they share that whole prefix (up to a 64-bit collision, which the store rules out by also comparing +//! the tokens). A router that wants to know which runtime holds the longest prefix of a request computes the same +//! chain from the request's token ids and asks each runtime for the deepest value it knows +//! ([`super::summary::PrefixSummary::match_tokens`]); no runtime state is needed to compute it. +//! +//! The function is fixed by this file and by [`CHAIN_VERSION`]; changing either changes every value. + +/// Version of the chain function, part of the summary's namespace so a router never mixes two functions. +pub const CHAIN_VERSION: u32 = 1; +/// Start value of the chain (the value "before block 0"). +pub const CHAIN_SEED: u64 = 0x4C45_4C45_4B41_0001; + +const K: u64 = 0x517C_C1B7_2722_0A95; + +#[inline] +fn finalize(mut h: u64) -> u64 { + // splitmix64 finalizer + h ^= h >> 30; + h = h.wrapping_mul(0xBF58_476D_1CE4_E5B9); + h ^= h >> 27; + h = h.wrapping_mul(0x94D0_49BB_1331_11EB); + h ^ (h >> 31) +} + +/// The chain value after one more block of tokens. +#[inline] +pub fn chain_step(prev: u64, block: &[i32]) -> u64 { + let mut h = prev; + for &token in block { + h = (h.rotate_left(5) ^ u64::from(token as u32)).wrapping_mul(K); + } + finalize(h ^ ((block.len() as u64) << 40)) +} + +/// The chain values after every FULL block of `tokens` (the partial tail has none). +pub fn chain(tokens: &[i32], block_tokens: usize) -> Vec { + assert!(block_tokens > 0, "block_tokens must be positive"); + let mut out = Vec::with_capacity(tokens.len() / block_tokens); + let mut prev = CHAIN_SEED; + for block in tokens.chunks_exact(block_tokens) { + prev = chain_step(prev, block); + out.push(prev); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_chain_covers_only_full_blocks_and_every_earlier_token() { + let tokens: Vec = (0..100).collect(); + assert_eq!(chain(&tokens, 32).len(), 3); + assert_eq!(chain(&tokens[..95], 32).len(), 2); + assert_eq!(chain(&tokens[..63], 32).len(), 1); + let a = chain(&tokens, 32); + // a prefix of the same tokens gives the same values + assert_eq!(chain(&tokens[..64], 32), a[..2]); + // changing one token changes its block and every later one, never an earlier one + let mut edited = tokens.clone(); + edited[40] += 1; + let b = chain(&edited, 32); + assert_eq!(a[0], b[0]); + assert_ne!(a[1], b[1]); + assert_ne!(a[2], b[2]); + // the same block after different history differs + let mut shifted = tokens.clone(); + shifted[0] += 1; + let c = chain(&shifted, 32); + assert!(a.iter().zip(&c).all(|(x, y)| x != y)); + } + + #[test] + fn the_function_is_pinned() { + // These values are the protocol: a router computes them independently. + let tokens: Vec = (0..8).collect(); + assert_eq!(chain(&tokens, 4), vec![0x9e7feaf140c714d6, 0xcd122713bf23558d]); + } + + #[test] + fn negative_and_large_ids_hash_without_collisions_on_a_sweep() { + let mut seen = std::collections::HashSet::new(); + for t in [-1, 0, 1, 248_319, i32::MAX, i32::MIN] { + assert!(seen.insert(chain_step(CHAIN_SEED, &[t, 1, 2, 3]))); + } + for len in 1..64usize { + assert!(seen.insert(chain_step(CHAIN_SEED, &vec![7; len]))); + } + } +} diff --git a/crates/leleka-runtime/src/prefix_cache/mod.rs b/crates/leleka-runtime/src/prefix_cache/mod.rs new file mode 100644 index 00000000..1c16034e --- /dev/null +++ b/crates/leleka-runtime/src/prefix_cache/mod.rs @@ -0,0 +1,38 @@ +//! Cross-session prefix cache of the serving runtime (`docs/prefix-cache.md`). +//! +//! The model-free parts live here: the block hash chain a router can reproduce ([`hash`]), the content-addressed +//! store with its adaptive admission and eviction ([`store`]), the host-RAM budget ([`budget`]) and the pool +//! summary / `prefix_match` reply ([`summary`]). The device side that fills and restores it is +//! `qwen_forward::original_serve_prefix`. + +pub mod budget; +pub mod hash; +pub mod store; +pub mod summary; + +pub use hash::{chain, chain_step, CHAIN_SEED, CHAIN_VERSION}; +pub use store::{ByteSize, Consider, PolicyParams, PrefixStore, Reject, Stats, StoreConfig}; +pub use summary::{PrefixMatch, PrefixSummary}; + +/// A 64-bit fingerprint of a description string (FNV-1a, finalized like the chain), for the summary's namespace. +pub fn fingerprint(text: &str) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for byte in text.bytes() { + h ^= u64::from(byte); + h = h.wrapping_mul(0x0100_0000_01b3); + } + hash::chain_step(h, &[]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_fingerprint_separates_configurations() { + let a = fingerprint("qwen-iq3-s|block=2048|kv=int8|chain=1"); + assert_eq!(a, fingerprint("qwen-iq3-s|block=2048|kv=int8|chain=1")); + assert_ne!(a, fingerprint("qwen-iq3-s|block=1024|kv=int8|chain=1")); + assert_ne!(a, fingerprint("qwen-iq3-s|block=2048|kv=int8|chain=2")); + } +} diff --git a/crates/leleka-runtime/src/prefix_cache/store.rs b/crates/leleka-runtime/src/prefix_cache/store.rs new file mode 100644 index 00000000..775ebe1d --- /dev/null +++ b/crates/leleka-runtime/src/prefix_cache/store.rs @@ -0,0 +1,1008 @@ +//! The content-addressed prefix store: shared blocks, checkpoint nodes, and the adaptive admission and eviction +//! policy (`docs/prefix-cache.md`, "Design"). +//! +//! * A **block** holds the K/V cells and index rows of `block_tokens` consecutive tokens, keyed by the hash chain +//! value after it (so by the whole token prefix it ends). Two sessions with the same system prompt reach the same +//! blocks and share ONE copy; a block is freed when no node covers it any more (`refs`). +//! * A **node** is a checkpoint: the model's recurrent state after a whole number of blocks `k`, keyed by the chain +//! value after block `k - 1`. Restoring it needs its `k` blocks and nothing else, so a request resumes from the +//! deepest node that is a prefix of its prompt, whichever session created it. +//! * Admission and eviction work on expected tokens saved per byte (see [`PolicyParams`]); the store never holds +//! more than `budget_bytes` of payload. +//! +//! The payload types are the caller's (host images in production, tiny structs in the tests); the store only needs +//! their sizes. + +use super::hash::{chain_step, CHAIN_SEED}; +use std::collections::{HashMap, HashSet}; + +/// Bytes a payload pins in host memory. +pub trait ByteSize { + fn byte_size(&self) -> usize; +} + +/// Knobs of the value estimate. The defaults are the operator-facing policy; `docs/prefix-cache.md` explains them. +#[derive(Clone, Debug, PartialEq)] +pub struct PolicyParams { + /// Probability that the next request of a session continues from the deepest node it just created. + pub frontier_prior: f64, + /// Probability that an interior node (one with a deeper neighbour in its chain) is hit again; each branch below + /// it raises it, because a branch point is by definition shared. + pub interior_prior: f64, + /// Weight of the decayed hit mass in the hit probability. + pub hit_gain: f64, + /// Hit mass of a hit by ANOTHER session than the one that built the node (a shared root, or a rewrite of + /// history): evidence that the node is a branch point. + pub shared_weight: f64, + /// Hit mass of a session's own continuation. 0 by default: such a hit only says the node WAS the session's + /// frontier, which the frontier prior already values, and counting it would keep every superseded frontier + /// looking like a branch point. (It still refreshes the node's age.) + pub continuation_weight: f64, + /// Requests after which priors and hit mass halve. + pub half_life: f64, +} +impl Default for PolicyParams { + fn default() -> Self { + Self { frontier_prior: 0.5, interior_prior: 0.03, hit_gain: 1.0, shared_weight: 3.0, continuation_weight: 0.0, half_life: 256.0 } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct StoreConfig { + /// Tokens per block; every node sits on a multiple of it. + pub block_tokens: usize, + /// Payload bytes the store may hold. + pub budget_bytes: usize, + /// Hard cap on checkpoint nodes (each also bounds an O(nodes x depth) scoring pass). + pub max_nodes: usize, + pub policy: PolicyParams, +} + +/// Counters for the metrics line and the status endpoint. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Stats { + pub requests: u64, + pub hits: u64, + /// Hits on a branch point: a node with descendants (a prefix shared by several sessions, or a forked history). + pub shared_hits: u64, + pub misses: u64, + pub reused_tokens: u64, + pub prompt_tokens: u64, + pub admitted: u64, + pub already_cached: u64, + pub rejected: u64, + pub evicted: u64, + /// Admitted on an estimate, then evicted at once because the real payload was bigger and worth less. + pub rejected_after_build: u64, +} + +struct Block { + tokens: Box<[i32]>, + payload: B, + bytes: usize, + /// Nodes whose path covers this block. + refs: u32, +} + +struct Node { + /// Chain values of blocks `0..k`; the last one is the node's key. + path: Box<[u64]>, + payload: N, + bytes: usize, + touched: u64, + hit_mass: f64, + hit_stamp: u64, + hits: u64, + shared_hits: u64, + /// Built as the deepest node of its request (the likeliest resume point of the session's next request). + frontier: bool, +} + +/// The deepest cached node that is a prefix of a prompt. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Match { + pub key: u64, + pub tokens: usize, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Reject { + /// The entry alone is bigger than the budget. + TooLarge, + /// Making room would evict entries worth more than this one. + NotWorth, + /// Nothing left to evict. + NoRoom, + /// A block with this chain value holds other tokens (a 64-bit collision): never cached. + Collision, + /// `commit` got blocks other than the candidate's missing ones. + Mismatch, +} + +#[derive(Debug, PartialEq, Eq)] +pub enum Consider { + /// A node for exactly this prefix exists (it was touched). + Exists, + Rejected(Reject), + /// Room was made; build the payloads and `commit`. + Admit(Candidate), +} + +/// An admitted insertion waiting for its payloads. +#[derive(Debug, PartialEq, Eq)] +pub struct Candidate { + key: u64, + path: Vec, + /// Block indices (0-based) whose payload the store does not hold yet. + pub missing: Vec, + frontier: bool, +} +impl Candidate { + pub fn key(&self) -> u64 { + self.key + } + /// Blocks the node covers. + pub fn blocks(&self) -> usize { + self.path.len() + } +} + +struct Scored { + key: u64, + /// Expected tokens saved per byte freed (the order victims are taken in). + score: f64, + /// Expected tokens saved (probability of a hit x tokens only this node saves). + value: f64, + freed: usize, +} + +pub struct PrefixStore { + cfg: StoreConfig, + blocks: HashMap>, + nodes: HashMap>, + clock: u64, + node_bytes: usize, + block_bytes: usize, + stats: Stats, + /// Blocks of an admitted candidate's path whose last node was evicted to make room for it: kept (the candidate + /// is about to cover them again) until `commit` or `abort`. + orphans: HashSet, +} + +impl PrefixStore { + pub fn new(cfg: StoreConfig) -> Self { + assert!(cfg.block_tokens > 0 && cfg.block_tokens % 4 == 0, "block_tokens must be a positive multiple of the 4-cell page"); + Self { cfg, blocks: HashMap::new(), nodes: HashMap::new(), clock: 0, node_bytes: 0, block_bytes: 0, stats: Stats::default(), orphans: HashSet::new() } + } + pub fn config(&self) -> &StoreConfig { + &self.cfg + } + pub fn stats(&self) -> &Stats { + &self.stats + } + pub fn bytes(&self) -> usize { + self.node_bytes + self.block_bytes + } + pub fn node_bytes(&self) -> usize { + self.node_bytes + } + pub fn block_bytes(&self) -> usize { + self.block_bytes + } + pub fn node_count(&self) -> usize { + self.nodes.len() + } + pub fn block_count(&self) -> usize { + self.blocks.len() + } + pub fn clock(&self) -> u64 { + self.clock + } + + /// A new request begins: ages every prior and hit mass by one tick. + pub fn tick(&mut self, prompt_tokens: usize) { + self.clock += 1; + self.stats.requests += 1; + self.stats.prompt_tokens += prompt_tokens as u64; + } + + pub fn contains_node(&self, key: u64) -> bool { + self.nodes.contains_key(&key) + } + pub fn node_payload(&self, key: u64) -> Option<&N> { + self.nodes.get(&key).map(|n| &n.payload) + } + /// Tokens the node covers. + pub fn node_tokens(&self, key: u64) -> Option { + self.nodes.get(&key).map(|n| n.path.len() * self.cfg.block_tokens) + } + /// The payloads of the node's blocks from block `from_block` on, with their block indices. + pub fn blocks_from(&self, key: u64, from_block: usize) -> Option> { + let node = self.nodes.get(&key)?; + let mut out = Vec::with_capacity(node.path.len().saturating_sub(from_block)); + for (j, h) in node.path.iter().enumerate().skip(from_block) { + out.push((j, &self.blocks.get(h)?.payload)); + } + Some(out) + } + + /// The deepest node that is a prefix of `tokens` and covers at most `limit` tokens. The blocks are compared + /// token for token, so a hash collision cannot produce a hit. + pub fn longest_match(&self, tokens: &[i32], limit: usize) -> Option { + let g = self.cfg.block_tokens; + let mut prev = CHAIN_SEED; + let mut best = None; + for (j, block) in tokens.chunks_exact(g).enumerate() { + let end = (j + 1) * g; + if end > limit { + break; + } + let h = chain_step(prev, block); + match self.blocks.get(&h) { + Some(b) if *b.tokens == *block => {} + _ => break, + } + prev = h; + if self.nodes.contains_key(&h) { + best = Some(Match { key: h, tokens: end }); + } + } + best + } + + /// The deepest node among `chain` (chain values of a prompt's blocks, from [`super::hash::chain`]): the tokens + /// of a cached prefix of that prompt, 0 when none. Hash-only (the router's query): it cannot see collisions. + pub fn prefix_match(&self, chain: &[u64]) -> usize { + chain.iter().rposition(|h| self.nodes.contains_key(h)).map_or(0, |j| (j + 1) * self.cfg.block_tokens) + } + + /// Every node as `(key, tokens)`, deepest first. + pub fn heads(&self) -> Vec<(u64, usize)> { + let mut heads: Vec<(u64, usize)> = self.nodes.iter().map(|(k, n)| (*k, n.path.len() * self.cfg.block_tokens)).collect(); + heads.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); + heads + } + + /// The heads ranked by value (best first), for a summary that has to leave some out. + pub fn heads_by_value(&self) -> Vec<(u64, usize)> { + let mut scored = self.scores(&HashSet::new(), &HashSet::new()); + scored.sort_by(|a, b| b.score.total_cmp(&a.score).then(a.key.cmp(&b.key))); + scored.iter().map(|s| (s.key, self.nodes[&s.key].path.len() * self.cfg.block_tokens)).collect() + } + + pub fn record_miss(&mut self) { + self.stats.misses += 1; + } + + /// Whether the node has descendants, i.e. whether histories fork below it: a system prompt shared by several + /// sessions, or a rewritten history. (A session's own frontier has none.) + pub fn is_branch_point(&self, key: u64) -> bool { + let Some(node) = self.nodes.get(&key) else { return false }; + let at = node.path.len() - 1; + self.nodes.values().any(|other| other.path.len() > node.path.len() && other.path[at] == key) + } + + /// A request resumed from `m`. A hit on a branch point counts as evidence of sharing, a hit on a frontier as + /// the session's own continuation (see [`PolicyParams`]). + pub fn record_hit(&mut self, m: &Match) { + let branch = self.is_branch_point(m.key); + self.record_hit_as(m, branch); + } + + /// `record_hit` with the sharing verdict given by the caller. + pub fn record_hit_as(&mut self, m: &Match, shared: bool) { + let weight = if shared { self.cfg.policy.shared_weight } else { self.cfg.policy.continuation_weight }; + let clock = self.clock; + let half_life = self.cfg.policy.half_life; + if let Some(node) = self.nodes.get_mut(&m.key) { + node.hit_mass = decayed(node.hit_mass, clock - node.hit_stamp, half_life) + weight; + node.hit_stamp = clock; + node.touched = clock; + node.hits += 1; + node.shared_hits += u64::from(shared); + self.stats.hits += 1; + self.stats.shared_hits += u64::from(shared); + self.stats.reused_tokens += m.tokens as u64; + } + } + + fn probability(&self, node: &Node, children: u32) -> f64 { + let p = &self.cfg.policy; + let prior = if children == 0 && node.frontier { p.frontier_prior } else { 1.0 - (1.0 - p.interior_prior).powi(1 + children as i32) }; + let base = prior * decayed(1.0, self.clock - node.touched, p.half_life); + let mass = decayed(node.hit_mass, self.clock - node.hit_stamp, p.half_life); + 1.0 - (1.0 - base) * (-p.hit_gain * mass).exp() + } + + /// Value of every node not in `removed`: expected tokens saved per byte its eviction frees. A node's saving is + /// measured against its nearest SURVIVING ancestor, so thinning a chain makes what is left worth more. + /// `protect`: blocks that stay whatever happens (the path of an entry being admitted). + fn scores(&self, removed: &HashSet, protect: &HashSet) -> Vec { + let g = self.cfg.block_tokens; + let mut cover: HashMap = HashMap::new(); + for key in removed { + if let Some(node) = self.nodes.get(key) { + for h in node.path.iter() { + *cover.entry(*h).or_default() += 1; + } + } + } + let mut ancestor: HashMap = HashMap::with_capacity(self.nodes.len()); + let mut children: HashMap = HashMap::new(); + for (key, node) in &self.nodes { + if removed.contains(key) { + continue; + } + let mut depth = 0; + for i in (0..node.path.len() - 1).rev() { + let h = node.path[i]; + if self.nodes.contains_key(&h) && !removed.contains(&h) { + depth = (i + 1) * g; + *children.entry(h).or_default() += 1; + break; + } + } + ancestor.insert(*key, depth); + } + let mut out = Vec::with_capacity(ancestor.len()); + for (key, node) in &self.nodes { + let Some(&anc) = ancestor.get(key) else { continue }; + let mut freed = node.bytes; + for h in node.path.iter() { + let block = &self.blocks[h]; + if block.refs.saturating_sub(cover.get(h).copied().unwrap_or(0)) == 1 && !protect.contains(h) { + freed += block.bytes; + } + } + let marginal = (node.path.len() * g - anc) as f64; + let p = self.probability(node, children.get(key).copied().unwrap_or(0)); + out.push(Scored { key: *key, score: p * marginal / freed.max(1) as f64, value: p * marginal, freed }); + } + out + } + + /// Decide whether a node for `tokens` (a whole number of blocks) is worth its bytes, making room if so. + /// `est_state` / `est_block`: the sizes the payloads are expected to have. Evictions made here are final even if + /// the caller then fails to build the payloads. + pub fn consider(&mut self, tokens: &[i32], frontier: bool, est_state: usize, est_block: usize) -> Consider { + let g = self.cfg.block_tokens; + assert!(!tokens.is_empty() && tokens.len() % g == 0, "a node covers whole blocks"); + self.release_orphans(); + let mut path = Vec::with_capacity(tokens.len() / g); + let mut missing = Vec::new(); + let mut prev = CHAIN_SEED; + for (j, block) in tokens.chunks_exact(g).enumerate() { + let h = chain_step(prev, block); + match self.blocks.get(&h) { + Some(b) if *b.tokens != *block => { + self.stats.rejected += 1; + return Consider::Rejected(Reject::Collision); + } + Some(_) => {} + None => missing.push(j), + } + path.push(h); + prev = h; + } + let key = prev; + if let Some(node) = self.nodes.get_mut(&key) { + node.touched = self.clock; + self.stats.already_cached += 1; + return Consider::Exists; + } + let need = est_state + missing.len() * est_block; + if need > self.cfg.budget_bytes { + self.stats.rejected += 1; + return Consider::Rejected(Reject::TooLarge); + } + let protect: HashSet = path.iter().copied().collect(); + let mut removed: Vec = Vec::new(); + let mut removed_set: HashSet = HashSet::new(); + let mut freed_total = 0usize; + let mut lost = 0.0f64; + let mut need_slot = self.nodes.len() >= self.cfg.max_nodes; + let free = self.cfg.budget_bytes.saturating_sub(self.bytes()); + while need > free + freed_total || need_slot { + let victim = self + .scores(&removed_set, &protect) + .into_iter() + .min_by(|a, b| a.score.total_cmp(&b.score).then(a.key.cmp(&b.key))); + let Some(victim) = victim else { + self.stats.rejected += 1; + return Consider::Rejected(Reject::NoRoom); + }; + // What the candidate would be worth once this victim is gone (a victim that is its own ancestor raises its + // saving) against everything given up so far: take victims while the sacrifice stays smaller than the gain. + let mut after = removed_set.clone(); + after.insert(victim.key); + if lost + victim.value >= self.candidate_value(&path, frontier, &after) { + self.stats.rejected += 1; + return Consider::Rejected(Reject::NotWorth); + } + lost += victim.value; + freed_total += victim.freed; + removed_set.insert(victim.key); + removed.push(victim.key); + need_slot = false; + } + for key in removed { + self.evict_keeping(key, &protect); + } + Consider::Admit(Candidate { key, path, missing, frontier }) + } + + /// Expected tokens saved by a node at the end of `path` (against its nearest surviving ancestor). + fn candidate_value(&self, path: &[u64], frontier: bool, removed: &HashSet) -> f64 { + let g = self.cfg.block_tokens; + let anc = (0..path.len() - 1) + .rev() + .find(|&i| self.nodes.contains_key(&path[i]) && !removed.contains(&path[i])) + .map_or(0, |i| (i + 1) * g); + let marginal = (path.len() * g - anc) as f64; + let p = if frontier { self.cfg.policy.frontier_prior } else { self.cfg.policy.interior_prior }; + p * marginal + } + + /// Insert an admitted candidate. `tokens` are the same tokens that were considered; `blocks` hold exactly the + /// candidate's missing blocks. The real sizes may differ from the estimates: the budget is enforced again and the + /// new node may be the entry that goes. + pub fn commit(&mut self, candidate: Candidate, tokens: &[i32], state: N, blocks: Vec<(usize, B)>) -> Result<(), Reject> { + let g = self.cfg.block_tokens; + if tokens.len() != candidate.path.len() * g + || blocks.len() != candidate.missing.len() + || blocks.iter().zip(&candidate.missing).any(|((j, _), m)| j != m) + || candidate.missing.iter().any(|j| self.blocks.contains_key(&candidate.path[*j])) + || self.nodes.contains_key(&candidate.key) + { + return Err(Reject::Mismatch); + } + for (j, payload) in blocks { + let bytes = payload.byte_size(); + self.block_bytes += bytes; + self.blocks.insert(candidate.path[j], Block { tokens: tokens[j * g..(j + 1) * g].into(), payload, bytes, refs: 0 }); + } + for h in &candidate.path { + self.orphans.remove(h); + match self.blocks.get_mut(h) { + Some(block) => block.refs += 1, + // a present block vanished between consider and commit: impossible while the caller is single-threaded + None => return Err(Reject::Mismatch), + } + } + let bytes = state.byte_size(); + self.node_bytes += bytes; + self.nodes.insert( + candidate.key, + Node { + path: candidate.path.into_boxed_slice(), + payload: state, + bytes, + touched: self.clock, + hit_mass: 0.0, + hit_stamp: self.clock, + hits: 0, + shared_hits: 0, + frontier: candidate.frontier, + }, + ); + self.stats.admitted += 1; + self.enforce_budget(candidate.key); + Ok(()) + } + + fn enforce_budget(&mut self, fresh: u64) { + while self.bytes() > self.cfg.budget_bytes || self.nodes.len() > self.cfg.max_nodes { + let victim = self + .scores(&HashSet::new(), &HashSet::new()) + .into_iter() + .min_by(|a, b| a.score.total_cmp(&b.score).then(a.key.cmp(&b.key))); + let Some(victim) = victim else { break }; + if victim.key == fresh { + self.stats.rejected_after_build += 1; + } + self.evict(victim.key); + } + } + + /// The caller could not build the payloads of an admitted candidate. + pub fn abort(&mut self, candidate: Candidate) { + drop(candidate); + self.release_orphans(); + } + + fn release_orphans(&mut self) { + for h in std::mem::take(&mut self.orphans) { + if self.blocks.get(&h).is_some_and(|b| b.refs == 0) { + if let Some(block) = self.blocks.remove(&h) { + self.block_bytes -= block.bytes; + } + } + } + } + + /// Remove a node and every block only it covered. + fn evict(&mut self, key: u64) { + self.evict_keeping(key, &HashSet::new()); + } + + /// `evict`, except that blocks in `keep` stay (as orphans) when this was their last node. + fn evict_keeping(&mut self, key: u64, keep: &HashSet) { + let Some(node) = self.nodes.remove(&key) else { return }; + self.node_bytes -= node.bytes; + self.stats.evicted += 1; + for h in node.path.iter() { + let gone = match self.blocks.get_mut(h) { + Some(block) => { + block.refs -= 1; + block.refs == 0 + } + None => false, + }; + if gone && keep.contains(h) { + self.orphans.insert(*h); + } else if gone { + if let Some(block) = self.blocks.remove(h) { + self.block_bytes -= block.bytes; + } + } + } + } + + /// Drop everything (the device state the payloads were taken from is gone or suspect). + pub fn clear(&mut self) { + self.orphans.clear(); + self.blocks.clear(); + self.nodes.clear(); + self.node_bytes = 0; + self.block_bytes = 0; + } + + /// Change the budget (e.g. the operator or the memory guard); evicts down to it. + pub fn set_budget(&mut self, bytes: usize) { + self.cfg.budget_bytes = bytes; + self.enforce_budget(0); + } + + #[cfg(test)] + pub(crate) fn check_invariants(&self) { + let mut refs: HashMap = HashMap::new(); + let mut node_bytes = 0; + for node in self.nodes.values() { + node_bytes += node.bytes; + for h in node.path.iter() { + assert!(self.blocks.contains_key(h), "a node's block is missing"); + *refs.entry(*h).or_default() += 1; + } + } + let mut block_bytes = 0; + for (h, b) in &self.blocks { + assert_eq!(refs.get(h).copied().unwrap_or(0), b.refs, "refcount of a block"); + assert!(b.refs > 0 || self.orphans.contains(h), "an unreferenced block is kept"); + block_bytes += b.bytes; + } + assert_eq!((node_bytes, block_bytes), (self.node_bytes, self.block_bytes)); + } +} + +fn decayed(value: f64, age: u64, half_life: f64) -> f64 { + if value == 0.0 { + 0.0 + } else { + value * 0.5f64.powf(age as f64 / half_life) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::prefix_cache::hash::chain; + + #[derive(Debug)] + struct Payload(usize); + impl ByteSize for Payload { + fn byte_size(&self) -> usize { + self.0 + } + } + const G: usize = 8; + const STATE: usize = 100; + const BLOCK: usize = 30; + + fn store(budget: usize) -> PrefixStore { + PrefixStore::new(StoreConfig { block_tokens: G, budget_bytes: budget, max_nodes: 64, policy: PolicyParams::default() }) + } + fn tokens(session: i32, shared_blocks: usize, blocks: usize) -> Vec { + // `shared_blocks` identical leading blocks, then blocks private to `session` + let mut t = Vec::new(); + for j in 0..blocks { + for i in 0..G { + t.push(if j < shared_blocks { (j * G + i) as i32 } else { session * 10_000 + (j * G + i) as i32 }); + } + } + t + } + /// Insert the node at `blocks` of `t` the way the serving code does. `Exists` stands for "now cached". + fn put(s: &mut PrefixStore, t: &[i32], blocks: usize, frontier: bool) -> Consider { + let prefix = &t[..blocks * G]; + match s.consider(prefix, frontier, STATE, BLOCK) { + Consider::Admit(c) => { + let blocks_in: Vec<(usize, Payload)> = c.missing.iter().map(|j| (*j, Payload(BLOCK))).collect(); + s.commit(c, prefix, Payload(STATE), blocks_in).unwrap(); + s.check_invariants(); + Consider::Exists + } + other => other, + } + } + + #[test] + fn a_request_resumes_from_the_deepest_node_of_any_session() { + let mut s = store(10_000); + let a = tokens(1, 2, 5); + let b = tokens(2, 2, 5); + assert_eq!(put(&mut s, &a, 2, false), Consider::Exists); + assert_eq!(put(&mut s, &a, 5, true), Consider::Exists); + // session B shares the first two blocks only + let m = s.longest_match(&b, b.len()).unwrap(); + assert_eq!(m.tokens, 2 * G); + let m = s.longest_match(&a, a.len()).unwrap(); + assert_eq!(m.tokens, 5 * G); + // the limit keeps the last prompt token out of the cached part + assert_eq!(s.longest_match(&a, 5 * G - 1).unwrap().tokens, 2 * G); + assert_eq!(s.longest_match(&a, G - 1), None); + // an unrelated prompt matches nothing, and so does a prompt shorter than a block + assert_eq!(s.longest_match(&tokens(3, 0, 5), 40), None); + assert_eq!(s.longest_match(&a[..G - 1], G - 1), None); + } + + #[test] + fn common_prefixes_are_stored_once() { + let mut s = store(100_000); + let a = tokens(1, 4, 6); + let b = tokens(2, 4, 6); + put(&mut s, &a, 6, true); + let after_a = s.block_bytes(); + assert_eq!(after_a, 6 * BLOCK); + put(&mut s, &b, 6, true); + // B adds its two private blocks only + assert_eq!(s.block_bytes(), 8 * BLOCK); + assert_eq!(s.block_count(), 8); + assert_eq!(s.node_bytes(), 2 * STATE); + // the shared blocks are referenced by both nodes + let ma = s.longest_match(&a, a.len()).unwrap(); + let mb = s.longest_match(&b, b.len()).unwrap(); + assert_ne!(ma.key, mb.key); + assert_eq!(s.blocks_from(ma.key, 4).unwrap().len(), 2); + assert_eq!(s.blocks_from(ma.key, 0).unwrap().len(), 6); + s.check_invariants(); + } + + #[test] + fn a_node_with_descendants_is_a_branch_point_and_a_frontier_is_not() { + let mut s = store(100_000); + let a = tokens(1, 2, 5); + let b = tokens(2, 2, 5); + put(&mut s, &a, 2, false); + put(&mut s, &a, 5, true); + let shared = s.longest_match(&b, b.len()).unwrap(); + let own = s.longest_match(&a, a.len()).unwrap(); + assert!(s.is_branch_point(shared.key), "A's chain continues below the shared prefix"); + assert!(!s.is_branch_point(own.key)); + s.record_hit(&shared); + s.record_hit(&own); + assert_eq!(s.stats().shared_hits, 1); + assert_eq!(s.stats().hits, 2); + // once B has built its own chain the shared node has two branches below it + put(&mut s, &b, 5, true); + assert!(s.is_branch_point(shared.key)); + assert!(!s.is_branch_point(0xdead)); + } + + #[test] + fn an_existing_node_is_only_touched() { + let mut s = store(10_000); + let a = tokens(1, 0, 3); + put(&mut s, &a, 3, true); + let before = (s.bytes(), s.stats().admitted); + assert_eq!(s.consider(&a, true, STATE, BLOCK), Consider::Exists); + assert_eq!((s.bytes(), s.stats().admitted), before); + assert_eq!(s.stats().already_cached, 1); + } + + #[test] + fn eviction_frees_a_block_only_when_no_node_covers_it() { + let mut s = store(100_000); + let a = tokens(1, 4, 6); + let b = tokens(2, 4, 6); + put(&mut s, &a, 6, true); + put(&mut s, &b, 6, true); + let ma = s.longest_match(&a, a.len()).unwrap(); + s.evict(ma.key); + s.check_invariants(); + // the four shared blocks survive for B, A's two private ones are gone + assert_eq!(s.block_count(), 6); + assert_eq!(s.longest_match(&a, a.len()), None); + assert_eq!(s.longest_match(&b, b.len()).unwrap().tokens, 6 * G); + let mb = s.longest_match(&b, b.len()).unwrap(); + s.evict(mb.key); + assert_eq!((s.block_count(), s.bytes()), (0, 0)); + } + + #[test] + fn a_full_store_evicts_the_least_valuable_entry_for_a_more_valuable_one() { + // room for about two single-block nodes + let mut s = store(2 * (STATE + BLOCK) + 10); + let old = tokens(1, 0, 1); + let other = tokens(2, 0, 1); + put(&mut s, &old, 1, true); + put(&mut s, &other, 1, true); + for _ in 0..200 { + s.tick(10); + } + // `old` idles for 200 requests while `other` is used again and again + for _ in 0..3 { + s.tick(10); + let m = s.longest_match(&other, other.len() + 1).unwrap(); + s.record_hit_as(&m, false); + } + let fresh = tokens(3, 0, 1); + assert_eq!(put(&mut s, &fresh, 1, true), Consider::Exists, "a new frontier beats an idle one"); + assert!(s.longest_match(&old, 100).is_none(), "the idle entry went"); + assert!(s.longest_match(&other, 100).is_some(), "the used entry stayed"); + assert!(s.longest_match(&fresh, 100).is_some()); + assert_eq!(s.stats().evicted, 1); + assert!(s.bytes() <= s.config().budget_bytes); + } + + #[test] + fn a_low_value_candidate_does_not_evict_a_hot_entry() { + let mut s = store(STATE + BLOCK + 10); + let hot = tokens(1, 0, 1); + put(&mut s, &hot, 1, true); + for _ in 0..4 { + s.tick(10); + let m = s.longest_match(&hot, 100).unwrap(); + s.record_hit_as(&m, true); + } + // an interior (non-frontier) candidate of another prompt is worth far less than the shared, used root + let cold = tokens(2, 0, 1); + assert_eq!(s.consider(&cold, false, STATE, BLOCK), Consider::Rejected(Reject::NotWorth)); + assert!(s.longest_match(&hot, 100).is_some()); + assert_eq!(s.stats().rejected, 1); + assert_eq!(s.stats().evicted, 0); + } + + #[test] + fn an_entry_bigger_than_the_budget_is_refused_up_front() { + let mut s = store(100); + let a = tokens(1, 0, 2); + assert_eq!(s.consider(&a, true, STATE, BLOCK), Consider::Rejected(Reject::TooLarge)); + assert_eq!(s.bytes(), 0); + } + + #[test] + fn a_hit_by_another_session_makes_a_shared_root_outlive_private_leaves() { + // budget for the shared root chain + 3 private frontier leaves + let mut s = store(STATE * 5 + BLOCK * 8); + let root = tokens(0, 2, 2); + put(&mut s, &root, 2, false); + // sessions branch off the root, one after the other; every new session hits the root + for session in 1..=6 { + s.tick(100); + let t = tokens(session, 2, 4); + let m = s.longest_match(&t, t.len()).unwrap(); + assert!(m.tokens >= 2 * G); + s.record_hit_as(&m, true); + put(&mut s, &t, 4, true); + s.check_invariants(); + assert!(s.bytes() <= s.config().budget_bytes); + } + // the root survives all the churn, the oldest private leaves went + assert_eq!(s.longest_match(&root, root.len()).map(|m| m.tokens), Some(2 * G)); + assert!(s.longest_match(&tokens(1, 2, 4), 100).map(|m| m.tokens) == Some(2 * G), "session 1's leaf was evicted"); + assert_eq!(s.longest_match(&tokens(6, 2, 4), 100).map(|m| m.tokens), Some(4 * G), "the newest leaf stays"); + } + + #[test] + fn thinning_a_chain_keeps_the_deepest_node_and_the_blocks_it_needs() { + let mut s = store(6 * STATE + 12 * BLOCK); + let long = tokens(1, 0, 12); + for k in 1..=12 { + s.tick(100); + put(&mut s, &long, k, k == 12); + assert!(s.bytes() <= s.config().budget_bytes); + } + s.check_invariants(); + // the frontier is cached with its whole chain of blocks + let m = s.longest_match(&long, long.len()).unwrap(); + assert_eq!(m.tokens, 12 * G); + assert_eq!(s.blocks_from(m.key, 0).unwrap().len(), 12); + assert!(s.node_count() <= 6, "{} nodes", s.node_count()); + } + + #[test] + fn the_budget_is_enforced_again_when_the_real_payload_is_bigger_than_the_estimate() { + let mut s = store(STATE + BLOCK + 10); + let a = tokens(1, 0, 1); + match s.consider(&a, true, STATE, BLOCK) { + Consider::Admit(c) => { + s.commit(c, &a, Payload(STATE * 3), vec![(0, Payload(BLOCK))]).unwrap(); + } + other => panic!("{other:?}"), + } + assert_eq!(s.bytes(), 0, "the oversized node was dropped at once"); + assert_eq!(s.stats().rejected_after_build, 1); + s.check_invariants(); + } + + #[test] + fn commit_refuses_blocks_that_are_not_the_candidates() { + let mut s = store(10_000); + let a = tokens(1, 0, 2); + let Consider::Admit(c) = s.consider(&a, true, STATE, BLOCK) else { panic!() }; + assert_eq!(c.missing, vec![0, 1]); + assert_eq!(s.commit(c, &a, Payload(STATE), vec![(0, Payload(BLOCK))]), Err(Reject::Mismatch)); + assert_eq!(s.bytes(), 0); + } + + #[test] + fn a_colliding_block_is_never_cached_or_matched() { + let mut s = store(10_000); + let a = tokens(1, 0, 1); + put(&mut s, &a, 1, true); + // forge a block under a's chain value that holds other tokens + let h = chain(&a, G)[0]; + s.blocks.get_mut(&h).unwrap().tokens = vec![9; G].into(); + assert_eq!(s.longest_match(&a, 100), None); + assert_eq!(s.consider(&a, true, STATE, BLOCK), Consider::Rejected(Reject::Collision)); + } + + #[test] + fn the_node_cap_makes_room_by_value() { + let mut s = PrefixStore::::new(StoreConfig { + block_tokens: G, + budget_bytes: 1 << 20, + max_nodes: 2, + policy: PolicyParams::default(), + }); + for session in 1..=4 { + s.tick(10); + put(&mut s, &tokens(session, 0, 1), 1, true); + assert!(s.node_count() <= 2); + } + s.check_invariants(); + assert!(s.longest_match(&tokens(4, 0, 1), 100).is_some()); + assert!(s.longest_match(&tokens(1, 0, 1), 100).is_none()); + } + + #[test] + fn prefix_match_reports_the_deepest_known_chain_value() { + let mut s = store(100_000); + let a = tokens(1, 3, 6); + put(&mut s, &a, 3, false); + put(&mut s, &a, 6, true); + let c = chain(&a, G); + assert_eq!(s.prefix_match(&c), 6 * G); + assert_eq!(s.prefix_match(&c[..4]), 3 * G); + assert_eq!(s.prefix_match(&c[..2]), 0); + let other = chain(&tokens(2, 3, 6), G); + assert_eq!(s.prefix_match(&other), 3 * G); + assert_eq!(s.prefix_match(&[]), 0); + assert_eq!(s.heads().iter().map(|h| h.1).collect::>(), vec![6 * G, 3 * G]); + assert_eq!(s.heads_by_value().len(), 2); + } + + #[test] + fn shrinking_the_budget_evicts_down_to_it() { + let mut s = store(100_000); + for session in 1..=5 { + s.tick(10); + put(&mut s, &tokens(session, 0, 2), 2, true); + } + assert_eq!(s.node_count(), 5); + s.set_budget(2 * (STATE + 2 * BLOCK)); + assert!(s.bytes() <= 2 * (STATE + 2 * BLOCK)); + assert_eq!(s.node_count(), 2); + s.check_invariants(); + s.clear(); + assert_eq!((s.bytes(), s.node_count(), s.block_count()), (0, 0, 0)); + } + + #[test] + fn a_long_agent_session_costs_a_sparse_chain_not_a_node_per_block() { + // one session growing 1..=40 blocks, frontier each time; budget for ~8 states + let mut s = store(8 * STATE + 40 * BLOCK); + let t = tokens(1, 0, 40); + for k in 1..=40 { + s.tick(100); + if let Some(m) = s.longest_match(&t, k * G) { + s.record_hit_as(&m, false); + } + put(&mut s, &t, k, true); + assert!(s.bytes() <= s.config().budget_bytes); + } + s.check_invariants(); + let m = s.longest_match(&t, t.len()).unwrap(); + assert_eq!(m.tokens, 40 * G, "the frontier is always kept"); + assert!(s.node_count() <= 8); + // the surviving ancestors are spread, not clustered at the tail only + let depths: Vec = s.heads().iter().map(|h| h.1 / G).collect(); + assert!(depths.iter().any(|d| *d < 39), "{depths:?}"); + } + + /// The pool at the production size, model-free: 12 agent sessions behind one runtime, an 8k shared system prompt, histories + /// growing by 4k tokens per request up to 180k, interleaved round robin, 2048-token blocks, the sizes a real node and block have + /// (127 MB of state, 29 MB per block) against a 13 GB budget. Checks the budget, the hit rate, the cost of the policy and of a + /// lookup over a 180k-token prompt. + #[test] + #[ignore = "scale simulation, seconds in release: cargo test --release -p leleka-runtime --lib -- --ignored twelve_sessions"] + fn twelve_sessions_growing_to_180k_tokens_stay_inside_the_budget_and_the_lookup_stays_fast() { + const BLOCK_TOKENS: usize = 2048; + const STATE_BYTES: usize = 127 << 20; + const BLOCK_BYTES: usize = 29 << 20; + let mut s = PrefixStore::::new(StoreConfig { + block_tokens: BLOCK_TOKENS, + budget_bytes: 13 << 30, + max_nodes: 1024, + policy: PolicyParams::default(), + }); + let token = |session: i32, i: usize| -> i32 { + if i < 4 * BLOCK_TOKENS { (i as i32 * 31) % 247_000 + 1 } else { ((i64::from(session) * 1_000_003 + i as i64 * 7919) % 247_000 + 1) as i32 } + }; + let sessions = 12; + let mut lengths = vec![8_192usize; sessions]; + let (mut match_us, mut policy_us) = (Vec::new(), Vec::new()); + let (mut reused, mut prompt_total) = (0usize, 0usize); + for _round in 0..43 { + for session in 0..sessions { + let n = lengths[session]; + let prompt: Vec = (0..n).map(|i| token(session as i32, i)).collect(); + s.tick(n); + let limit = n - 1; + let started = std::time::Instant::now(); + let hit = s.longest_match(&prompt, limit); + match_us.push(started.elapsed().as_secs_f64() * 1e6); + let resume = hit.map_or(0, |m| m.tokens); + match hit { + Some(m) => s.record_hit(&m), + None => s.record_miss(), + } + reused += resume; + prompt_total += limit; + let last_grid = limit / BLOCK_TOKENS * BLOCK_TOKENS; + let started = std::time::Instant::now(); + let mut end = (resume / BLOCK_TOKENS + 1) * BLOCK_TOKENS; + while end <= last_grid { + if let Consider::Admit(c) = s.consider(&prompt[..end], end == last_grid, STATE_BYTES, BLOCK_BYTES) { + let blocks = c.missing.iter().map(|j| (*j, Payload(BLOCK_BYTES))).collect(); + s.commit(c, &prompt[..end], Payload(STATE_BYTES), blocks).unwrap(); + } + end += BLOCK_TOKENS; + } + policy_us.push(started.elapsed().as_secs_f64() * 1e6); + assert!(s.bytes() <= s.config().budget_bytes); + lengths[session] += 4_096; + } + } + s.check_invariants(); + let longest = lengths.iter().max().copied().unwrap(); + let mean = |v: &[f64]| v.iter().sum::() / v.len() as f64; + let max = |v: &[f64]| v.iter().cloned().fold(0.0, f64::max); + eprintln!( + "scale: {} requests, longest prompt {longest}; reuse {:.1}%; lookup mean {:.0} us max {:.0} us; policy per request mean {:.0} us max {:.0} us; nodes {} blocks {} bytes {} MiB of {}; admitted {} rejected {} evicted {}", + match_us.len(), + 100.0 * reused as f64 / prompt_total as f64, + mean(&match_us), max(&match_us), mean(&policy_us), max(&policy_us), + s.node_count(), s.block_count(), s.bytes() >> 20, s.config().budget_bytes >> 20, + s.stats().admitted, s.stats().rejected, s.stats().evicted + ); + assert!(longest >= 170_000); + // the cache is smaller than the sum of the histories (12 x ~90k tokens on average = 15 GB of blocks alone): it must have chosen + assert!(s.stats().evicted > 0 || s.stats().rejected > 0); + // a lookup over a 180k-token prompt (hashing and comparing every token) is milliseconds even in a debug build + assert!(max(&match_us) < 200_000.0, "{} us", max(&match_us)); + assert!(max(&policy_us) < 2_000_000.0, "{} us", max(&policy_us)); + // sessions keep resuming close to their frontier: the hit rate stays high + assert!(reused as f64 / prompt_total as f64 > 0.5); + } +} diff --git a/crates/leleka-runtime/src/prefix_cache/summary.rs b/crates/leleka-runtime/src/prefix_cache/summary.rs new file mode 100644 index 00000000..31b2b1f5 --- /dev/null +++ b/crates/leleka-runtime/src/prefix_cache/summary.rs @@ -0,0 +1,170 @@ +//! What a runtime tells a front router about its prefix cache (`docs/prefix-cache.md`, "Pool protocol"). +//! +//! The summary is the list of the cache's checkpoint heads: for each node, the hash-chain value after its last +//! block ([`super::hash`]) and the tokens it covers. A router that hashes a request's prompt with the same chain +//! asks every runtime [`PrefixSummary::match_tokens`] and sends the request to the one with the longest match (ties: +//! the less loaded). The summary is a snapshot; a runtime may have evicted a node since, so a router treats the +//! number as a hint, never as a promise. + +use super::hash::CHAIN_VERSION; +use super::store::{ByteSize, PrefixStore, Stats}; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; + +/// Wire version of the summary object. +pub const SUMMARY_VERSION: u32 = 1; + +/// One checkpoint head. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Head { + /// Chain value after the node's last block, 16 lowercase hex digits. + pub h: String, + /// Tokens the node covers (a multiple of `block_tokens`). + pub tokens: u32, +} + +/// The counters of [`Stats`] plus the gauges, as sent. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct SummaryStats { + pub requests: u64, + pub hits: u64, + pub shared_hits: u64, + pub misses: u64, + pub reused_tokens: u64, + pub prompt_tokens: u64, + pub admitted: u64, + pub rejected: u64, + pub evicted: u64, +} +impl From<&Stats> for SummaryStats { + fn from(s: &Stats) -> Self { + Self { + requests: s.requests, + hits: s.hits, + shared_hits: s.shared_hits, + misses: s.misses, + reused_tokens: s.reused_tokens, + prompt_tokens: s.prompt_tokens, + admitted: s.admitted, + rejected: s.rejected + s.rejected_after_build, + evicted: s.evicted, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PrefixSummary { + pub version: u32, + pub chain_version: u32, + /// Fingerprint of everything that makes two caches interchangeable (model identity, block size, KV format, + /// chain version), 16 hex digits. A router only compares chain values across runtimes with the same namespace. + pub namespace: String, + pub block_tokens: u32, + pub budget_bytes: u64, + pub used_bytes: u64, + pub nodes: u32, + pub blocks: u32, + /// `true` when `heads` leaves out nodes (the cache holds more than `max_heads`); the best are kept. + pub truncated: bool, + pub heads: Vec, + pub stats: SummaryStats, +} + +pub fn hex(h: u64) -> String { + format!("{h:016x}") +} + +impl PrefixSummary { + pub fn build(store: &PrefixStore, namespace: u64, max_heads: usize) -> Self { + let all = store.heads_by_value(); + let truncated = all.len() > max_heads; + let heads = all.into_iter().take(max_heads).map(|(h, tokens)| Head { h: hex(h), tokens: tokens as u32 }).collect(); + Self { + version: SUMMARY_VERSION, + chain_version: CHAIN_VERSION, + namespace: hex(namespace), + block_tokens: store.config().block_tokens as u32, + budget_bytes: store.config().budget_bytes as u64, + used_bytes: store.bytes() as u64, + nodes: store.node_count() as u32, + blocks: store.block_count() as u32, + truncated, + heads, + stats: SummaryStats::from(store.stats()), + } + } + + /// Tokens of the longest cached prefix of a prompt whose chain values (one per full block) are `chain`; + /// 0 when none of its heads is here. + pub fn match_tokens(&self, chain: &[u64]) -> u32 { + let known: HashMap<&str, u32> = self.heads.iter().map(|h| (h.h.as_str(), h.tokens)).collect(); + chain.iter().rev().find_map(|h| known.get(hex(*h).as_str()).copied()).unwrap_or(0) + } +} + +/// The reply of the `prefix_match` query: how much of a prompt this runtime has cached. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PrefixMatch { + pub namespace: String, + pub block_tokens: u32, + /// Tokens of the longest cached prefix (0 = none). + pub cached_tokens: u32, +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::prefix_cache::hash::chain; + use crate::prefix_cache::store::{Consider, PolicyParams, StoreConfig}; + + struct P(usize); + impl ByteSize for P { + fn byte_size(&self) -> usize { + self.0 + } + } + + fn filled() -> (PrefixStore, Vec) { + let mut s = PrefixStore::new(StoreConfig { block_tokens: 8, budget_bytes: 1 << 20, max_nodes: 16, policy: PolicyParams::default() }); + let tokens: Vec = (0..48).collect(); + for k in [2usize, 6] { + let Consider::Admit(c) = s.consider(&tokens[..k * 8], true, 10, 5) else { panic!() }; + let blocks = c.missing.iter().map(|j| (*j, P(5))).collect(); + s.commit(c, &tokens[..k * 8], P(10), blocks).unwrap(); + } + (s, tokens) + } + + #[test] + fn a_router_matches_a_prompt_against_the_heads_with_the_same_chain() { + let (store, tokens) = filled(); + let summary = PrefixSummary::build(&store, 0xabc, 64); + assert_eq!((summary.version, summary.block_tokens, summary.nodes, summary.blocks), (1, 8, 2, 6)); + assert_eq!(summary.namespace, "0000000000000abc"); + assert!(!summary.truncated); + // the router hashes its own prompt: it shares 3 blocks, then diverges + let mut prompt = tokens.clone(); + prompt[30] = -5; + assert_eq!(summary.match_tokens(&chain(&prompt, 8)), 16, "the node at 2 blocks is the deepest prefix"); + assert_eq!(summary.match_tokens(&chain(&tokens, 8)), 48); + assert_eq!(summary.match_tokens(&chain(&tokens[..40], 8)), 16); + assert_eq!(summary.match_tokens(&chain(&[9; 64], 8)), 0); + assert_eq!(summary.match_tokens(&[]), 0); + // the store's own query agrees + assert_eq!(store.prefix_match(&chain(&prompt, 8)), 16); + } + + #[test] + fn the_summary_round_trips_as_json_and_truncates_to_the_best_heads() { + let (store, _) = filled(); + let summary = PrefixSummary::build(&store, 7, 1); + assert!(summary.truncated); + assert_eq!(summary.heads.len(), 1); + let text = serde_json::to_string(&summary).unwrap(); + let back: PrefixSummary = serde_json::from_str(&text).unwrap(); + assert_eq!(back, summary); + assert!(text.contains("\"namespace\":\"0000000000000007\""), "{text}"); + let m = PrefixMatch { namespace: summary.namespace.clone(), block_tokens: 8, cached_tokens: 48 }; + assert_eq!(serde_json::from_str::(&serde_json::to_string(&m).unwrap()).unwrap(), m); + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/executor_original_prompt.rs b/crates/leleka-runtime/src/qwen_forward/executor_original_prompt.rs index edec0e7c..580ee2da 100644 --- a/crates/leleka-runtime/src/qwen_forward/executor_original_prompt.rs +++ b/crates/leleka-runtime/src/qwen_forward/executor_original_prompt.rs @@ -4,7 +4,7 @@ use super::*; use super::super::{dense_weight_cache::DenseWeightCache,moe_weight_cache::{MoeWeightCache,RetainedOriginalMtpWeights}}; use super::super::prompt_device_rows::{PromptDeviceSource,PromptDeviceRows,PromptDeviceNormedRows,PromptDeviceFinal}; -use super::super::session::original_prompt::{OriginalPromptTxn,OriginalSessionCheckpoint,OriginalPromptInput}; +use super::super::session::original_prompt::{OriginalPromptTxn,OriginalSessionCheckpoint,OriginalPromptInput,ParkedSession,ParkedBlock}; use super::super::qsa_index::prompt_device::resident_device::{ResidentQsaLayer,ResidentQsaPrior}; use super::super::output::OriginalPromptSample; use super::super::session::original_prompt::draft::{OriginalDraftSession,OriginalDraftCheckpoint}; @@ -226,6 +226,28 @@ impl<'ctx> OriginalPromptExecutor<'ctx>{ if self.layers.iter().flatten().count()!=12{return Err(Error::IdentityMismatch);} session.original_checkpoint(binding) } + /// Prefix cache: park the point the session stands at (see `ParkedSession`). + pub(in crate::qwen_forward) fn park_session(&mut self,binding:&ModelBinding, + session:&mut QwenSession<'ctx>)->Result{ + if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} + if self.layers.iter().flatten().count()!=12{return Err(Error::IdentityMismatch);} + session.park_original(binding,&self.layers) + } + /// Prefix cache: the cells `first..first + tokens` of the twelve layers as plain bytes. + pub(in crate::qwen_forward) fn park_block(&self,session:&QwenSession<'ctx>,first:usize,tokens:usize)->Result{ + if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} + if self.layers.iter().flatten().count()!=12{return Err(Error::IdentityMismatch);} + session.park_block(&self.layers,first,tokens) + } + /// Prefix cache: make the session and the twelve layers stand at `parked`, writing `blocks`. A failure poisons + /// the executor, as for `restore_session`. + pub(in crate::qwen_forward) fn import_session(&mut self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, + session:&mut QwenSession<'ctx>,parked:&ParkedSession,blocks:&[&ParkedBlock])->Result<()>{ + if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} + let imported=session.import_parked(binding,dense,&mut self.layers,parked,blocks); + if imported.is_err(){self.failed=true;} + imported + } /// Roll the session AND the twelve physical resident layers back to `checkpoint` (a request reset to the /// empty prompt, or an abandoned prompt transaction). A failure poisons the executor. pub(in crate::qwen_forward) fn restore_session(&mut self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, diff --git a/crates/leleka-runtime/src/qwen_forward/gdn_state.rs b/crates/leleka-runtime/src/qwen_forward/gdn_state.rs index cc00fd20..4d558474 100644 --- a/crates/leleka-runtime/src/qwen_forward/gdn_state.rs +++ b/crates/leleka-runtime/src/qwen_forward/gdn_state.rs @@ -32,6 +32,10 @@ impl GdnStateKey { } } impl GdnPrior { + /// Host bytes of the recurrent image and its history window (prefix-cache accounting). + pub(in crate::qwen_forward) fn host_bytes(&self) -> usize { + (self.0.values.len() + self.0.history.len()) * 4 + } pub(super) fn mirror_key(&self) -> GdnStateKey { GdnStateKey(Rc::downgrade(&self.0)) } diff --git a/crates/leleka-runtime/src/qwen_forward/input.rs b/crates/leleka-runtime/src/qwen_forward/input.rs index 3d37a33f..12a01fc1 100644 --- a/crates/leleka-runtime/src/qwen_forward/input.rs +++ b/crates/leleka-runtime/src/qwen_forward/input.rs @@ -515,6 +515,10 @@ struct PleState { #[derive(Clone)] pub(super) struct PlePrior(Rc); impl PlePrior { + /// Host bytes of the history window (prefix-cache accounting). + pub(in crate::qwen_forward) fn host_bytes(&self) -> usize { + self.0.history.len() * 4 + } #[cfg(all(test, target_os = "linux", target_arch = "x86_64"))] pub(super) fn oracle_history(&self) -> &[f32] { &self.0.history diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_prefix.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix.rs new file mode 100644 index 00000000..cc760537 --- /dev/null +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_prefix.rs @@ -0,0 +1,780 @@ +//! The cross-session prefix cache bound to the Original serve stack (`docs/prefix-cache.md`). +//! +//! Where the conversation cache (`original_serve_conversation`) keeps a chain of checkpoints of the ONE conversation +//! whose K/V the positional buffer holds, this keeps content-addressed checkpoints of every prefix the stack has +//! read, in host RAM, and puts any of them back whichever session asks: +//! +//! * the prompt is read on a fixed token grid (`PromptOptions::grid`): every batched chunk ends on a multiple of +//! `block_tokens`. The state after such a chunk is a pure function of the tokens before it, so a checkpoint taken +//! by one request is exactly the state any other request would reach by reading the same tokens, and a request +//! resumed from it reads exactly the chunks a full read reads from there; +//! * after a chunk the policy may admit a checkpoint at that grid point (`PrefixStore::consider`): the recurrent +//! state (a `ParkedSession` plus the draft ring's snapshot) and the K/V cells and index rows of the blocks the +//! store does not hold yet (`ParkedBlock`); +//! * a request resumes from the deepest checkpoint that is a prefix of its prompt: the state is installed and only +//! the cells the positional buffer does not already hold are written back (`QwenSession::import_parked`). +//! +//! `live` is the part of the positional buffer known to hold the current prompt's cells (written by the prefill, or +//! put back by an import). It is truncated before a chunk or an import overwrites cells and extended after, so a +//! cancelled or failed request never claims cells it did not finish writing. +use super::super::contract::Error; +use crate::prefix_cache::{ + budget, fingerprint, ByteSize, Consider, PolicyParams, PrefixMatch, PrefixStore, PrefixSummary, Reject, Stats, StoreConfig, +}; +use std::time::Instant; + +/// What the operator asked for (`--prefix-cache-mib`, `--prefix-cache-block`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PrefixBudget { + Off, + /// A share of the host memory available when the stack opens (`budget::AutoBudget`). + Auto, + Bytes(u64), +} + +#[derive(Clone, Debug)] +pub(crate) struct PrefixConfig { + pub(crate) budget: PrefixBudget, + /// Tokens per block and per chunk-grid step; 0 = the prefill capacity (a grid step is then one full chunk, so the prefill runs + /// at the speed of the chunk size the operator chose). + pub(crate) block_tokens: usize, + pub(crate) max_nodes: usize, + /// Host memory that must stay available after an insertion. + pub(crate) memory_floor: u64, + pub(crate) policy: PolicyParams, + /// The laptop profile of `auto` (smaller floor and ceiling). + pub(crate) laptop: bool, +} +impl PrefixConfig { + pub(crate) fn auto() -> Self { + Self { + budget: PrefixBudget::Auto, + block_tokens: 0, + max_nodes: 1024, + memory_floor: 3 << 30, + policy: PolicyParams::default(), + laptop: false, + } + } + pub(crate) fn validate(&self, capacity: usize) -> Result<(), Error> { + let block = self.resolved_block(capacity); + if block % 256 != 0 || block == 0 || block > capacity || self.max_nodes == 0 { + return Err(Error::InvalidDimension); + } + Ok(()) + } + pub(crate) fn resolved_block(&self, capacity: usize) -> usize { + if self.block_tokens == 0 { capacity } else { self.block_tokens } + } + /// Budget in bytes for the host memory available now; 0 = off. + pub(crate) fn resolve_budget(&self, mem_available: Option) -> u64 { + match self.budget { + PrefixBudget::Off => 0, + PrefixBudget::Bytes(bytes) => bytes, + PrefixBudget::Auto if self.laptop => budget::AutoBudget::laptop(mem_available).bytes(), + PrefixBudget::Auto => budget::AutoBudget::server(mem_available).bytes(), + } + } +} + +/// What the binding needs from the stack's owners. +pub(super) trait PrefixDevice { + type State: ByteSize; + type Block: ByteSize; + /// Prompt tokens the session holds. + fn position(&self) -> Result; + /// Expected sizes of a parked state and of a block of `block_tokens` cells. + fn estimate(&self, block_tokens: usize) -> (usize, usize); + /// Park the point the session stands at (a published prompt-chunk boundary). + fn park_state(&mut self) -> Result; + /// Park the cells `first .. first + tokens`. + fn park_block(&mut self, first: usize, tokens: usize) -> Result; + /// Install `state` and write `blocks` (`(block index, payload)`, each `block_tokens` cells from + /// `index * block_tokens`); the cells below the state's position that no block names already hold the prefix. + fn import(&mut self, state: &Self::State, blocks: &[(usize, &Self::Block)]) -> Result<(), Error>; + /// After `import`: re-anchor the draft ring at the state's snapshot and resynchronise the drafter. + fn restore_draft(&mut self, state: &Self::State, resume: usize) -> Result<(), Error>; + /// Host memory available now (`None` = unknown: insertion fails closed). + fn available_memory(&self) -> Option { + crate::conversation::memory::available_memory() + } +} + +/// Where a request starts reading. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct Start { + pub(super) resume: usize, + /// The positional buffer did not hold the request's prefix (another session ran in between, or nothing is live). + pub(super) switched: bool, + /// The checkpoint is a branch point: histories fork below it (a prefix shared by several sessions, or a rewrite). + pub(super) branch: bool, + /// Tokens whose cells were written back from host memory. + pub(super) copied_tokens: usize, + pub(super) import_ms: f64, + /// Microseconds the lookup of the deepest checkpoint took (hash chain + token comparison over the whole prompt). + pub(super) match_us: f64, +} + +/// What `after_chunk` did. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum ChunkOutcome { + /// Not a grid point, past the cacheable part, or the cache is off. + Nothing, + Exists, + Rejected(Reject), + /// The host is short of memory: nothing was built. + LowMemory, + Admitted { tokens: usize, new_blocks: usize, bytes: usize, park_ms: f64 }, +} + +struct Req { + /// Last prompt position a checkpoint may cover (the last prompt token starts the first verify window). + limit: usize, + /// The deepest grid point of this request: the likeliest resume point of the session's next request. + last_grid: usize, +} + +/// The policy, the store and the live-prefix bookkeeping, over the stack's payload types. +pub(super) struct PrefixServe { + cfg: PrefixConfig, + block_tokens: usize, + namespace: u64, + store: PrefixStore, + live: Vec, + req: Option, + /// Sizes measured on the last real payloads (the estimates for the next admission). + seen_state_bytes: Option, + seen_block_bytes: Option, + park_ms_request: f64, + consider_ms_request: f64, + admitted_request: u64, + /// Verification: the next requests neither look up nor add checkpoints (a full read on the same grid). + bypass: bool, + last_match_us: f64, + /// (milliseconds of the K/V + state import, milliseconds of the draft re-anchoring) of the last hit. + last_import_split: (f64, f64), +} + +fn lcp(a: &[i32], b: &[i32]) -> usize { + a.iter().zip(b).take_while(|(x, y)| x == y).count() +} + +impl PrefixServe { + /// `identity`: whatever makes two runtimes' caches interchangeable (model digest, KV format...), hashed with the + /// block size into the summary's namespace. + pub(super) fn new(cfg: PrefixConfig, capacity: usize, budget_bytes: u64, identity: &str) -> Self { + let block_tokens = cfg.resolved_block(capacity); + let namespace = fingerprint(&format!("{identity}|block={block_tokens}|chain={}", crate::prefix_cache::CHAIN_VERSION)); + let store = PrefixStore::new(StoreConfig { + block_tokens, + budget_bytes: usize::try_from(budget_bytes).unwrap_or(usize::MAX), + max_nodes: cfg.max_nodes, + policy: cfg.policy.clone(), + }); + Self { + cfg, + block_tokens, + namespace, + store, + live: Vec::new(), + req: None, + seen_state_bytes: None, + seen_block_bytes: None, + park_ms_request: 0.0, + consider_ms_request: 0.0, + admitted_request: 0, + bypass: false, + last_match_us: 0.0, + last_import_split: (0.0, 0.0), + } + } + + /// (import, draft re-anchoring) milliseconds of the last hit. + pub(super) fn last_import_split(&self) -> (f64, f64) { + self.last_import_split + } + + /// Microseconds the last lookup took (also on a miss). + pub(super) fn last_match_us(&self) -> f64 { + self.last_match_us + } + + /// While set, requests read their whole prompt from 0 on the grid and leave the store alone. + pub(super) fn set_bypass(&mut self, bypass: bool) { + self.bypass = bypass; + } + + pub(super) fn block_tokens(&self) -> usize { + self.block_tokens + } + pub(super) fn namespace(&self) -> u64 { + self.namespace + } + pub(super) fn stats(&self) -> &Stats { + self.store.stats() + } + pub(super) fn bytes(&self) -> usize { + self.store.bytes() + } + pub(super) fn budget_bytes(&self) -> usize { + self.store.config().budget_bytes + } + pub(super) fn node_count(&self) -> usize { + self.store.node_count() + } + pub(super) fn block_count(&self) -> usize { + self.store.block_count() + } + pub(super) fn live_tokens(&self) -> usize { + self.live.len() + } + pub(super) fn summary(&self, max_heads: usize) -> PrefixSummary { + PrefixSummary::build(&self.store, self.namespace, max_heads) + } + /// The `prefix_match` query: how much of a prompt (given as its chain) is cached. + pub(super) fn prefix_match(&self, chain: &[u64]) -> PrefixMatch { + PrefixMatch { + namespace: crate::prefix_cache::summary::hex(self.namespace), + block_tokens: self.block_tokens as u32, + cached_tokens: self.store.prefix_match(chain) as u32, + } + } + #[cfg(test)] + pub(super) fn store(&self) -> &PrefixStore { + &self.store + } + + /// The device state is unknown or gone: drop every checkpoint and the live claim. + pub(super) fn invalidate(&mut self) { + self.store.clear(); + self.live.clear(); + self.req = None; + } + + /// Head of a request: install the deepest checkpoint that is a prefix of `prompt`, if any (`None` = read from 0; + /// the caller resets the owners). An error leaves the owners in an unknown place; the caller drops the cache. + pub(super) fn begin>( + &mut self, + device: &mut D, + prompt: &[i32], + ) -> Result, Error> { + let g = self.block_tokens; + self.park_ms_request = 0.0; + self.consider_ms_request = 0.0; + self.admitted_request = 0; + if self.bypass { + self.req = None; + return Ok(None); + } + self.store.tick(prompt.len()); + let limit = prompt.len().saturating_sub(1); + self.req = Some(Req { limit, last_grid: limit / g * g }); + let lookup = Instant::now(); + let found = self.store.longest_match(prompt, limit); + let match_us = lookup.elapsed().as_secs_f64() * 1e6; + let Some(hit) = found else { + self.store.record_miss(); + self.last_match_us = match_us; + // the caller resets the owners to the empty prompt, which also rewrites the first index row: no cell of the + // buffer is claimed any more, even if the request is cancelled before its first chunk + self.live.clear(); + return Ok(None); + }; + // Cells of the positional buffer that already hold this prefix. A request that extends everything the buffer + // holds is the session's own continuation (no copy needed beyond what the buffer lacks); one that leaves it + // somewhere inside came after another session. Whether the HIT is shared evidence is a different question: it is + // when histories fork below the node (`is_branch_point`), whichever session ran last. + let common_full = lcp(&self.live, &prompt[..limit]); + let continuation = !self.live.is_empty() && common_full == self.live.len(); + let switched = !continuation; + let branch = self.store.is_branch_point(hit.key); + let common = common_full.min(hit.tokens); + let copy = common < hit.tokens; + let started = Instant::now(); + let first_block = common / g; + let blocks = if copy { self.store.blocks_from(hit.key, first_block).ok_or(Error::IdentityMismatch)? } else { Vec::new() }; + let state = self.store.node_payload(hit.key).ok_or(Error::IdentityMismatch)?; + // the import overwrites every cell from the first named block on + self.live.truncate(if blocks.is_empty() { common } else { first_block * g }); + device.import(state, &blocks)?; + let imported_ms = started.elapsed().as_secs_f64() * 1e3; + device.restore_draft(state, hit.tokens)?; + let copied_tokens = blocks.len() * g; + let import_ms = started.elapsed().as_secs_f64() * 1e3; + self.last_import_split = (imported_ms, import_ms - imported_ms); + self.live.clear(); + self.live.extend_from_slice(&prompt[..hit.tokens]); + self.last_match_us = match_us; + self.store.record_hit_as(&hit, branch); + Ok(Some(Start { resume: hit.tokens, switched, branch, copied_tokens, import_ms, match_us })) + } + + /// The prefill is about to write the cells from `first` on. + pub(super) fn before_chunk(&mut self, first: usize) { + self.live.truncate(first); + } + + /// A chunk ending at `end` was published: the cells below `end` are this prompt's; maybe checkpoint there. + /// An error means the checkpoint could not be built (the caller drops the cache, the request goes on). + pub(super) fn after_chunk>( + &mut self, + device: &mut D, + prompt: &[i32], + end: usize, + ) -> Result { + let g = self.block_tokens; + if self.live.len() <= end { + let have = self.live.len(); + self.live.extend_from_slice(&prompt[have..end]); + } + let Some(req) = self.req.as_ref() else { return Ok(ChunkOutcome::Nothing) }; + if end == 0 || end % g != 0 || end > req.limit { + return Ok(ChunkOutcome::Nothing); + } + let frontier = end == req.last_grid; + let (est_state, est_block) = device.estimate(g); + let est_state = self.seen_state_bytes.unwrap_or(est_state); + let est_block = self.seen_block_bytes.unwrap_or(est_block); + let considering = Instant::now(); + let verdict = self.store.consider(&prompt[..end], frontier, est_state, est_block); + self.consider_ms_request += considering.elapsed().as_secs_f64() * 1e3; + let candidate = match verdict { + Consider::Exists => return Ok(ChunkOutcome::Exists), + Consider::Rejected(why) => return Ok(ChunkOutcome::Rejected(why)), + Consider::Admit(candidate) => candidate, + }; + let additional = (est_state + candidate.missing.len() * est_block) as u64; + if !budget::admit_growth(device.available_memory(), additional, self.cfg.memory_floor) { + self.store.abort(candidate); + return Ok(ChunkOutcome::LowMemory); + } + let started = Instant::now(); + let state = device.park_state()?; + if device.position()? != end as u64 { + return Err(Error::IdentityMismatch); + } + let mut blocks = Vec::with_capacity(candidate.missing.len()); + for &j in &candidate.missing { + blocks.push((j, device.park_block(j * g, g)?)); + } + self.seen_state_bytes = Some(state.byte_size()); + if let Some((_, block)) = blocks.first() { + self.seen_block_bytes = Some(block.byte_size()); + } + let new_blocks = blocks.len(); + let bytes = state.byte_size() + blocks.iter().map(|(_, b)| b.byte_size()).sum::(); + let park_ms = started.elapsed().as_secs_f64() * 1e3; + self.store.commit(candidate, &prompt[..end], state, blocks).map_err(|_| Error::IdentityMismatch)?; + self.park_ms_request += park_ms; + self.admitted_request += 1; + Ok(ChunkOutcome::Admitted { tokens: end, new_blocks, bytes, park_ms }) + } + + /// The request is over. `completed` is false when the owners are lost (the checkpoints and the live claim go); + /// a cancelled request is completed: its chunks kept the live claim honest. + pub(super) fn finish(&mut self, completed: bool) { + self.req = None; + if !completed { + self.invalidate(); + } + } + + /// Admissions of the request just served and the time spent parking them. + pub(super) fn request_parking(&self) -> (u64, f64, f64) { + (self.admitted_request, self.park_ms_request, self.consider_ms_request) + } + + /// The metrics line. + pub(super) fn describe(&self) -> String { + let s = self.store.stats(); + format!( + "prefix stats: nodes={} blocks={} used_mib={} budget_mib={} requests={} hits={} shared_hits={} misses={} reused_tokens={} prompt_tokens={} admitted={} rejected={} evicted={} already_cached={} live_tokens={}", + self.store.node_count(), + self.store.block_count(), + self.store.bytes() >> 20, + self.store.config().budget_bytes >> 20, + s.requests, + s.hits, + s.shared_hits, + s.misses, + s.reused_tokens, + s.prompt_tokens, + s.admitted, + s.rejected + s.rejected_after_build, + s.evicted, + s.already_cached, + self.live.len() + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::backend::original_prompt::{PromptOptions, PromptPath, PromptPlan}; + + const G: usize = 256; + + /// A payload with a size. + struct Bytes(usize); + impl ByteSize for Bytes { + fn byte_size(&self) -> usize { + self.0 + } + } + /// The state a fake device parks: where the session stood, and a digest of the tokens it had read. + struct State { + position: u64, + digest: u64, + } + impl ByteSize for State { + fn byte_size(&self) -> usize { + 100 + } + } + struct Block { + cells: Vec, + } + impl ByteSize for Block { + fn byte_size(&self) -> usize { + self.cells.len() * 4 + } + } + + /// A device whose positional buffer is a token per cell and whose recurrent state is a digest of every token + /// read in order, so a restore that mixes up cells or states is visible as soon as it is used. + struct Fake { + cells: Vec, + position: u64, + digest: u64, + log: Vec, + fail_import: bool, + available: Option, + } + impl Fake { + fn new() -> Self { + Self { cells: vec![-1; 1 << 16], position: 0, digest: 0, log: Vec::new(), fail_import: false, available: Some(1 << 40) } + } + fn read(&mut self, tokens: &[i32], first: usize) { + assert_eq!(first as u64, self.position, "chunks are contiguous"); + for (i, &t) in tokens.iter().enumerate() { + self.cells[first + i] = t; + self.digest = self.digest.wrapping_mul(1_000_003).wrapping_add(t as u64 + 7); + } + self.position += tokens.len() as u64; + } + } + impl PrefixDevice for Fake { + type State = State; + type Block = Block; + fn position(&self) -> Result { + Ok(self.position) + } + fn estimate(&self, block_tokens: usize) -> (usize, usize) { + (100, block_tokens * 4) + } + fn park_state(&mut self) -> Result { + Ok(State { position: self.position, digest: self.digest }) + } + fn park_block(&mut self, first: usize, tokens: usize) -> Result { + assert!((first + tokens) as u64 <= self.position, "only cells the session has read"); + Ok(Block { cells: self.cells[first..first + tokens].to_vec() }) + } + fn import(&mut self, state: &State, blocks: &[(usize, &Block)]) -> Result<(), Error> { + if self.fail_import { + return Err(Error::CudaExecution); + } + for (j, block) in blocks { + self.cells[j * G..j * G + block.cells.len()].copy_from_slice(&block.cells); + } + self.log.push(format!("import {} blocks={}", state.position, blocks.len())); + self.position = state.position; + self.digest = state.digest; + Ok(()) + } + fn restore_draft(&mut self, _: &State, resume: usize) -> Result<(), Error> { + self.log.push(format!("draft {resume}")); + Ok(()) + } + fn available_memory(&self) -> Option { + self.available + } + } + + fn cfg() -> PrefixConfig { + PrefixConfig { block_tokens: G, ..PrefixConfig::auto() } + } + fn serve() -> PrefixServe { + PrefixServe::new(cfg(), 1024, 1 << 30, "test") + } + + /// One request against the fake: begin, read the plan's chunks on the grid, finish. Returns (start, digest the + /// session holds at the end of the prefill = a function of all tokens read). + fn request(s: &mut PrefixServe, d: &mut Fake, prompt: &[i32], stop_after_chunks: Option) -> (Option, u64) { + let start = s.begin(d, prompt).unwrap(); + let resume = match &start { + Some(st) => st.resume, + None => { + // the caller resets the owners; the cells stay where they are + d.position = 0; + d.digest = 0; + 0 + } + }; + let tokens: Vec = prompt.iter().map(|&t| t as u32).collect(); + let options = PromptOptions { grid: s.block_tokens(), prompt_cache: false, turn_token: None, root_min: 0, force_batched: true, ..PromptOptions::original_mode17(1 << 16) }; + let mut chunks = 0; + for action in PromptPlan::new(&tokens, resume, None, None, options, 1024).unwrap() { + if action.path == PromptPath::FinalSeed { + break; + } + if stop_after_chunks == Some(chunks) { + // cancelled before this chunk + s.finish(true); + return (start, d.digest); + } + s.before_chunk(action.first); + // a chunk interrupted half way would have written part of its cells: model it by a failing chunk + d.read(&prompt[action.first..action.first + action.count], action.first); + s.after_chunk(d, prompt, action.first + action.count).unwrap(); + chunks += 1; + } + assert_eq!(d.position as usize, prompt.len() - 1); + // the invariant that matters: the cells the session reads are this prompt's + assert_eq!(&d.cells[..prompt.len() - 1], &prompt[..prompt.len() - 1]); + s.finish(true); + (start, d.digest) + } + + /// A token that depends on the stream `seed` and the position `i` (ids stay inside the vocabulary). + fn tok(seed: i32, i: usize) -> i32 { + ((i64::from(seed) * 1_000_003 + i as i64 * 7919) % 247_000 + 1) as i32 + } + fn doc(seed: i32, blocks: usize, extra: usize) -> Vec { + (0..blocks * G + extra).map(|i| tok(seed, i)).collect() + } + /// `shared` leading blocks from a common system prompt, then the session's own tokens. + fn session(id: i32, shared: usize, total: usize, extra: usize) -> Vec { + let mut t = doc(0, shared, 0); + t.extend((shared * G..total * G + extra).map(|i| tok(id, i))); + t + } + fn full_digest(prompt: &[i32]) -> u64 { + let mut d = Fake::new(); + d.read(&prompt[..prompt.len() - 1], 0); + d.digest + } + + #[test] + fn a_second_session_with_the_same_system_prompt_resumes_from_the_shared_blocks_and_ends_in_the_full_reads_state() { + let mut s = serve(); + let mut d = Fake::new(); + let a = session(1, 4, 8, 50); + let b = session(2, 4, 8, 50); + let (start, digest) = request(&mut s, &mut d, &a, None); + assert_eq!(start, None); + assert_eq!(digest, full_digest(&a)); + // A's checkpoints: every grid point of its prompt was admitted (room is plentiful) + assert_eq!(s.node_count(), 8); + assert_eq!(s.block_count(), 8); + // B reads the same system prompt: resumes at 4 blocks, building on A's blocks + d.log.clear(); + let (start, digest) = request(&mut s, &mut d, &b, None); + let start = start.unwrap(); + assert_eq!((start.resume, start.switched, start.branch), (4 * G, true, true)); + assert_eq!(start.copied_tokens, 0, "the buffer held A, whose first four blocks are the shared prompt: nothing to write back"); + assert_eq!(digest, full_digest(&b), "the resumed read ends in exactly the full read's state"); + assert_eq!(s.stats().hits, 1); + assert_eq!(s.stats().shared_hits, 1); + // B's own blocks were added, the shared four were not stored again + assert_eq!(s.block_count(), 12); + } + + #[test] + fn interleaved_sessions_each_resume_from_their_own_deepest_checkpoint() { + let mut s = serve(); + let mut d = Fake::new(); + let mut prompts = [session(1, 4, 6, 10), session(2, 4, 6, 10), session(3, 4, 6, 10)]; + let mut last_len = [0usize; 3]; + for turn in 0..4 { + for (i, p) in prompts.iter_mut().enumerate() { + let (start, digest) = request(&mut s, &mut d, p, None); + assert_eq!(digest, full_digest(p), "turn {turn} session {i}"); + let resume = start.map_or(0, |st| st.resume); + let expected = match (turn, i) { + (0, 0) => 0, + (0, _) => 4 * G, // the shared system prompt + // the session's own deepest checkpoint: the grid point at or below its previous prefill end + _ => (last_len[i] - 1) / G * G, + }; + assert_eq!(resume, expected, "turn {turn} session {i}"); + last_len[i] = p.len(); + // the agent appends a tool result: one more block and a bit + p.extend(doc(1000 + (i as i32 + 1) * 10 + turn, 1, 30)); + } + } + // sharing: the system prompt's four blocks exist once per cached chain, not once per session + assert!(s.stats().shared_hits >= 2); + assert!(s.stats().hits >= 11); + } + + #[test] + fn a_miss_resets_the_owners_so_nothing_is_claimed_even_if_the_request_is_cancelled_before_its_first_chunk() { + let mut s = serve(); + let mut d = Fake::new(); + let a = session(1, 0, 4, 10); + request(&mut s, &mut d, &a, None); + assert_eq!(s.live_tokens(), a.len() - 1); + // another session misses: the owners are reset (the empty-prompt rollback rewrites the first index row), then the + // request is cancelled before it read anything + let b = session(2, 0, 4, 10); + assert_eq!(s.begin(&mut d, &b).unwrap(), None); + assert_eq!(s.live_tokens(), 0); + s.finish(true); + // A comes back: it resumes from its checkpoints and every cell is written back (none is claimed from the buffer) + let (start, digest) = request(&mut s, &mut d, &a, None); + let start = start.unwrap(); + assert_eq!((start.resume, start.copied_tokens), (4 * G, 4 * G)); + assert_eq!(digest, full_digest(&a)); + } + + #[test] + fn the_same_session_continuing_copies_no_cells() { + let mut s = serve(); + let mut d = Fake::new(); + let mut p = session(1, 0, 6, 10); + request(&mut s, &mut d, &p, None); + p.extend(doc(777, 1, 40)); + let (start, digest) = request(&mut s, &mut d, &p, None); + let start = start.unwrap(); + assert_eq!((start.resume, start.switched, start.branch, start.copied_tokens), (6 * G, false, false, 0)); + assert_eq!(digest, full_digest(&p)); + } + + #[test] + fn switching_to_another_session_and_back_writes_back_only_what_the_buffer_lost() { + let mut s = serve(); + let mut d = Fake::new(); + let a = session(1, 2, 8, 10); + let b = session(2, 2, 8, 10); + request(&mut s, &mut d, &a, None); + request(&mut s, &mut d, &b, None); + // A again: the buffer holds B; the first 2 blocks are shared, so only A's later cells are written back + let (start, digest) = request(&mut s, &mut d, &a, None); + let start = start.unwrap(); + assert_eq!(start.resume, 8 * G); + assert!(start.switched); + assert_eq!(start.copied_tokens, 6 * G, "blocks 2..8; the two shared blocks were in the buffer"); + assert_eq!(digest, full_digest(&a)); + } + + #[test] + fn a_cancelled_prefill_never_claims_cells_it_did_not_finish() { + let mut s = serve(); + let mut d = Fake::new(); + let a = session(1, 0, 8, 10); + // cancelled after 3 of 8 chunks + request(&mut s, &mut d, &a, Some(3)); + assert_eq!(s.live_tokens(), 3 * G); + assert_eq!(s.node_count(), 3, "the checkpoints of the finished chunks are good"); + // the buffer gets scribbled over by a different request, then A is retried + let b = session(2, 0, 8, 10); + request(&mut s, &mut d, &b, Some(1)); + let (start, digest) = request(&mut s, &mut d, &a, None); + let start = start.unwrap(); + assert_eq!(start.resume, 3 * G); + assert_eq!(digest, full_digest(&a), "restored from the 3-block checkpoint, finished, and equal to a full read"); + } + + #[test] + fn a_failed_import_is_an_error_for_the_caller_and_invalidate_forgets_everything() { + let mut s = serve(); + let mut d = Fake::new(); + let a = session(1, 0, 4, 10); + request(&mut s, &mut d, &a, None); + let mut longer = a.clone(); + longer.extend(doc(555, 2, 0)); + d.fail_import = true; + assert!(s.begin(&mut d, &longer).is_err()); + s.invalidate(); + d.fail_import = false; + assert_eq!((s.node_count(), s.block_count(), s.live_tokens()), (0, 0, 0)); + let (start, digest) = request(&mut s, &mut d, &longer, None); + assert_eq!(start, None); + assert_eq!(digest, full_digest(&longer)); + // a lost owner (finish(false)) forgets too + s.finish(false); + assert_eq!(s.node_count(), 0); + } + + #[test] + fn the_budget_bounds_the_store_and_the_newest_frontier_survives() { + // room for ~3 states and 6 blocks of 256 tokens (1 KiB each here) + let mut s = PrefixServe::new(cfg(), 1024, 3 * 100 + 9 * 1024, "test"); + let mut d = Fake::new(); + let mut p = session(1, 0, 4, 10); + for turn in 0..6 { + let (_, digest) = request(&mut s, &mut d, &p, None); + assert_eq!(digest, full_digest(&p)); + assert!(s.bytes() <= s.budget_bytes(), "turn {turn}: {} > {}", s.bytes(), s.budget_bytes()); + p.extend(doc(turn + 3000, 1, 5)); + } + assert!(s.stats().evicted + s.stats().rejected > 0, "the budget forced choices"); + // the last request's deepest checkpoint is cached + let last = (p.len() - (G + 5) - 1) / G * G; + let hit = s.store().longest_match(&p, p.len() - 1).unwrap(); + assert_eq!(hit.tokens, last); + } + + #[test] + fn low_host_memory_skips_the_checkpoint_instead_of_building_it() { + let mut s = serve(); + let mut d = Fake::new(); + d.available = Some(1 << 20); // below the 3 GiB floor + let a = session(1, 0, 3, 10); + let start = s.begin(&mut d, &a).unwrap(); + assert_eq!(start, None); + d.read(&a[..G], 0); + s.before_chunk(0); + assert_eq!(s.after_chunk(&mut d, &a, G).unwrap(), ChunkOutcome::LowMemory); + assert_eq!(s.node_count(), 0); + d.available = None; + assert_eq!(s.after_chunk(&mut d, &a, G).unwrap(), ChunkOutcome::LowMemory, "unknown telemetry fails closed"); + } + + #[test] + fn the_pool_queries_see_the_cached_prefixes() { + let mut s = serve(); + let mut d = Fake::new(); + let a = session(1, 3, 6, 10); + request(&mut s, &mut d, &a, None); + let chain = crate::prefix_cache::chain(&a, G); + let m = s.prefix_match(&chain); + assert_eq!((m.cached_tokens as usize, m.block_tokens as usize), (6 * G, G)); + // another session that shares 3 blocks + let other = crate::prefix_cache::chain(&session(2, 3, 6, 10), G); + assert_eq!(s.prefix_match(&other).cached_tokens as usize, 3 * G); + let summary = s.summary(100); + assert_eq!(summary.namespace, m.namespace); + assert_eq!(summary.match_tokens(&chain) as usize, 6 * G); + assert!(s.describe().contains("nodes=6")); + } + + #[test] + fn config_resolution_follows_the_operator() { + let cfg = PrefixConfig::auto(); + assert_eq!(cfg.resolved_block(8192), 8192); + assert_eq!(cfg.resolved_block(1024), 1024); + assert_eq!(PrefixConfig { block_tokens: 2048, ..PrefixConfig::auto() }.resolved_block(8192), 2048); + assert!(cfg.validate(1024).is_ok()); + assert!(PrefixConfig { block_tokens: 300, ..PrefixConfig::auto() }.validate(1024).is_err()); + assert!(PrefixConfig { block_tokens: 4096, ..PrefixConfig::auto() }.validate(2048).is_err()); + assert_eq!(PrefixConfig { budget: PrefixBudget::Off, ..PrefixConfig::auto() }.resolve_budget(Some(1 << 40)), 0); + assert_eq!(PrefixConfig { budget: PrefixBudget::Bytes(5), ..PrefixConfig::auto() }.resolve_budget(None), 5); + assert_eq!(PrefixConfig::auto().resolve_budget(None), 0); + assert!(PrefixConfig::auto().resolve_budget(Some(80 << 30)) > (30 << 30)); + // the 5090 server after the expert source: a few GiB, not nothing + let server = PrefixConfig::auto().resolve_budget(Some(14 << 30)); + assert!(server >= (7 << 30) && server <= (8 << 30), "{server}"); + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs index 47e95391..7b59312d 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs @@ -38,7 +38,7 @@ use super::{ original_spec_controller::{OriginalSpecController, SpecError}, output_native::{OriginalNativeOutput, OriginalNativePenaltyHistory}, session::{ - original_prompt::{draft::OriginalDraftCheckpoint, OriginalPromptInput, OriginalSessionCheckpoint}, + original_prompt::{draft::OriginalDraftCheckpoint, OriginalPromptInput, OriginalSessionCheckpoint, ParkedBlock, ParkedSession}, QwenSession, }, }; @@ -56,6 +56,15 @@ mod conversation; pub(crate) use conversation::{ConversationConfig, TURN_TOKEN}; use conversation::{ResumeDevice, ServeConversation}; +#[path = "original_serve_prefix.rs"] +mod prefix; +pub(crate) use prefix::{PrefixBudget, PrefixConfig}; +use prefix::{ChunkOutcome, PrefixDevice, PrefixServe}; +use crate::prefix_cache::{ByteSize, PrefixMatch, PrefixSummary}; + +/// The digest of the pinned model's first shard: part of the prefix cache's namespace. +const PINNED_MODEL: &str = "sha256:4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3"; + /// Prompt-chunk capacities the Original prefill admits (`PromptPlan::new`), ascending. pub(crate) const ADMITTED_CAPACITIES: [usize; 10] = [256, 512, 1024, 2048, 3072, 4096, 6144, 8192, 16384, 32768]; /// The default chunk. The Original sizes it from the free expert-cache slots (`--prefill-auto`); with no GPU @@ -89,6 +98,11 @@ pub(crate) struct StackConfig { /// generate.cpp's conversation cache (`--prompt-cache` and friends); on by default with the Original's /// settings (`--prompt-cache 6`). `None` reads every request from the empty prompt. pub(crate) conversation: Option, + /// The cross-session prefix cache (`--prefix-cache-mib`, `docs/prefix-cache.md`). When it is on it REPLACES the + /// conversation cache: the prompt is read on a token grid and any request resumes from the deepest checkpoint + /// that is a prefix of its prompt, whichever session built it. `None` (the default) leaves the conversation + /// cache in charge. + pub(crate) prefix: Option, /// The VRAM expert tier (`--expert-cache`, `--expert-cache-per-layer`, `--expert-profile`, `--pcie-frac`, /// `--adapt-every/--adapt-swaps`). Off by default: every routed expert on the CPU pool. pub(crate) expert_tier: ExpertTierConfig, @@ -106,6 +120,7 @@ impl StackConfig { kv_format: KvFormat::Int8, kv_resident: leleka_cuda_driver::KV_RESIDENT_DEFAULT_CELLS, conversation: Some(ConversationConfig::original()), + prefix: None, expert_tier: ExpertTierConfig::off(), } } @@ -129,6 +144,9 @@ impl StackConfig { if let Some(conversation) = &self.conversation { conversation.validate()?; } + if let Some(prefix) = &self.prefix { + prefix.validate(self.capacity)?; + } self.expert_tier.validate() } } @@ -146,6 +164,28 @@ struct StackPoint<'ctx> { draft: OriginalDraftCheckpoint, } +/// A prefix-cache checkpoint of the stack: the session's recurrent state and the draft ring's snapshot at one grid point. +struct StackState { + session: ParkedSession, + draft: OriginalDraftCheckpoint, +} +impl ByteSize for StackState { + fn byte_size(&self) -> usize { + self.session.host_bytes() + self.draft.host_bytes() + } +} +/// The K/V cells and index rows of one block of the twelve resident QSA layers. +struct StackBlock(ParkedBlock); +impl ByteSize for StackBlock { + fn byte_size(&self) -> usize { + self.0.host_bytes() + } +} +/// Bytes of one cell across the twelve layers: INT8 K+V with scales (1056 B) and the pooled index key (128 B). +const PARKED_BYTES_PER_TOKEN: usize = 12 * (1056 + 128); +/// Expected size of a parked state before one was measured (GDN/PLE images, the draft ring, the index tails). +const PARKED_STATE_ESTIMATE: usize = 120 << 20; + fn plan_error(error: PlanError) -> Error { match error { PlanError::InvalidInput => Error::InvalidDimension, @@ -172,6 +212,8 @@ pub(crate) struct OriginalServeStack<'a, 'ctx> { empty_draft: OriginalDraftCheckpoint, /// The conversation cache (checkpoints hold priors and snapshots of the owners below: dropped first). conversation: Option>>, + /// The prefix cache (`StackConfig::prefix`); replaces `conversation` when set. + prefix: Option>, /// Prompt tokens the last request did not read again. reused: usize, /// Where the conversation cache placed the last request (`reused`, or the re-read checkpoint's length). @@ -306,7 +348,35 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { let pool = CpuExpertPool::new(binding, config.cpu_workers).map_err(at("CpuExpertPool::new"))?; let empty_session = executor.checkpoint_session(binding, &mut session).map_err(at("checkpoint_session"))?; let empty_draft = draft.checkpoint(binding, &session).map_err(at("draft.checkpoint"))?; - let conversation = config.conversation.clone().map(ServeConversation::new); + let prefix = match &config.prefix { + Some(prefix_config) => { + let available = crate::conversation::memory::available_memory(); + let bytes = prefix_config.resolve_budget(available); + if bytes == 0 { + operator_note(&format!( + "prefix cache off (budget {:?}, available host memory {:?} MiB)", + prefix_config.budget, + available.map(|b| b >> 20) + )); + None + } else { + let identity = format!("qwen4exp:{PINNED_MODEL}:kv={:?}:resident={}", config.kv_format, config.kv_resident); + let serve = PrefixServe::new(prefix_config.clone(), config.capacity, bytes, &identity); + operator_note(&format!( + "prefix cache on: block/grid {} tokens, budget {} MiB, state ~{} MiB + {} B per token, host memory available {:?} MiB, namespace {}", + serve.block_tokens(), + bytes >> 20, + PARKED_STATE_ESTIMATE >> 20, + PARKED_BYTES_PER_TOKEN, + available.map(|b| b >> 20), + crate::prefix_cache::summary::hex(serve.namespace()) + )); + Some(serve) + } + } + None => None, + }; + let conversation = if prefix.is_some() { None } else { config.conversation.clone().map(ServeConversation::new) }; let residency = ResidencyState::new(&config.expert_tier); let mut loan = None; let expert_cache = match original_serve_residency::open_tier(binding, context, &moe, &config.expert_tier, config.capacity) @@ -342,6 +412,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { binding, context, conversation, + prefix, reused: 0, resume_point: 0, full_policy: mtp_full_policy(&rope), @@ -465,6 +536,36 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { if let Some(conversation) = self.conversation.as_mut() { conversation.invalidate(); } + if let Some(prefix) = self.prefix.as_mut() { + prefix.invalidate(); + } + } + + /// Verification arm: while set, requests read their whole prompt on the grid without using or changing the prefix + /// cache (the reference a cached request must reproduce). + #[allow(dead_code)] + pub(crate) fn prefix_bypass(&mut self, bypass: bool) { + if let Some(prefix) = self.prefix.as_mut() { + prefix.set_bypass(bypass); + } + } + + /// The prefix cache's summary for a front router (`None` when the cache is off). + #[allow(dead_code)] + pub(crate) fn prefix_summary(&self, max_heads: usize) -> Option { + self.prefix.as_ref().map(|prefix| prefix.summary(max_heads)) + } + + /// The `prefix_match` query: how many tokens of the prompt whose block hash chain is `chain` are cached. + #[allow(dead_code)] + pub(crate) fn prefix_match(&self, chain: &[u64]) -> Option { + self.prefix.as_ref().map(|prefix| prefix.prefix_match(chain)) + } + + /// The prefix cache's metrics line (`None` when the cache is off). + #[allow(dead_code)] + pub(crate) fn prefix_metrics(&self) -> Option { + self.prefix.as_ref().map(|prefix| prefix.describe()) } /// Close every owner in dependency order; the first failure is reported after all were attempted. @@ -906,10 +1007,13 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { force_batched: true, verify_width: 4, auto_max: 8192, + grid: 0, }; - let (options, reread_to) = match &self.conversation { - Some(conversation) => (conversation.config().plan_options(options), conversation.reread_to()), - None => (options, None), + let (options, reread_to) = match (&self.prefix, &self.conversation) { + // the prefix cache reads on its grid and has no turn/root cuts: every checkpoint is a pure function of its tokens + (Some(prefix), _) => (PromptOptions { grid: prefix.block_tokens(), ..options }, None), + (None, Some(conversation)) => (conversation.config().plan_options(options), conversation.reread_to()), + (None, None) => (options, None), }; let capacity = self.config.capacity; let plan = PromptPlan::new(&tokens, resume, reread_to, None, options, capacity).map_err(|e| { crate::bringup_trace!("DBG[{:.0}s] PromptPlan::new err {e:?} (n={n} capacity={capacity})", dbg_el()); plan_error(e) })?; @@ -930,8 +1034,12 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { if cancel() { return Err(SpecError::Cancelled); } + if let Some(prefix) = self.prefix.as_mut() { + prefix.before_chunk(action.first); + } self.prefill_chunk(&source, action.count, cancel)?; self.after_prompt_action(&request.prompt, &action); + self.prefix_after_chunk(&request.prompt, action.first + action.count); } if self.session.target_origin()?.next_position() != (n as u64 - 1) { return Err(Error::IdentityMismatch.into()); @@ -983,6 +1091,26 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { ran } + /// The prefix cache after a published chunk: a checkpoint at the grid point if the policy wants one. A checkpoint + /// that cannot be built costs the cache, never the request. + fn prefix_after_chunk(&mut self, prompt: &[i32], end: usize) { + let Some(mut prefix) = self.prefix.take() else { return }; + let _span = profile::span("prefix.after_chunk"); + match prefix.after_chunk(self, prompt, end) { + Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { + if std::env::var_os("LELEKA_PREFIX_TRACE").is_some() { + operator_text(&format!("prefix admit: tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20)); + } + } + Ok(_) => {} + Err(error) => { + operator_text(&format!("prefix cache: {error:?} while checkpointing; dropping the cache")); + prefix.invalidate(); + } + } + self.prefix = Some(prefix); + } + /// The conversation cache's bookkeeping after a published chunk. A checkpoint that cannot be saved costs /// the cache, never the request: the cache is dropped and the request goes on. fn after_prompt_action(&mut self, prompt: &[i32], action: &crate::backend::original_prompt::PromptAction) { @@ -1124,6 +1252,110 @@ impl<'a, 'ctx> ResumeDevice for OriginalServeStack<'a, 'ctx> { } } +impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { + /// `RequestOwners::resume` with the prefix cache: install the deepest checkpoint that is a prefix of the prompt. + fn prefix_resume(&mut self, request: &ServeRequest) -> Option { + let mut prefix = self.prefix.take()?; + let _resume_span = profile::span("request.resume"); + let n = request.prompt.len(); + let resume = if self.broken.is_some() { + prefix.invalidate(); + None + } else { + match prefix.begin(self, &request.prompt) { + Ok(Some(start)) => { + self.reused = start.resume; + self.resume_point = start.resume; + operator_text(&format!( + "prefix request: n={n} hit=yes resume={} switched={} branch={} copied_tokens={} import_ms={:.1} (state+kv {:.1}, draft {:.1}) match_us={:.0} live_tokens={}", + start.resume, + start.switched, + start.branch, + start.copied_tokens, + start.import_ms, + prefix.last_import_split().0, + prefix.last_import_split().1, + start.match_us, + prefix.live_tokens() + )); + Some(start.resume) + } + Ok(None) => { + operator_text(&format!("prefix request: n={n} hit=no resume=0 match_us={:.0}", prefix.last_match_us())); + None + } + Err(error) => { + // the cache is an optimisation: drop it and start from the empty prompt (`reset`) + operator_text(&format!("prefix cache: {error:?}; reading the whole prompt")); + prefix.invalidate(); + None + } + } + }; + self.prefix = Some(prefix); + resume + } +} + +/// The prefix cache's device side over the stack's own owners. +impl<'a, 'ctx> PrefixDevice for OriginalServeStack<'a, 'ctx> { + type State = StackState; + type Block = StackBlock; + fn position(&self) -> Result { + Ok(self.session.target_origin()?.next_position()) + } + fn estimate(&self, block_tokens: usize) -> (usize, usize) { + (PARKED_STATE_ESTIMATE, block_tokens * PARKED_BYTES_PER_TOKEN) + } + fn park_state(&mut self) -> Result { + if let Some(error) = self.broken { + return Err(error); + } + let _p = profile::span("prefix.park_state"); + let session = self.executor.park_session(self.binding, &mut self.session)?; + let draft = self.draft.checkpoint(self.binding, &self.session)?; + Ok(StackState { session, draft }) + } + fn park_block(&mut self, first: usize, tokens: usize) -> Result { + if let Some(error) = self.broken { + return Err(error); + } + let _p = profile::span("prefix.park_block"); + self.executor.park_block(&self.session, first, tokens).map(StackBlock) + } + fn import(&mut self, state: &StackState, blocks: &[(usize, &StackBlock)]) -> Result<()> { + if let Some(error) = self.broken { + return Err(error); + } + let blocks: Vec<&ParkedBlock> = blocks.iter().map(|(_, block)| &block.0).collect(); + let _p = profile::span("prefix.import_session"); + // a refused import touches nothing; a failed physical one poisons the executor + let imported = self.executor.import_session(self.binding, &self.dense, &mut self.session, &state.session, &blocks); + if let Err(error) = imported { + self.mark_broken(error); + } + imported + } + fn restore_draft(&mut self, state: &StackState, resume: usize) -> Result<()> { + if let Some(error) = self.broken { + return Err(error); + } + let result = (|| { + { + let _p = profile::span("prefix.draft_resume_at"); + self.draft.resume_at(self.binding, &self.dense, &self.session, &state.draft)?; + } + let upto = i64::try_from(resume).map_err(|_| Error::Overflow)?; + let _p = profile::span("prefix.mtp_kv_restore"); + self.executor.mtp_kv_restore(self.binding, &self.session, &mut self.draft, upto) + })(); + if let Err(error) = result { + self.mark_broken(error); + } + result + } +} + impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> { fn is_fresh(&self) -> bool { self.broken.is_none() @@ -1148,6 +1380,9 @@ impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> { fn resume(&mut self, request: &ServeRequest) -> Option { self.reused = 0; self.resume_point = 0; + if self.prefix.is_some() { + return self.prefix_resume(request); + } let mut conversation = self.conversation.take()?; let _resume_span = profile::span("request.resume"); let resume = if self.broken.is_some() { @@ -1230,6 +1465,11 @@ impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> { if let Some(conversation) = self.conversation.as_mut() { conversation.finish(completed); } + if let Some(prefix) = self.prefix.as_mut() { + prefix.finish(completed); + let (admitted, park_ms, consider_ms) = prefix.request_parking(); + operator_text(&format!("prefix request done: admitted={admitted} park_ms={park_ms:.1} policy_ms={consider_ms:.1} {}", prefix.describe())); + } } } diff --git a/crates/leleka-runtime/src/qwen_forward/qsa_resident_device.rs b/crates/leleka-runtime/src/qwen_forward/qsa_resident_device.rs index e80f09ba..6a3e7077 100644 --- a/crates/leleka-runtime/src/qwen_forward/qsa_resident_device.rs +++ b/crates/leleka-runtime/src/qwen_forward/qsa_resident_device.rs @@ -60,6 +60,10 @@ impl<'ctx> ResidentQsaPrior<'ctx>{ Ok(Self(Rc::new(Prior{binding:self.0.binding.clone(),owner:self.0.owner.clone(),origin,layer:self.0.layer,provider:self.0.provider.clone(),index,kv}))) } } +/// One layer's share of a parked block: the host K/V pages and the pooled index rows of `tokens` cells from +/// `first_token` (prefix cache; plain bytes, no lineage). +pub(in crate::qwen_forward) struct ParkedLayerSpan{pub(in crate::qwen_forward) first_token:usize,pub(in crate::qwen_forward) tokens:usize,pub(in crate::qwen_forward) kv:Vec,pub(in crate::qwen_forward) index:Vec} +impl ParkedLayerSpan{pub(in crate::qwen_forward) fn bytes(&self)->usize{self.kv.len()+self.index.len()}} pub(in crate::qwen_forward) struct ResidentQsaLayer<'ctx>{context:&'ctx Context<'ctx>,index:OriginalQsaResidentIndex<'ctx>,kv:OriginalQsaMappedJournal<'ctx>,current:ResidentQsaPrior<'ctx>} impl<'ctx> ResidentQsaLayer<'ctx>{ #[allow(clippy::too_many_arguments)] @@ -115,6 +119,34 @@ impl<'ctx> ResidentQsaLayer<'ctx>{ let index=self.index.restore(ws,&prior.0.index).map_err(device_error);let kv=self.kv.rollback(ws,&prior.0.kv).map_err(device_error);index?;kv?; self.current=ResidentQsaPrior(Rc::new(Prior{binding:prior.0.binding.clone(),owner:prior.0.owner.clone(),origin,layer:prior.layer(),provider:prior.0.provider.clone(),index:prior.0.index.clone(),kv:prior.0.kv.clone()}));Ok(self.current.clone()) } + /// Bytes of the cells `first..first + tokens` of this layer as a prefix-cache span (host K/V pages and pooled index + /// rows). `first` and `tokens` are multiples of four and lie below the layer's end. + pub(in crate::qwen_forward) fn export_span(&self,first:usize,tokens:usize)->Result{ + if first%4!=0||tokens%4!=0||tokens==0||first+tokens>self.current.next_position() as usize{return Err(Error::InvalidPosition)} + let(mut kv,mut index)=(Vec::new(),Vec::new()); + {let _p=crate::qwen_forward::original_serve_profile::span("prefix.export_kv");self.kv.export_pages(first/4,tokens/4,&mut kv).map_err(device_error)?;} + {let _p=crate::qwen_forward::original_serve_profile::span("prefix.export_index");self.index.export_rows(first/4,tokens/4,&mut index).map_err(device_error)?;} + Ok(ParkedLayerSpan{first_token:first,tokens,kv,index}) + } + /// The tail of the layer's index checkpoint at its current end (what `import` needs besides the spans). + pub(in crate::qwen_forward) fn export_tail(&self)->Result>{ + self.index.export_tail(&self.current.0.index).map_err(device_error) + } + /// Install a parked prefix ending at `end`: write the spans, then re-mint the layer's index checkpoint and mapped + /// prefix from this layer's own lineage. Both physical halves are attempted; the first failure is returned. + #[allow(clippy::too_many_arguments)] + pub(in crate::qwen_forward) fn import(&mut self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,session:&QwenSession<'ctx>, + tail:&[u8],spans:&[&ParkedLayerSpan],end:usize,ws:&mut NativeBatchWorkspace<'ctx>)->Result>{ + cache.validate(binding)?;let origin=session.target_origin()?;let context=cache.retained_context(binding,session.mtp_context()?)?; + if !std::ptr::eq(context,self.context)||!self.current.0.binding.matches(&binding.identity()){return Err(Error::IdentityMismatch)} + let index_spans:Vec<(usize,&[u8])>=spans.iter().map(|s|(s.first_token/4,&s.index[..])).collect(); + let kv_spans:Vec<(usize,&[u8])>=spans.iter().map(|s|(s.first_token/4,&s.kv[..])).collect(); + let index={let _p=crate::qwen_forward::original_serve_profile::span("prefix.layer_index");self.index.import(ws,&index_spans,tail,end).map_err(device_error)}; + let kv={let _p=crate::qwen_forward::original_serve_profile::span("prefix.layer_kv");self.kv.import_pages(ws,&kv_spans,end).map_err(device_error)}; + let(index,kv)=(index?,kv?); + self.current=ResidentQsaPrior(Rc::new(Prior{binding:self.current.0.binding.clone(),owner:self.current.0.owner.clone(),origin,layer:self.current.layer(),provider:self.current.0.provider.clone(),index,kv})); + Ok(self.current.clone()) + } /// One-way handoff into the native verifier. It moves the same resident /// index and mapped K/V owners used by the prompt executor; it never clones /// a checkpoint or recreates state from a final image. The returned prior diff --git a/crates/leleka-runtime/src/qwen_forward/session_original_draft.rs b/crates/leleka-runtime/src/qwen_forward/session_original_draft.rs index 8e84c21d..bbaf245d 100644 --- a/crates/leleka-runtime/src/qwen_forward/session_original_draft.rs +++ b/crates/leleka-runtime/src/qwen_forward/session_original_draft.rs @@ -11,6 +11,10 @@ pub(in crate::qwen_forward) struct OriginalDraftSession<'ctx>{ pub(in crate::qwen_forward) struct OriginalDraftCheckpoint{ binding:BindingIdentity,origin:TargetStepOrigin,snapshot:MtpInt8Snapshot,first_materialized:usize, } +impl OriginalDraftCheckpoint{ + /// Host bytes of the ring image (prefix-cache accounting; pages shared with neighbouring points are counted in full). + pub(in crate::qwen_forward) fn host_bytes(&self)->usize{self.snapshot.encoded_bytes()} +} /// Exclusive canonical loan is held until all target permits are prepared and /// CUDA has completed. Publication below is only infallible assignment. pub(super) struct OriginalDraftPublication<'a,'ctx>{ diff --git a/crates/leleka-runtime/src/qwen_forward/session_original_prompt.rs b/crates/leleka-runtime/src/qwen_forward/session_original_prompt.rs index a338a4ab..2b2e8f2f 100644 --- a/crates/leleka-runtime/src/qwen_forward/session_original_prompt.rs +++ b/crates/leleka-runtime/src/qwen_forward/session_original_prompt.rs @@ -3,7 +3,7 @@ //! state is never relabelled as an earlier causal row or scalar transaction. use super::*; use std::cell::{Cell, RefCell}; -use super::super::qsa_index::prompt_device::resident_device::{ResidentQsaPrior,ResidentQsaSeal,ResidentQsaLayer}; +use super::super::qsa_index::prompt_device::resident_device::{ResidentQsaPrior,ResidentQsaSeal,ResidentQsaLayer,ParkedLayerSpan}; use super::super::dense_weight_cache::DenseWeightCache; #[path="session_original_draft.rs"] pub(in crate::qwen_forward) mod draft; @@ -155,6 +155,101 @@ impl<'driver> QwenSession<'driver> { } } +/// A session point that belongs to no lineage (prefix cache, `docs/prefix-cache.md`): the position, the recurrent +/// and PLE host priors (immutable images, shared by reference) and, per resident QSA layer, the bytes of its index +/// checkpoint tail. The K/V cells and pooled index rows below the position are parked separately as +/// [`ParkedBlock`]s, because they are shared by every point of the same token prefix. +pub(in crate::qwen_forward) struct ParkedSession{ + position:u64,predecessors:[i32;2],ple:Option, + gdn:[Option;STATE_CAPACITY],tails:[Option>;STATE_CAPACITY], +} +impl ParkedSession{ + pub(in crate::qwen_forward) fn next_position(&self)->u64{self.position} + /// Host bytes this point pins (priors counted in full even where a neighbouring point shares an image). + pub(in crate::qwen_forward) fn host_bytes(&self)->usize{ + self.ple.as_ref().map_or(0,PlePrior::host_bytes)+self.gdn.iter().flatten().map(GdnPrior::host_bytes).sum::() + +self.tails.iter().flatten().map(Vec::len).sum::() + } +} +/// The cells `first_token .. first_token + tokens` of every resident QSA layer, as plain bytes. +pub(in crate::qwen_forward) struct ParkedBlock{ + first_token:usize,tokens:usize,layers:[Option;STATE_CAPACITY], +} +impl ParkedBlock{ + pub(in crate::qwen_forward) fn first_token(&self)->usize{self.first_token} + pub(in crate::qwen_forward) fn tokens(&self)->usize{self.tokens} + pub(in crate::qwen_forward) fn host_bytes(&self)->usize{self.layers.iter().flatten().map(ParkedLayerSpan::bytes).sum()} +} +impl<'driver> QwenSession<'driver> { + /// Park the point the session stands at. Same preconditions as `original_checkpoint` (recurrent priors current, + /// every resident witness valid), and the layers must stand where the session does. + pub(in crate::qwen_forward) fn park_original(&mut self,binding:&ModelBinding, + layers:&[Option>;STATE_CAPACITY])->Result{ + let checkpoint=self.original_checkpoint(binding)?; + let mut tails:[Option>;STATE_CAPACITY]=std::array::from_fn(|_|None); + for slot in 0..48{match(&layers[slot],self.qsa_layers[slot]){ + (Some(layer),true)=>{ + if self.resident_qsa_states[slot].as_ref().is_none_or(|current|!current.same_prior(&layer.current())){return Err(Error::IdentityMismatch);} + tails[slot]=Some(layer.export_tail()?); + } + (None,false)=>{} + _=>return Err(Error::IdentityMismatch), + }} + Ok(ParkedSession{position:checkpoint.origin.next_position(),predecessors:checkpoint.predecessors,ple:checkpoint.ple,gdn:checkpoint.gdn,tails}) + } + /// The cells `first..first + tokens` of every resident layer (the session stands at or beyond `first + tokens`). + pub(in crate::qwen_forward) fn park_block(&self,layers:&[Option>;STATE_CAPACITY], + first:usize,tokens:usize)->Result{ + if self.state_lag.is_some()||(first+tokens) as u64>self.next_position{return Err(Error::InvalidPosition);} + let mut out:[Option;STATE_CAPACITY]=std::array::from_fn(|_|None); + for slot in 0..48{match(&layers[slot],self.qsa_layers[slot]){ + (Some(layer),true)=>out[slot]=Some(layer.export_span(first,tokens)?), + (None,false)=>{} + _=>return Err(Error::IdentityMismatch), + }} + Ok(ParkedBlock{first_token:first,tokens,layers:out}) + } + /// Make the session and the twelve physical layers stand at `parked`, writing the cells of `blocks` (the layers' + /// cells below the position that no block names must already hold the parked prefix; the caller knows which). + /// Unlike `restore_original_checkpoint` this accepts a point of ANOTHER lineage, because everything a lineage + /// witness would vouch for is re-written or re-minted from this session's own owners. The branch generation + /// is bumped first, fencing every older checkpoint. + pub(in crate::qwen_forward) fn import_parked(&mut self,binding:&ModelBinding, + dense:&DenseWeightCache<'driver>,layers:&mut[Option>;STATE_CAPACITY], + parked:&ParkedSession,blocks:&[&ParkedBlock])->Result<()>{ + let origin=self.target_origin()?; + if !self.binding.matches(&binding.identity())||self.layer_count!=48||parked.position>=u64::from(binding.input_constants().context_length()){ + return Err(Error::IdentityMismatch); + } + let _=origin; + for slot in 0..48{ + let wanted=self.qsa_layers[slot]; + if wanted!=layers[slot].is_some()||wanted!=parked.tails[slot].is_some() + ||blocks.iter().any(|b|b.layers[slot].is_some()!=wanted){return Err(Error::IdentityMismatch);} + } + let generation=self.checkpoint_generation.checked_add(1).ok_or(Error::Overflow)?; + {let _p=super::super::original_serve_profile::span("prefix.import_sync");self.complete_cuda()?;} + self.checkpoint_generation=generation; + let context=dense.retained_context(binding,self.mtp_context()?)?; + let mut workspace={let _p=super::super::original_serve_profile::span("prefix.import_workspace");dense.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?}; + let mut restored=std::array::from_fn(|_|None);let mut first_error=None; + let end=usize::try_from(parked.position).map_err(|_|Error::Overflow)?; + for(slot,layer)in layers.iter_mut().enumerate(){if let Some(layer)=layer{ + let spans:Vec<&ParkedLayerSpan>=blocks.iter().filter_map(|b|b.layers[slot].as_ref()).collect(); + let tail=parked.tails[slot].as_deref().ok_or(Error::IdentityMismatch)?; + match layer.import(binding,dense,self,tail,&spans,end,&mut workspace){Ok(current)=>restored[slot]=Some(current), + Err(error)=>{first_error.get_or_insert(error);}} + }} + drop(workspace); + if let Some(error)=first_error{self.note_mtp_failure(&error);return Err(error);} + self.complete_cuda()?; + self.next_position=parked.position;self.predecessors=parked.predecessors; + self.ple_state=parked.ple.clone();self.gdn_states=parked.gdn.clone(); + self.state_lag=None; + self.qsa_states=std::array::from_fn(|_|None);self.resident_qsa_states=restored;Ok(()) + } +} + #[derive(Clone, Copy, PartialEq, Eq)] enum DevicePhase { Staging, Ready(GrRole), Read(GrRole), Final, Published } diff --git a/crates/runtime-client/proto/runtime.proto b/crates/runtime-client/proto/runtime.proto index 71bd1209..b1f96927 100644 --- a/crates/runtime-client/proto/runtime.proto +++ b/crates/runtime-client/proto/runtime.proto @@ -55,6 +55,8 @@ message Snapshot { bool transport_ready = 6; bool model_ready = 7; LoadedModel loaded = 8; Capabilities capabilities = 9; string active_request_id = 10; + // JSON pool summary of the runtime's cross-session prefix cache (docs/prefix-cache.md), empty when it has none. + string prefix_cache_json = 11; } message LoadRequest { string operation_id = 1; string expected_epoch = 2; ModelDescriptor model = 3; LoadConfig config = 4; } message UnloadRequest { string operation_id = 1; string expected_epoch = 2; string handle = 3; } diff --git a/crates/runtime-client/src/backend.rs b/crates/runtime-client/src/backend.rs index dd20cd05..1f22ded8 100644 --- a/crates/runtime-client/src/backend.rs +++ b/crates/runtime-client/src/backend.rs @@ -34,6 +34,8 @@ pub struct GrpcBackend { attached: Option, /// Shared with the pump task so `cancel` can address the running request. active: Arc>>, + /// The prefix-cache summary of the last snapshot a `capabilities` probe read (no extra connection per query). + prefix_summary: Mutex>, } #[derive(Clone)] @@ -90,6 +92,7 @@ impl GrpcBackend { client: None, attached: None, active: Arc::new(Mutex::new(None)), + prefix_summary: Mutex::new(None), } } @@ -138,6 +141,17 @@ impl api::Backend for GrpcBackend { }; client.snapshot().await.ok() }); + // the probe is one snapshot read per health tick: keep its prefix-cache summary for `prefix_cache_summary` + if let Ok(mut cell) = self.prefix_summary.lock() { + *cell = probe + .as_ref() + .filter(|snapshot| { + snapshot.model_ready + && !snapshot.prefix_cache_json.is_empty() + && attached.as_ref().is_some_and(|a| a.epoch == snapshot.epoch) + }) + .map(|snapshot| snapshot.prefix_cache_json.clone()); + } match (probe, attached) { (Some(snapshot), Some(attached)) if snapshot.model_ready @@ -157,6 +171,12 @@ impl api::Backend for GrpcBackend { } } + /// The runtime's prefix-cache summary as of the last `capabilities` probe (one health tick old at most); `None` when the + /// runtime is unreachable, restarted since the attach, or has no such cache. + fn prefix_cache_summary(&self) -> Option { + self.prefix_summary.lock().ok().and_then(|cell| cell.clone()) + } + fn load( &mut self, model: api::ModelDescriptor, diff --git a/crates/runtime-client/src/client.rs b/crates/runtime-client/src/client.rs index f6a0b4d1..68504b7c 100644 --- a/crates/runtime-client/src/client.rs +++ b/crates/runtime-client/src/client.rs @@ -346,6 +346,7 @@ mod tests { loaded: Some(convert::loaded_to_proto(&loaded)), capabilities: Some(proto::Capabilities::default()), active_request_id: String::new(), + prefix_cache_json: String::new(), }; assert!(validate_snapshot(&snapshot).is_ok()); snapshot @@ -383,6 +384,7 @@ mod tests { loaded: None, capabilities: Some(proto::Capabilities::default()), active_request_id: String::new(), + prefix_cache_json: String::new(), } } } diff --git a/crates/runtime-client/tests/grpc_backend.rs b/crates/runtime-client/tests/grpc_backend.rs index d209f1df..9913e02c 100644 --- a/crates/runtime-client/tests/grpc_backend.rs +++ b/crates/runtime-client/tests/grpc_backend.rs @@ -115,6 +115,7 @@ impl Fake { tool_call_streaming: false, }), active_request_id: String::new(), + prefix_cache_json: String::new(), } } diff --git a/desktop-core/src/bin/leleka-inference.rs b/desktop-core/src/bin/leleka-inference.rs index 239378c7..fcbaa54a 100644 --- a/desktop-core/src/bin/leleka-inference.rs +++ b/desktop-core/src/bin/leleka-inference.rs @@ -36,6 +36,8 @@ const PROMPT_CACHE_EVERY_FLAG: &str = "--prompt-cache-every"; const PROMPT_CACHE_ROOT_FLAG: &str = "--prompt-cache-root"; const TURN_TOKEN_FLAG: &str = "--turn-token"; const EXPERT_SOURCE_FLAG: &str = "--expert-source"; +const PREFIX_CACHE_MIB_FLAG: &str = "--prefix-cache-mib"; +const PREFIX_CACHE_BLOCK_FLAG: &str = "--prefix-cache-block"; const EXECUTION_FLAGS: [&str; 7] = [ ADAPTIVE_SLOTS_FLAG, RESIDENT_OWNERS_FLAG, @@ -51,7 +53,7 @@ async fn main() -> Result<(), Box> { let args: Vec = std::env::args().skip(1).collect(); if args.as_slice() == ["--help"] { println!( - "leleka-inference --listen IP:PORT --token-env NAME --shard0 PATH --shard1 PATH --gpu ORDINAL --gpu-budget BYTES --context-tokens COUNT [--kar-archive PATH --kar-staging PATH | --kar-archive-fd N --kar-provenance PATH | --kar-archive-file PATH --kar-provenance PATH (read-only regular file, no write bits, owned by the caller: the low-RAM form of the pinned archive)] [--mtp-pack PATH --mtp-staging PATH] [--experimental-native-integer-iq3-windowed256-retained-gr | --experimental-optimized-windowed256-mtp [--ranked-expert-profile PATH --expert-profile-sha256 DIGEST] | --experimental-optimized-windowed256-mtp-queued-owners --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-streamed-spill --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-retained-scratch --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-strata-adaptive-slots --ranked-expert-profile PATH --expert-profile-sha256 DIGEST] [--public-evaluation-output /PRIVATE/measurements.jsonl (adaptive slots only; LELEKA_PUBLIC_EVALUATION=yes and LELEKA_EVALUATION_NONCE required)] [--backend-mode auto|original|preview (default auto; an --experimental-* flag selects preview unless the mode is given)] [--original-prefill-capacity 256..8192] [--mtp-rt-dir PATH] [--spec-min-p 0..1] [--kv int8 (fp16|q4_0|k8v4 are refused)] [--kv-resident CELLS (default 32768, min 20480, 0 = all in VRAM)] [--prompt-cache N (conversation checkpoints, default 6 as in the Original, 0 = off)] [--prompt-cache-every N] [--prompt-cache-root N] [--turn-token ID (negative = none)] [--expert-source resident|mapped (default resident: a ~50 GB RAM copy of the routed experts; mapped: read-only mappings of shard 0, the low-RAM laptop form)]" + "leleka-inference --listen IP:PORT --token-env NAME --shard0 PATH --shard1 PATH --gpu ORDINAL --gpu-budget BYTES --context-tokens COUNT [--kar-archive PATH --kar-staging PATH | --kar-archive-fd N --kar-provenance PATH | --kar-archive-file PATH --kar-provenance PATH (read-only regular file, no write bits, owned by the caller: the low-RAM form of the pinned archive)] [--mtp-pack PATH --mtp-staging PATH] [--experimental-native-integer-iq3-windowed256-retained-gr | --experimental-optimized-windowed256-mtp [--ranked-expert-profile PATH --expert-profile-sha256 DIGEST] | --experimental-optimized-windowed256-mtp-queued-owners --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-streamed-spill --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-retained-scratch --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-strata-adaptive-slots --ranked-expert-profile PATH --expert-profile-sha256 DIGEST] [--public-evaluation-output /PRIVATE/measurements.jsonl (adaptive slots only; LELEKA_PUBLIC_EVALUATION=yes and LELEKA_EVALUATION_NONCE required)] [--backend-mode auto|original|preview (default auto; an --experimental-* flag selects preview unless the mode is given)] [--original-prefill-capacity 256..8192] [--mtp-rt-dir PATH] [--spec-min-p 0..1] [--kv int8 (fp16|q4_0|k8v4 are refused)] [--kv-resident CELLS (default 32768, min 20480, 0 = all in VRAM)] [--prompt-cache N (conversation checkpoints, default 6 as in the Original, 0 = off)] [--prompt-cache-every N] [--prompt-cache-root N] [--turn-token ID (negative = none)] [--prefix-cache-mib auto|N|0 (cross-session prefix cache in host RAM, replaces the conversation cache; auto = a share of the memory available at start; default off)] [--prefix-cache-block TOKENS (block and chunk-grid size, a multiple of 256; default the prefill capacity)] [--expert-source resident|mapped (default resident: a ~50 GB RAM copy of the routed experts; mapped: read-only mappings of shard 0, the low-RAM laptop form)]" ); return Ok(()); } @@ -990,6 +992,7 @@ fn operator_original_serve( let (mut kv, mut kv_resident) = (false, false); let (mut cache, mut every, mut root, mut turn) = (false, false, false, false); let mut expert_source = false; + let (mut prefix_mib, mut prefix_block) = (false, false); let mut ordinary = Vec::with_capacity(args.len()); let mut offset = 0usize; while offset < args.len() { @@ -1074,6 +1077,20 @@ fn operator_original_serve( Some(u32::try_from(id).map_err(|_| "invalid_turn_token")?) }; offset += 2; + } else if flag == PREFIX_CACHE_MIB_FLAG { + if std::mem::replace(&mut prefix_mib, true) { + return Err("duplicate_prefix_cache_mib"); + } + let budget = leleka_runtime::prefix_cache::budget::parse_mib(value()?)?; + options.prefix_cache.get_or_insert_with(Default::default).budget_bytes = budget; + offset += 2; + } else if flag == PREFIX_CACHE_BLOCK_FLAG { + if std::mem::replace(&mut prefix_block, true) { + return Err("duplicate_prefix_cache_block"); + } + options.prefix_cache.get_or_insert_with(Default::default).block_tokens = + value()?.parse().map_err(|_| "invalid_prefix_cache_block")?; + offset += 2; } else if flag == EXPERT_SOURCE_FLAG { if std::mem::replace(&mut expert_source, true) { return Err("duplicate_expert_source"); diff --git a/desktop-core/src/runtime_rpc.rs b/desktop-core/src/runtime_rpc.rs index 4a4d7fcb..8fd5f1f5 100644 --- a/desktop-core/src/runtime_rpc.rs +++ b/desktop-core/src/runtime_rpc.rs @@ -53,6 +53,8 @@ struct State { lifecycle_busy: bool, active: Option, stopping: bool, + /// The backend's prefix-cache summary as of the last observation (`Backend::prefix_cache_summary`). + prefix_cache_json: String, } struct Operation { digest: [u8; 32], @@ -131,6 +133,7 @@ fn snapshot(state: &State) -> proto::Snapshot { capabilities_to_proto(&state.capabilities) }), active_request_id: state.active.clone().unwrap_or_default(), + prefix_cache_json: if state.stopping { String::new() } else { state.prefix_cache_json.clone() }, } } fn publish(inner: &Inner, state: &mut State) { @@ -167,6 +170,7 @@ impl RuntimeServer { lifecycle_busy: false, active: None, stopping: false, + prefix_cache_json: String::new(), }), changes, controls: Arc::new(Semaphore::new(16)), @@ -736,12 +740,14 @@ fn close_admission(inner: &Inner) { } fn refresh_capabilities(inner: &Inner) { // Observations must not wait behind a load/acceptance acknowledgement. - let capabilities = match inner.backend.try_lock() { - Ok(backend) => backend.capabilities(), + let (capabilities, summary) = match inner.backend.try_lock() { + Ok(backend) => (backend.capabilities(), backend.prefix_cache_summary()), Err(std::sync::TryLockError::WouldBlock) => return, - Err(std::sync::TryLockError::Poisoned(_)) => api::BackendCapabilities::default(), + Err(std::sync::TryLockError::Poisoned(_)) => (api::BackendCapabilities::default(), None), }; if let Ok(mut state) = inner.state.lock() { + // the summary changes with every request; watchers are told about it only through a snapshot they ask for + state.prefix_cache_json = summary.unwrap_or_default(); let capabilities = if state.loaded.is_some() { capabilities } else { diff --git a/desktop-core/tests/api_over_runtime.rs b/desktop-core/tests/api_over_runtime.rs index defc2d88..c8145b98 100644 --- a/desktop-core/tests/api_over_runtime.rs +++ b/desktop-core/tests/api_over_runtime.rs @@ -170,6 +170,7 @@ struct Stack { impl Stack { async fn start(name: &str, address: SocketAddr) -> Self { let tokenizer = tokenizer(name); + let prefix_view = Arc::new(strata_control::prefix_view::PrefixView::default()); let config = BackendWorkerConfig { tokenizer: tokenizer.clone(), model: ScriptedEngine::fixture_descriptor(), @@ -181,6 +182,7 @@ impl Stack { attach_retry: Duration::from_millis(50), health_interval: Duration::from_millis(50), cancel_drain_timeout: Duration::from_secs(5), + prefix_view: Some(prefix_view.clone()), }; let backend = leleka_runtime_client::backend::GrpcBackend::new( tokio::runtime::Handle::current(), @@ -205,6 +207,7 @@ impl Stack { tokenizer: Some(tokenizer), generation: Some(requests), control: Some(control), + prefix_cache: prefix_view, ..Default::default() }; let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -563,3 +566,58 @@ async fn documents_the_256_generations_per_runtime_epoch_limit() { stack.finish().await; runtime.stop().await; } + +#[tokio::test(flavor = "multi_thread")] +async fn the_engines_prefix_summary_reaches_v1_status_and_answers_prefix_match() { + let runtime = Runtime::start(None).await; + runtime.operator_loads_the_model().await; + let stack = Stack::start("chain-prefix", runtime.address).await; + stack.wait_state(WorkerState::Ready).await; + let get_status = || async { + let text = stack.client.get(format!("{}/v1/status", stack.base)).send().await.unwrap().text().await.unwrap(); + serde_json::from_str::(&text).unwrap() + }; + + // an engine without a prefix cache reports none + assert_eq!(get_status().await["prefix_cache"], Value::Null); + + // the engine's cache summary travels runtime -> snapshot (gRPC) -> worker health tick -> /v1/status + let summary = json!({ + "version": 1, "chain_version": 1, "namespace": "00000000000000ab", "block_tokens": 2048, + "budget_bytes": 1u64 << 30, "used_bytes": 1u64 << 20, "nodes": 2, "blocks": 6, "truncated": false, + "heads": [{"h": "00000000000000a1", "tokens": 4096}, {"h": "00000000000000a2", "tokens": 12288}], + "stats": {"requests": 3, "hits": 1, "shared_hits": 1, "misses": 2, "reused_tokens": 4096, "prompt_tokens": 9000, "admitted": 2, "rejected": 0, "evicted": 0}, + }); + runtime.engine.set_prefix_summary(Some(summary.to_string())); + let deadline = Instant::now() + Duration::from_secs(10); + let status = loop { + let status = get_status().await; + if status["prefix_cache"].is_object() { + break status; + } + assert!(Instant::now() < deadline, "the summary never reached /v1/status"); + tokio::time::sleep(Duration::from_millis(20)).await; + }; + assert_eq!(status["prefix_cache"]["namespace"], "00000000000000ab"); + assert_eq!(status["prefix_cache"]["heads"].as_array().unwrap().len(), 2); + + let (code, text) = stack + .post( + "/v1/prefix_match", + &json!({"namespace": "00000000000000ab", "block_hashes": ["00000000000000a1", "00000000000000aa", "00000000000000a2"]}), + ) + .await; + assert_eq!(code, 200, "{text}"); + let answer: Value = serde_json::from_str(&text).unwrap(); + assert_eq!((answer["cached_tokens"].as_u64(), answer["block_tokens"].as_u64()), (Some(12288), Some(2048))); + + // the cache goes away (the engine restarted without it): the view clears + runtime.engine.set_prefix_summary(None); + let deadline = Instant::now() + Duration::from_secs(10); + while !get_status().await["prefix_cache"].is_null() { + assert!(Instant::now() < deadline, "the summary never cleared"); + tokio::time::sleep(Duration::from_millis(20)).await; + } + stack.finish().await; + runtime.stop().await; +} diff --git a/docs/original-serve.md b/docs/original-serve.md index 6939de16..9e6df1bc 100644 --- a/docs/original-serve.md +++ b/docs/original-serve.md @@ -130,7 +130,9 @@ check of a checkpoint). Code: `qwen_forward/original_serve_conversation.rs` over (then `settle_state` reads the GDN/PLE state back). generate.cpp skips the draft of the last window on EOS/length and continues with that gap in the ring; this port's draft lineage does not admit the gap, so such a request resumes from its last turn checkpoint instead (it re-reads the reply). -* Not bound: parking whole conversations in host RAM (`--conversation-cache-mib`, opt-in in the Original too). +* Not bound: parking whole conversations in host RAM (`--conversation-cache-mib`, opt-in in the Original too). The port's answer for a + pool of agents is the content-addressed cross-session prefix cache of `docs/prefix-cache.md` (`--prefix-cache-mib`), which replaces + this cache when it is on. * Any failure of the cache drops it and the request reads its whole prompt; a failed or broken request drops it. * What "the same answer" means: the batched prefill's arithmetic depends on how the prompt is cut into chunks, and a resumed request is cut differently from a full read (it starts at the resume point; a root boundary is only diff --git a/docs/port-status.md b/docs/port-status.md index fcefa521..ab432a20 100644 --- a/docs/port-status.md +++ b/docs/port-status.md @@ -54,6 +54,7 @@ A `.cu` file may sit at **S** while its Rust host side sits at **L** or **O**; b | Sampling request keys (`sampling_keys`, `GEN` grammar) | `control-plane/src/{sampling,wire}.rs`, `crates/sampler-ref/src/params.rs` | full | O: golden `GEN` strings lifted from `server.py` by AST | | `serve/structured.py` | `responses.rs`, `response_tools.rs` | full parity (validation only, no grammar decoding) | T | | `core/conversation_{cache,buffer,memory,state,snapshot}`, `program/conv_cache.hpp`, parking, checkpoint chain | `crates/leleka-runtime/src/conversation/` | full for policy and accounting; GPU snapshot bound through the session owners | O for cache and manager (`conversation/golden`); L for the CUDA-bound snapshot | +| (not in the Original) cross-session prefix cache: content-addressed blocks and checkpoints in host RAM, pool summary / `prefix_match` | `crates/leleka-runtime/src/prefix_cache/`, `qwen_forward/original_serve_prefix.rs`, `control-plane/src/prefix_view.rs`; docs/prefix-cache.md | new in the port; model-free policy and store tested, bound to the real model on the 5090 and the laptop | L: greedy ids of every cached request equal a full read on the same chunk grid (jobs 921-927) | | `cvec.{hpp,cu}` host loader, SVE1 embedding files, M-RoPE positions | `crates/serving-policy/src/{cvec,vision}.rs`, `crates/experimental-ref/src/cvec.rs` | host side full; device apply is the experimental program below | O (`gen_cvec_fixtures.cpp`, `gen_vision_fixtures.cpp`) | | `program/logits_selection.hpp`, `core/progress.hpp` | `crates/serving-policy/src/{stride,watchdog}.rs` | full | O (golden vs the C++ header) | | `platform/direct_file`, `ngram/ple_reader` (async O_DIRECT row reader) | `crates/model-format/src/ple_reader*`, `leleka-runtime/.../qwen4exp_ple_reader.rs` | partial: async reader with page dedup and row cache; O_DIRECT is Linux-only | T (macOS), L | diff --git a/docs/prefix-cache.md b/docs/prefix-cache.md new file mode 100644 index 00000000..6ea56e8b --- /dev/null +++ b/docs/prefix-cache.md @@ -0,0 +1,331 @@ +# Cross-session prefix cache + +Branch `claude/prefix-cache` (cut from `claude/port-gpu-bringup` 6b94e7c). Code: `crates/leleka-runtime/src/prefix_cache/` +(model-free store, hash chain, budget, pool summary), `qwen_forward/original_serve_prefix.rs` (the binding to the Original +serve stack), the park/import primitives in `crates/cuda-driver` (`qsa_mapped_journal.rs`, `qsa_resident_index.rs`) and +`qwen_forward/session_original_prompt.rs`, and the pool surface in `control-plane/src/prefix_view.rs`. + +## Why + +Coding agents resend their whole context with every request (system and developer instructions, tool schemas, repository +context, every earlier turn and tool output), and a pool serves many agents from many runtimes: the next request is not +guaranteed to come from the agent that sent the last one. Prefill is 1.8k-3.7k tok/s here, so a 30-100k-token request +costs 10-40 s without a hit, and a 180k-token one a minute or more. + +The Original's conversation cache (`docs/original-serve.md`, "Conversation cache") keeps `--prompt-cache` checkpoints +(default 6: the pinned root, periodic ones, the last turn boundary) of the ONE conversation whose K/V the positional +buffer holds. A checkpoint is only valid while the positional cells below it still hold ITS tokens, so a request from +another session overwrites every cell after the shared prefix and the first session's later checkpoints die with them. +Parking whole conversations in host RAM (`--conversation-cache-mib`) is not bound in the port. Measured effect: +see "Results". + +## Design + +### One token grid + +The prompt is read on a fixed grid (`PromptOptions::grid`, `--prefix-cache-block`, default the prefill capacity, so a grid step is one +full chunk and the prefill runs at the speed of the chunk size the operator chose): +every batched chunk ends on a multiple of `block_tokens`, apart from the last one of a request, which ends at `n - 1` (the +last prompt token starts the first verify window). There are no turn or root cuts. Consequences: + +* the recurrent state, the K/V cells and the draft ring after a grid chunk are a pure function of the tokens before it, + whichever request read them (the batched prefill's arithmetic depends on how the prompt is cut into chunks, which is + why the Original's turn/root cuts make a resumed read differ from a full read); +* a request resumed at a grid point reads exactly the chunks a full read reads from there, so a cache hit reproduces the full + read bit for bit (checked on the real model, "Results"); +* what a session loses at the end of a request is the partial last chunk (on average half a block: 1k tokens at 2048, 4k at 8192). The block + size trades that loss against the prefill's per-chunk overhead: on the 5090 a 2048-token chunk prefills at ~1.4k tok/s on a 10-26k context + (jobs 921/922) and an 8192-token chunk at ~3.5k tok/s (job 915), so the default follows `--original-prefill-capacity`. + +### Blocks, nodes, sharing + +* A **block** holds the K/V cells (INT8 K+V with scales, 1056 B per cell and layer, host image) and the pooled index rows + (128 B per cell and layer) of `block_tokens` consecutive tokens of the twelve QSA layers: 14,208 B per token, 29.1 MB per + 2048-token block, 2.56 GB per 180k tokens. It is keyed by the **hash chain** value after it + (`hash::chain_step`), so by the whole token prefix it ends, and stores its tokens (verified on every match, so a 64-bit + collision cannot produce a hit). +* A **node** is a checkpoint at a grid point: the GDN and PLE host images, the predecessors, the index checkpoint tails of the + twelve layers (2,564 B each) and the draft ring's snapshot (about 127 MB in all at the 5090 profile), plus the list of its block + hashes. A node needs its blocks and nothing else. +* Blocks are shared by reference (`refs` = nodes covering them): N agents with the same 8k system prompt hold ONE copy of its + four blocks. Evicting a node frees its state and exactly the blocks no other node covers. + +### Restore path + +On a request the store walks the prompt's chain and returns the deepest node that is a prefix of the prompt and ends at or +before `n - 1` (`longest_match`: hashing 180k tokens and comparing them is about a millisecond). The stack then +(`QwenSession::import_parked`): + +1. computes how much of the positional buffer already holds the prefix: `live` is the part known to hold the current prompt's + cells (written by the prefill or put back by an import); it is truncated before a chunk or an import overwrites cells and + extended after, so a cancelled or failed request never claims cells it did not finish writing; +2. writes back only the blocks from the first one the buffer does not hold: host K/V pages straight into the pinned host + image (`OriginalQsaMappedJournal::import_pages`, which also resets the VRAM resident window of the layer so no stale slot + survives), pooled index rows into the device image (`OriginalQsaResidentIndex::import`); +3. re-mints each layer's lineage objects (index checkpoint, mapped prefix, `ResidentQsaPrior`) from the layer's own owners and + bumps the branch generation, which fences every older checkpoint; +4. installs the GDN/PLE images and the position, re-anchors the draft ring (`resume_at` + `kv_restore`) and prefills only + the suffix. + +The same session continuing copies no K/V at all (the buffer already holds its prefix); a session returning after others +copies only the blocks the others overwrote. Measured on the 5090: 98k tokens (1.4 GB) restored in 101 ms and 172-180k tokens (2.4-2.6 GB) in +175-194 ms (13-14 GB/s, a host memcpy of 14.2 KB per token), a hit that copies nothing in 1-3 ms, against 28-55 s of prefill. + +### Admission and eviction (what is kept) + +After every grid chunk the policy may admit a checkpoint (`PrefixStore::consider`). A node is scored by **expected tokens +saved per byte its eviction frees**: + +``` +value(node) = P(hit) * (tokens(node) - tokens(nearest surviving ancestor)) +score = value / (state bytes + bytes of blocks only this node covers) +``` + +`P(hit)` combines a prior that depends on the node's role with the decayed hit mass: + +* **frontier** (the deepest node a request built: the likeliest resume point of its session): prior 0.5; +* **interior** (a deeper neighbour exists in its chain): prior 0.03, raised by each branch below it (a branch point is + shared by definition); +* the prior halves every 256 requests without a touch (recency), and hits add mass: a hit by ANOTHER session than the one that + built the node (the live buffer did not extend its prefix: a shared root or a rewritten history) counts 3, a session's own + continuation counts 0 (it only says the node was the frontier, which the prior already values). + +Measuring against the nearest SURVIVING ancestor makes a thinned chain worth more per node, so a long session settles on its +frontier, the previous one or two, and a geometric spread of older nodes (for forks and history rewrites), not a node per +block. A candidate is admitted when there is room, or when the sum of the values of the victims it needs (cheapest per byte +first, counting the saving the candidate gains once a victim ancestor is gone) is less than its own value; otherwise it is +rejected before anything is built. Blocks of the candidate's own path survive the eviction of its ancestors. A byte budget +bounds the store (`--prefix-cache-mib`); the estimate is replaced by the real size after the build and the budget is +enforced again. + +Unit tests (`prefix_cache::store::tests`) pin: sharing, refcounts, the node cap, idle frontiers losing to fresh ones, hot +shared roots surviving churn, a long session settling on a sparse chain, oversize payloads, collisions. + +### Budget + +`--prefix-cache-mib auto|N|0`. `auto` keeps 4 GiB of `MemAvailable` free and takes 75% of the rest when the stack opens (ceiling 96 GiB, 24 GiB +with the laptop profile), and is off when that is under 1 GiB. `MemAvailable` already excludes the sealed KAR memfd (shmem) and the pinned K/V, +and it counts reclaimable page cache. On the 5090 server (121 GB; 55 GB sealed memfd, ~50 GB resident expert source) it was 22 GiB at open in +job 922, so the budget came out at 13.7 GiB; right after the model load it can be lower (job 915 sampled 14 GiB while the expert source was still +being copied), and it differs run to run with the page cache. The cost of a session is its blocks plus the states of the nodes kept: blocks are +14.2 KB per token (2.56 GB at 180k tokens), a state is about 127 MB (GDN/PLE images, the draft ring, the index tails), so at the default grid a +180k-token session costs 2.6 GB of blocks plus 127 MB per node kept (one node when thinned, 22 at an 8192 grid when all are kept). Before every +insertion the live `MemAvailable` is checked again against a 3 GiB floor: an insertion that would breach it is skipped, and unknown telemetry fails +closed. The accounting matches the process: job 922's store reported 5,176 MiB used and the process RSS grew by about 5.3 GB. + +### Concurrency, cancellation, failure + +The engine serves one generation at a time, so the store needs no locking; all of it lives on the owner thread. A request for +another session simply finds a different node. A cancelled request keeps the checkpoints of the chunks it finished (they are +immutable host images), claims only the cells of its finished chunks, and the next request, from any session, imports over +whatever the interrupted one left. A failure of the cache (a checkpoint that cannot be built, an import that fails) drops the +whole cache and the request is read from 0 after the usual reset (`prefix cache: ...; reading the whole prompt`); a lost +physical owner invalidates it with the stack. + +### What the cache does not do + +* It replaces the conversation cache when on (`StackConfig::prefix` / `--prefix-cache-mib`); with it off nothing changes. +* The live continuation of the Original (continue the session's decode-phase K/V as is) is not used: decode-produced cells are + not what a prefill produces, and sharing them would break the exactness above. A session resumes from its last grid node + and re-reads the partial block, the reply and the new tokens. A tool-call reply ends on EOS, after which the Original's own + live continuation is unavailable anyway. +* K/V is parked as INT8 host images only (`--kv int8`, the only format with sealed owners); the streamed layout + (`--kv-resident`) needs nothing special because the host image is the authority for every reachable cell. +* One engine, one buffer: two *concurrent* sessions on one runtime still alternate; the pool gets concurrency from many runtimes + and the router below. + +## Knobs and observability + +| Knob | Default | Meaning | +| --- | --- | --- | +| `--prefix-cache-mib auto\|N\|0` | off | Host-RAM budget; `auto` per the profile above. Turning it on replaces the conversation cache. | +| `--prefix-cache-block TOKENS` | the prefill capacity | Block size and chunk grid; a multiple of 256, at most the prefill capacity. | +| `LELEKA_PREFIX_TRACE=1` | off | One line per admitted checkpoint. | + +Logs (stderr, `leleka-serve ...`): `prefix cache on: ...` at open; per request `prefix request: n= hit= resume= shared= +copied_tokens= import_ms=`; `prefix request done: admitted= park_ms= prefix stats: nodes= blocks= used_mib= budget_mib= +requests= hits= shared_hits= misses= reused_tokens= prompt_tokens= admitted= rejected= evicted=`. `Usage::reused_input_tokens` +is the resume point. + +## Pool protocol + +A front router across many runtimes places a request on the runtime that holds the longest prefix of its prompt. Nothing but +the prompt's token ids is needed to ask. + +**Chain.** Cut the prompt into blocks of `block_tokens` tokens (the runtime's `block_tokens`, 2048 by default); the chain value +after block `j` is `h_j = chain_step(h_{j-1}, block_j)`, `h_{-1} = CHAIN_SEED = 0x4C454C454B410001`, where `chain_step` +folds each token `t` (as `u32`) as `h = rotl(h, 5) ^ t; h *= 0x517CC1B727220A95` and finalizes with splitmix64 over +`h ^ (len << 40)` (`prefix_cache::hash`, version `CHAIN_VERSION = 1`, pinned by a test; a partial tail has no value). +`h_j` depends on every token before the end of block `j`. + +**Summary** (`prefix_cache::PrefixSummary`, JSON). The engine publishes it after every request; `leleka-runtime` hands it +to the runtime gRPC `Snapshot.prefix_cache_json`; the control plane copies it on its health tick and after every request: + +```json +{"version":1,"chain_version":1,"namespace":"00000000000000ab","block_tokens":2048, + "budget_bytes":32212254720,"used_bytes":1048576,"nodes":2,"blocks":6,"truncated":false, + "heads":[{"h":"00000000000000a1","tokens":4096},{"h":"00000000000000a2","tokens":12288}], + "stats":{"requests":3,"hits":1,"shared_hits":1,"misses":2,"reused_tokens":4096,"prompt_tokens":9000,"admitted":2,"rejected":0,"evicted":0}} +``` + +`heads` lists the checkpoint nodes (chain value after the node's last block, tokens covered), best value first, at most 512 +(`truncated` says if some are left out; about 25 KB). `namespace` fingerprints everything that makes two caches +interchangeable (model digest, KV format and window, block size, chain version): compare chain values only between +runtimes with equal namespaces. + +**Surfaces.** + +* `GET /v1/status` carries the summary as `prefix_cache` (with `age_ms`), `null` when the runtime has none. +* `POST /v1/prefix_match` with `{"block_hashes": ["<16 hex>", ...], "namespace": "<16 hex>" (optional)}` (the prompt's chain + values in order, at most 16,384) answers `{"available":true,"compatible":true,"namespace":..,"block_tokens":2048, + "cached_tokens":12288,"truncated":false,"age_ms":..}`: the tokens of the deepest head among the hashes, 0 when none or when + the namespace differs. It is a hint about a snapshot (the runtime may have evicted a head since), computed in + microseconds from the control plane's copy; it never touches the GPU thread. +* In-engine, `OriginalServeStack::prefix_match(chain)` answers from the live store (exact for hash equality) and + `PrefixSummary::match_tokens` is the same lookup over a summary, for a router that polls summaries instead. + +A router's loop: hash the prompt once per distinct `block_tokens`, ask each candidate runtime (or its cached summary), send the +request to the longest `cached_tokens`, ties to the less loaded. The router itself is not part of this work. + +## Results + +All numbers below are from the real model; every log line is in the job logs named (kept outside Git, with the binary hashes). Greedy decoding, the +VRAM expert tier in STATIC mode (`LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=2048`, per layer, `ADAPT_EVERY=0`) with the prompt-routing seed OFF +(`LELEKA_ORIGINAL_SERVE_SEED=off`), so the expert placement is identical for every arm; MTP drafting on; INT8 K/V, `--kv-resident 20480`, +max context 262144. Hardware: RTX 5090 (driver 595.99), 121 GB RAM of which 55 GB is the sealed KAR memfd and ~50 GB the resident expert source; +model `sha256:4c1eb2ce...aca3` (shard 0); chunk 2048 unless stated. Workload generator: `backend_original_serve_prefix_smoke.rs` (real tokenizer; +deterministic text; the sessions' histories are literally extended, the way an agent resends its context). + +How "equal" was checked: after a request served from the cache, the SAME prompt is served again with the cache bypassed (`prefix_bypass`: no +lookup, no insertion; a full read from position 0 on the same chunk grid) and the committed token ids are compared (16-24 greedy tokens each). +This is the charter's non-lossy rule applied to the cache: it is not compared with the Original's turn/root cuts, which change the chunking. + +### 1. The failure mode today (job 921, `legacy`: the Original's conversation cache as shipped) + +Three sessions A, B, C share an 8k-token system+tools+repo prefix, requests interleaved `A1 B1 C1 A2 B2 C2 ...` (5 turns, +4k tokens per turn, 10k -> 26k). + +| request | prompt tokens | reused (legacy) | re-read (legacy) | TTFT legacy | reused (prefix) | re-read (prefix) | TTFT prefix | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| A1 | 10,020 | 0 | 10,019 | 11.2 s | 0 | 10,019 | 8.6 s | +| B1 / C1 | 10,020 | 7,998 | 2,021 | 2.2 s | 6,144 | 3,875 | 2.8-2.9 s | +| A2 / B2 / C2 | 14,051 | 7,998 | 6,052 | 4.4-7.5 s | 8,192 | 5,858 | 4.1 s | +| A3 / B3 / C3 | 18,082 | 7,998 | 10,083 | 7.3-7.8 s | 12,288 | 5,793 | 4.4 s | +| A4 / B4 / C4 | 22,113 | 7,998 | 14,114 | 10.0-10.3 s | 16,384 | 5,728 | 4.3-4.4 s | +| A5 / B5 / C5 | 26,144 | 7,998 | 18,145 | 12.9-13.0 s | 20,480 | 5,663 | 4.5 s | +| all 15 | 271,215 | 111,972 (41.3%) | 159,243 | mean 8.3 s, p95 13.0 s | 184,320 (68.0%) | 86,895 | mean 4.4 s, p95 4.5 s | + +Today, after the first request every request reuses only the pinned root (7,998 tokens: the first turn boundary); the session's own later K/V is +overwritten by the other sessions and re-read, so TTFT grows with the context (13 s at 26k). With the prefix cache TTFT is flat (4.4 s) because +only the suffix since the last grid point is read (~5.7k tokens at ~1.4k tok/s with 2048-token chunks; a bigger chunk reads it faster, see 3). +At 10k the cache reuses less than the root (6,144 < 7,998): the grid has no turn cuts, so the shared 8k prefix is cached at its last 2048 boundary. +Equality: **all 14 verified requests produced the same ids as the full read** (job 922). +Restore cost: import 11 ms mean (24 ms max, 18,432 tokens = 262 MB copied in 24 ms); lookup 23 us mean; parking 3.5 ms per request mean. + +### 2. A realistic agent trace (jobs 923 legacy, 927 prefix; 924 is the same run with the policy before its last fix) + +Synthetic Codex-like trace after `docs/experiments/2026-10-03-agent-ab-threejs.md` (97 requests, 3.3M input tokens): 4 sessions x 24 requests = 96 +requests in seeded random interleaving, a 2.5k-token system+tools prefix shared by all, each session growing from ~3k to ~40k tokens with +heavy-tailed tool outputs (64 to ~6k tokens). 2.19M prompt tokens in total. + +| | legacy (job 923) | prefix cache (job 927, auto budget 7.8 GiB) | +| --- | ---: | ---: | +| prompt tokens reused | 580,618 (26.5%) | 1,927,168 (88.0%) | +| prompt tokens read again | 1,608,955 | 262,405 | +| TTFT mean / p50 / p95 / max | 12.5 / 11.3 / 27.6 / 27.6 s | 2.5 / 1.7 / 5.5 / 5.8 s | +| sum of TTFT over the trace | 1,200 s | 244 s | +| decode (mean of per-request rates) | 29.9 tok/s | 31.9 tok/s | + +| context | requests | legacy reuse | legacy mean TTFT | prefix reuse | prefix mean TTFT | +| --- | ---: | ---: | ---: | ---: | ---: | +| 0-8k | 18 | 61% | 2.2 s | 55% | 2.2 s | +| 8-16k | 16 | 39% | 5.6 s | 76% | 2.6 s | +| 16-24k | 13 | 39% | 8.9 s | 82% | 3.0 s | +| 24-32k | 19 | 23% | 15.6 s | 90% | 2.6 s | +| 32-50k | 30 | 21% | 22.0 s | 93% | 2.5 s | + +Under a real byte budget (7.8 GiB: the memory available when the stack opened was 14.5 GiB) the adaptive policy admitted 68 checkpoints, rejected 8 and +evicted 25, ending with 43 nodes and 76 blocks (7,833 MiB used): the trace still reused 88%. RSS grew by the amount the store reports (53.6 -> 61.4 GB). The last +request of every session (reused 38,912 of 40.7k tokens) was re-read with the cache bypassed: all 4 equal (TTFT 1.7 s cached vs 28.8-29.2 s full read). +Cancel safety (a request cancelled during the prefill, one cancelled after its first round, the same prompt served and verified, a switch to +another session): all passed. Restore (job 924): 99 hits; a hit that copied nothing cost 1.3 ms; the 40 hits that copied 20-37k tokens (up to 524 MB) took 34 ms +on average (43 ms max). Lookup over a 40k-token prompt: 29 us mean, 59 us max. + +Decode speed: the decode path is untouched; the only effect is a one-time cold start of the VRAM resident K/V window after an import (the +resolver is reset because the host image changed): for the same request with identical output, decode took 594 vs 565 ms (+5%, 29 ms) at 10k +context and 596 vs 593 ms (+0.5%) at 40k (jobs 922 / 924; 14 + 4 pairs, +0.5% to +5%, never more than 30 ms per request). + +### 3. 100k and 180k contexts + +Two sessions A and B, each 8k shared + private history, 3 turns (+3k tokens per turn), interleaved `A1 B1 A2 B2 A3 B3`, chunk = grid = 8192 (the chunk +of job 915, where plain prefill of 100k / 180k ran at 3.4 / 3.5k tok/s and decode worked), auto budget **7.8 GiB** (only 14.5 GiB were available when the +stack opened). `legacy` = the Original's conversation cache. + +| context | request | prompt tokens | reused legacy | TTFT legacy | reused prefix | TTFT prefix | restore (host RAM -> K/V + state) | +| --- | --- | ---: | ---: | ---: | ---: | ---: | --- | +| 100k | A1 / B1 (cold) | 100,020 | 0 / 7,998 | 31.3 / 27.6 s | 0 / 0 (the 8,000-token shared prefix is shorter than one 8192 block) | 31.4 / 30.0 s | - | +| 100k | A2 / B2 | 103,051 | 7,998 | 28.2 / 28.1 s | 98,304 | 2.33 / 2.33 s | 98,304 tokens (1.4 GB) in 101 ms | +| 100k | A3 / B3 | 106,082 | 7,998 | 28.6 / 28.6 s | 98,304 | 2.79 / 2.79 s | 101 ms | +| 180k | A1 / B1 (cold) | 180,020 | 0 / 7,998 | 54.8 / 51.3 s | 0 / 0 | 55.1 / 53.7 s | - | +| 180k | A2 / B2 | 183,051 | 7,998 | 53.1 / 53.1 s | 172,032 | 4.76 / 4.76 s | 172,032 tokens (2.4 GB) in 175-177 ms | +| 180k | A3 / B3 | 186,082 | 7,998 | 53.7 / 53.6 s | 180,224 | 2.72 / 2.72 s | 182-194 ms | + +* Re-prefilling a 180k session costs 53 s (legacy: every request, because the other session overwrote the buffer); with the cache the request reads + only the suffix since the last 8192 boundary plus what is new: 4.8 s (A2: 11k tokens, two chunks) and 2.7 s (6k tokens), i.e. 11-20 times faster. The + restore itself is 0.1-0.2 s for 1.4-2.6 GB (13-14 GB/s host memcpy into the pinned image + the index rows), the lookup over a 186k-token prompt 0.2 ms. +* Equality: A3 and B3 at 100k and 180k were each re-read with the cache bypassed (30.7 s / 55.7 s full read vs 2.8 s / 2.7 s cached): **identical ids**. + Cancel safety at 100k (prefill cancelled, decode cancelled, retry equal to a full read, switch to the other session): passed. +* The 7.8 GiB budget holds about two 180k sessions: it ended with 16 nodes and 44 blocks (7,832 MiB), after 32 admissions, 13 rejections and 16 evictions; + both sessions still resumed at 172k / 180k, i.e. the policy kept each session's frontier and thinned its history. +* RAM per session: 8192-token blocks are 116 MB; 180k tokens = 22 blocks = 2.56 GB, plus 127 MB per node kept. The auto budget here is small because the + box holds the sealed KAR memfd and the 50 GB resident expert source; with `--expert-source mapped` (file-backed experts) the cache could take tens of GiB more. +* Parking cost on the request that builds a session (cold 180k): 350 ms for 9 admitted checkpoints (host copies of 8 blocks + state clones), against 55 s of prefill. + + +### 4. Laptop (RTX 3080 Laptop 16 GB, WSL2, mapped experts, sm86 build; slow CPU experts: ~45 tok/s prefill) + +Same grid workload, small (3k shared + 1k private, +1.5k per turn, 3 sessions x 3 turns, chunk/grid 1024), `legacy` vs `prefix`, auto budget (12.7 GiB): +`prefix` reused 28,672 of 49,950 prompt tokens (57%) vs 23,984 (48%) for `legacy`, whose turn>=2 requests all reuse the 2,998-token root; all 8 + 8 verified +requests were equal to the full read (including the cancelled-prefill and cancelled-decode checks and a copy of 1-4 blocks from host RAM, import 0.2-1.2 s +there because the WSL launch latency of the per-layer resolver reset dominates). One run of the same scenario ended in `Failed(CudaExecution)` on its +last request while the host was busy compiling; two reruns on an idle host passed (see Remaining). + +### 5. The policy at the production size, model-free + +`twelve_sessions_growing_to_180k_tokens...` (release, `--ignored`): 12 sessions behind one runtime, 8k shared prompt, histories growing 4k per request to 184k +tokens (516 requests), real node/block sizes (127 MB / 29 MB), 13 GB budget: the budget holds (13,305 of 13,312 MiB), reuse 62.2% (12 sessions of ~90k +tokens average do not fit in 13 GB: the cache keeps the sessions it can and rejects 8,212 candidate checkpoints), lookup over up to 184k tokens 124 us mean / +1.2 ms max, the policy 3.0 ms per request mean / 37 ms max. + +## Tests + +* Model-free (`cargo test -p leleka-runtime --lib prefix`): hash chain (pinned values), budget profiles and parsing, store + (sharing, refcounts, collisions, eviction by value, caps, thinning, budget enforcement, orphans), the orchestrator over a fake + device whose positional buffer is a token per cell (cross-session resume, interleaving, copy-only-what-the-buffer-lost, + cancellation, failed import, budget, low host memory, pool queries) and `PromptPlan` grid cuts. +* GPU, model-free (`cargo test -p leleka-cuda-driver --features cuda-driver --lib -- --ignored parked_tests`, RTX 3080 Laptop + sm86 build, 2026-10-17): parked K/V pages and index rows written back come out byte for byte, in pieces and as sub-ranges, + the tail round-trips through the image, malformed spans are refused. +* HTTP/gRPC (`cargo test -p strata-desktop-core --test api_over_runtime`, `-p strata-control --test prefix_match_http`): the summary + travels engine -> runtime gRPC snapshot -> worker -> `/v1/status` and answers `/v1/prefix_match`. +* Real model: `backend::original_serve_prefix_smoke::original_serve_prefix_cache_smoke` (jobs 921-92x). + +## Remaining + +* **Grid granularity.** The grid is the price of exactness (a state is shareable only where every request cuts the same way). A shared prefix shorter + than one block is not cached (the 8,000-token prompt of the 8192 runs), and a session re-reads on average half a block. Smaller blocks cut that loss + but run the prefill at the small chunk's speed (~1.4k tok/s at 2048 vs ~3.5k at 8192 on the 5090). A two-level grid (fine steps over the first tokens, + coarse after) would keep both; not built. +* **Cold VRAM window after an import.** The resident K/V window is reset when the host image changed; the first decode rounds refill it (+0.5-5%, + <= 30 ms per request on identical outputs). A targeted invalidation of only the overwritten pages would remove it. +* **RAM is the ceiling.** 2.6 GB of blocks per 180k-token session plus 127 MB per node; the 5090 holder leaves 7-35 GiB depending on the page cache + (`auto` follows it, and re-checks `MemAvailable` before every insertion). More sessions need `--expert-source mapped`, a bigger box, or a spill tier + (NVMe) that is not built. The INT8 K/V images are not compressed. +* **One buffer, one generation.** The cache removes the cost of switching sessions, not the serialization of the engine; concurrent sessions need runtimes, + hence the pool summary. +* **Exactness holds for the static expert tier.** With the adaptive tier or the prompt-routing seed on, GPU/CPU expert placement noise is the known + envelope (the checks above ran with `ADAPT_EVERY=0`, seed off). The live continuation of the Original is not used (decode-produced cells are not + prefill cells). +* **Not defaulted.** The cache is opt-in (`--prefix-cache-mib auto` replaces the conversation cache). One laptop run (host busy compiling) ended in + `Failed(CudaExecution)` on its last request and invalidated the cache as designed; four reruns on an idle host passed. Unexplained (suspect the WDDM + watchdog under host-memory contention); enabling by default is a one-line change in `leleka-inference` once the pool acceptance tests are done. +* **The router** and a Bloom summary for hundreds of runtimes are not part of this work; the summary lists up to 512 heads (about 25 KB).