STRA-338 S19a: the cross-session prefix cache and the pure memory admission move to the new leleka-engine-core crate (L2); leleka-runtime re-exports them under the old paths

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 10:54:33 +01:00
parent fc591f4e96
commit 38eb771a44
22 changed files with 402 additions and 92 deletions
Generated
+9
View File
@@ -1313,6 +1313,14 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "leleka-engine-core"
version = "0.1.0"
dependencies = [
"serde",
"serde_json",
]
[[package]]
name = "leleka-experimental-ref"
version = "0.1.0"
@@ -1535,6 +1543,7 @@ dependencies = [
"leleka-backend-api",
"leleka-context",
"leleka-cuda-driver",
"leleka-engine-core",
"leleka-experimental-ref",
"leleka-memory",
"leleka-model-format",
+2 -2
View File
@@ -1,7 +1,7 @@
[workspace]
resolver = "3"
members = ["crates/backend-api", "crates/worker-protocol", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "crates/gateway-text", "crates/gateway-domain", "control-plane", "desktop-core", "crates/libc-shim", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/leleka-memory", "crates/deploy", "crates/obs", "crates/native-cpu-expert", "crates/native-parity-bench", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy"]
default-members = ["crates/backend-api", "crates/worker-protocol", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "crates/gateway-text", "crates/gateway-domain", "control-plane", "desktop-core", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/leleka-memory", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "crates/deploy", "crates/obs"]
members = ["crates/backend-api", "crates/worker-protocol", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "crates/gateway-text", "crates/gateway-domain", "crates/engine-core", "control-plane", "desktop-core", "crates/libc-shim", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/leleka-memory", "crates/deploy", "crates/obs", "crates/native-cpu-expert", "crates/native-parity-bench", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy"]
default-members = ["crates/backend-api", "crates/worker-protocol", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "crates/gateway-text", "crates/gateway-domain", "crates/engine-core", "control-plane", "desktop-core", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/leleka-memory", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "crates/deploy", "crates/obs"]
[workspace.package]
edition = "2024"
+1 -1
View File
@@ -90,7 +90,7 @@
"crates/leleka-runtime/src/gpu_proofs/native_down_public_pair.rs": 540,
"crates/leleka-runtime/src/model_binding/qwen4exp_kar_ple.rs": 1026,
"crates/leleka-runtime/src/model_binding/qwen4exp_mtp.rs": 1124,
"crates/leleka-runtime/src/prefix_cache/store/tests.rs": 582,
"crates/engine-core/src/prefix_cache/store/tests.rs": 582,
"crates/leleka-runtime/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3.rs": 980,
"crates/leleka-runtime/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn.rs": 466,
"crates/leleka-runtime/src/qwen_forward/gr.rs": 1036,
+1 -1
View File
@@ -11,7 +11,7 @@
"leleka-tokenizer", "leleka-gguf", "leleka-kar-codec", "leleka-experimental-ref", "leleka-cpu-sys", "leleka-cpu-kernels",
"leleka-shm", "leleka-openvino", "leleka-memory", "leleka-gateway-text"
],
"L2": ["leleka-gateway-domain"],
"L2": ["leleka-gateway-domain", "leleka-engine-core"],
"L3": [
"leleka-libc-shim", "leleka-model-format", "leleka-cuda-driver", "leleka-native-cpu-expert", "leleka-gptoss", "leleka-igpu",
"leleka-gptoss-igpu", "leleka-gptoss-npu", "leleka-npu-service", "leleka-cpu-worker", "leleka-igpu-worker", "leleka-npu-worker",
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "leleka-engine-core"
version = "0.1.0"
description = "Pure domain of the Leleka serving engine: the cross-session prefix cache, host-memory admission. No CUDA, no async runtime, no env, no filesystem, no clock."
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[dependencies]
serde = { version = "1", features = ["derive"] }
[features]
# Test-only helpers (store invariant checks) for the crates that drive the store in their own tests.
testing = []
[dev-dependencies]
serde_json = "1"
[lints]
workspace = true
+7
View File
@@ -0,0 +1,7 @@
//! Pure domain of the serving engine (STRA-338 S19). Everything here is model-free and device-free: it builds
//! without CUDA, a clock, the environment or the filesystem, so it is tested without a GPU and reused by every adapter.
//!
//! The modules keep the names and paths they had inside `leleka-runtime`, which re-exports them under the old paths.
pub mod memory;
pub mod prefix_cache;
+6
View File
@@ -0,0 +1,6 @@
//! Host physical-memory admission, the pure half of `conversation_memory.{hpp,cpp}`.
/// Whether `allocation` fits in `available` while leaving `floor` free.
pub fn memory_admit(available: Option<u64>, allocation: u64, floor: u64) -> bool {
available.is_some_and(|available| available >= floor && allocation <= available - floor)
}
@@ -29,15 +29,29 @@ impl AutoBudget {
/// 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<u64>) -> Self {
Self { mem_available, floor: 4 * GIB, percent: 75, cap: 96 * GIB, min_useful: GIB }
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<u64>) -> Self {
Self { mem_available, floor: 4 * GIB, percent: 75, cap: 24 * GIB, min_useful: GIB }
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 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;
@@ -48,7 +62,7 @@ impl AutoBudget {
/// 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<u64>, additional: u64, floor: u64) -> bool {
crate::conversation::memory::memory_admit(mem_available, additional, floor)
crate::memory::memory_admit(mem_available, additional, floor)
}
/// Parse the operator value of `--prefix-cache-mib`: `auto`, `off`/`0`, or a size in MiB.
@@ -75,20 +89,37 @@ mod tests {
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);
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);
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::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);
}
@@ -79,7 +79,10 @@ mod tests {
fn the_function_is_pinned() {
// These values are the protocol: a router computes them independently.
let tokens: Vec<i32> = (0..8).collect();
assert_eq!(chain(&tokens, 4), vec![0x9e7feaf140c714d6, 0xcd122713bf23558d]);
assert_eq!(
chain(&tokens, 4),
vec![0x9e7feaf140c714d6, 0xcd122713bf23558d]
);
}
#[test]
@@ -10,7 +10,7 @@ pub mod hash;
pub mod store;
pub mod summary;
pub use hash::{chain, chain_step, CHAIN_SEED, CHAIN_VERSION};
pub use hash::{CHAIN_SEED, CHAIN_VERSION, chain, chain_step};
pub use store::{ByteSize, Consider, PolicyParams, PrefixStore, Reject, Stats, StoreConfig};
pub use summary::{PrefixMatch, PrefixSummary};
@@ -13,7 +13,7 @@
//! 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 super::hash::{CHAIN_SEED, chain_step};
use std::collections::{HashMap, HashSet};
/// Bytes a payload pins in host memory.
@@ -183,8 +183,8 @@ pub struct PrefixStore<N, B> {
#[cfg(test)]
mod tests;
mod decayed_fn;
mod impl_default_for_policyparams;
mod impl_prefixstore;
mod decayed_fn;
#[allow(unused_imports)]
use decayed_fn::decayed;
@@ -3,7 +3,6 @@
#[allow(unused_imports)]
use super::*;
pub(super) fn decayed(value: f64, age: u64, half_life: f64) -> f64 {
if value == 0.0 {
0.0
@@ -3,12 +3,24 @@
#[allow(unused_imports)]
use super::*;
impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
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(), tails: HashMap::new(), clock: 0, now_ms: 0, node_bytes: 0, block_bytes: 0, stats: Stats::default(), orphans: HashSet::new() }
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(),
tails: HashMap::new(),
clock: 0,
now_ms: 0,
node_bytes: 0,
block_bytes: 0,
stats: Stats::default(),
orphans: HashSet::new(),
}
}
pub fn config(&self) -> &StoreConfig {
&self.cfg
@@ -60,7 +72,12 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
return 0;
}
let now = self.now_ms;
let stale: Vec<u64> = self.nodes.iter().filter(|(_, node)| now.saturating_sub(node.last_used_ms) > limit).map(|(key, _)| *key).collect();
let stale: Vec<u64> = self
.nodes
.iter()
.filter(|(_, node)| now.saturating_sub(node.last_used_ms) > limit)
.map(|(key, _)| *key)
.collect();
for key in &stale {
self.evict(*key);
}
@@ -95,7 +112,11 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
pub fn tail_of(&self, key: u64) -> Option<(&B, usize, usize)> {
let node = self.nodes.get(&key)?;
let tail = node.tail.as_ref()?;
Some((&tail.payload, node.path.len() * self.cfg.block_tokens, tail.tokens.len()))
Some((
&tail.payload,
node.path.len() * self.cfg.block_tokens,
tail.tokens.len(),
))
}
/// 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<Vec<(usize, &B)>> {
@@ -125,15 +146,26 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
}
prev = h;
if self.nodes.contains_key(&h) {
best = Some(Match { key: h, tokens: end });
best = Some(Match {
key: h,
tokens: end,
});
}
// request-end checkpoints that extend this block (the longest whose tokens are the prompt's next ones)
if let Some(keys) = self.tails.get(&h) {
for key in keys {
let Some(tail) = self.nodes.get(key).and_then(|n| n.tail.as_ref()) else { continue };
let Some(tail) = self.nodes.get(key).and_then(|n| n.tail.as_ref()) else {
continue;
};
let upto = end + tail.tokens.len();
if upto <= limit && best.is_none_or(|b| upto > b.tokens) && tokens.get(end..upto).is_some_and(|t| t == &*tail.tokens) {
best = Some(Match { key: *key, tokens: upto });
if upto <= limit
&& best.is_none_or(|b| upto > b.tokens)
&& tokens.get(end..upto).is_some_and(|t| t == &*tail.tokens)
{
best = Some(Match {
key: *key,
tokens: upto,
});
}
}
}
@@ -144,13 +176,20 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
/// 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)
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().filter(|(_, n)| n.tail.is_none()).map(|(k, n)| (*k, n.path.len() * self.cfg.block_tokens)).collect();
let mut heads: Vec<(u64, usize)> = self
.nodes
.iter()
.filter(|(_, n)| n.tail.is_none())
.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
}
@@ -173,12 +212,16 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
/// 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 Some(node) = self.nodes.get(&key) else {
return false;
};
if node.tail.is_some() {
return false;
}
let at = node.path.len() - 1;
self.nodes.values().any(|other| other.path.len() > node.path.len() && other.path[at] == key)
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
@@ -190,7 +233,11 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
/// `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 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) {
@@ -208,7 +255,11 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
pub(in super::super) fn probability(&self, node: &Node<N, B>, 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 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()) * self.recency(node)
@@ -3,14 +3,15 @@
#[allow(unused_imports)]
use super::*;
impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
/// 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).
pub(in super::super) fn scores(&self, removed: &HashSet<u64>, protect: &HashSet<u64>) -> Vec<Scored> {
pub(in super::super) fn scores(
&self,
removed: &HashSet<u64>,
protect: &HashSet<u64>,
) -> Vec<Scored> {
let g = self.cfg.block_tokens;
let mut cover: HashMap<u64, u32> = HashMap::new();
for key in removed {
@@ -28,7 +29,11 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
}
let mut depth = 0;
// a tail node's nearest ancestor may be the grid node at the end of its own path
let upto = if node.tail.is_some() { node.path.len() } else { node.path.len() - 1 };
let upto = if node.tail.is_some() {
node.path.len()
} else {
node.path.len() - 1
};
for i in (0..upto).rev() {
let h = node.path[i];
if self.nodes.contains_key(&h) && !removed.contains(&h) {
@@ -41,17 +46,29 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
}
let mut out = Vec::with_capacity(ancestor.len());
for (key, node) in &self.nodes {
let Some(&anc) = ancestor.get(key) else { continue };
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) {
if block
.refs
.saturating_sub(cover.get(h).copied().unwrap_or(0))
== 1
&& !protect.contains(h)
{
freed += block.bytes;
}
}
let marginal = (self.tokens_of(node) - 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.push(Scored {
key: *key,
score: p * marginal / freed.max(1) as f64,
value: p * marginal,
freed,
});
}
out
}
@@ -59,21 +76,45 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
/// 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 {
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");
assert!(
!tokens.is_empty() && tokens.len() % g == 0,
"a node covers whole blocks"
);
self.consider_at(tokens, frontier, est_state, est_block)
}
/// `consider` for a checkpoint at the END OF A REQUEST: `tokens` is a whole number of blocks (at least one) plus a tail of
/// 1..block_tokens tokens. The tail's cells are charged as the same share of a block.
pub fn consider_tail(&mut self, tokens: &[i32], frontier: bool, est_state: usize, est_block: usize) -> Consider {
pub fn consider_tail(
&mut self,
tokens: &[i32],
frontier: bool,
est_state: usize,
est_block: usize,
) -> Consider {
let g = self.cfg.block_tokens;
assert!(tokens.len() > g && tokens.len() % g != 0, "a tail node extends at least one whole block by a partial one");
assert!(
tokens.len() > g && tokens.len() % g != 0,
"a tail node extends at least one whole block by a partial one"
);
self.consider_at(tokens, frontier, est_state, est_block)
}
pub(in super::super) fn consider_at(&mut self, tokens: &[i32], frontier: bool, est_state: usize, est_block: usize) -> Consider {
pub(in super::super) fn consider_at(
&mut self,
tokens: &[i32],
frontier: bool,
est_state: usize,
est_block: usize,
) -> Consider {
let g = self.cfg.block_tokens;
let tail_len = tokens.len() % g;
self.release_orphans();
@@ -93,14 +134,20 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
path.push(h);
prev = h;
}
let key = if tail_len == 0 { prev } else { chain_step(prev, &tokens[tokens.len() - tail_len..]) };
let key = if tail_len == 0 {
prev
} else {
chain_step(prev, &tokens[tokens.len() - tail_len..])
};
if let Some(node) = self.nodes.get_mut(&key) {
node.touched = self.clock;
node.last_used_ms = self.now_ms;
self.stats.already_cached += 1;
return Consider::Exists;
}
let need = est_state + missing.len() * est_block + (est_block as u128 * tail_len as u128 / g as u128) as usize;
let need = est_state
+ missing.len() * est_block
+ (est_block as u128 * tail_len as u128 / g as u128) as usize;
if need > self.cfg.budget_bytes {
self.stats.rejected += 1;
return Consider::Rejected(Reject::TooLarge);
@@ -138,26 +185,52 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
for key in removed {
self.evict_keeping(key, &protect);
}
Consider::Admit(Candidate { key, path, tail_len, missing, frontier })
Consider::Admit(Candidate {
key,
path,
tail_len,
missing,
frontier,
})
}
/// Expected tokens saved by a node at the end of `path` (against its nearest surviving ancestor).
pub(in super::super) fn candidate_value(&self, path: &[u64], tail_len: usize, frontier: bool, removed: &HashSet<u64>) -> f64 {
pub(in super::super) fn candidate_value(
&self,
path: &[u64],
tail_len: usize,
frontier: bool,
removed: &HashSet<u64>,
) -> f64 {
let g = self.cfg.block_tokens;
let upto = if tail_len > 0 { path.len() } else { path.len() - 1 };
let upto = if tail_len > 0 {
path.len()
} else {
path.len() - 1
};
let anc = (0..upto)
.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 + tail_len - anc) as f64;
let p = if frontier { self.cfg.policy.frontier_prior } else { self.cfg.policy.interior_prior };
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> {
pub fn commit(
&mut self,
candidate: Candidate,
tokens: &[i32],
state: N,
blocks: Vec<(usize, B)>,
) -> Result<(), Reject> {
if candidate.tail_len != 0 {
return Err(Reject::Mismatch);
}
@@ -166,26 +239,55 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
/// `commit` of a tail node: `tail` holds the cells of the tokens after the last full block. Tail nodes of the same history that
/// end earlier (a token-wise prefix of this one) are superseded: the next request of the session starts from this one.
pub fn commit_tail(&mut self, candidate: Candidate, tokens: &[i32], state: N, blocks: Vec<(usize, B)>, tail: B) -> Result<(), Reject> {
pub fn commit_tail(
&mut self,
candidate: Candidate,
tokens: &[i32],
state: N,
blocks: Vec<(usize, B)>,
tail: B,
) -> Result<(), Reject> {
self.commit_tail_keeping(candidate, tokens, state, blocks, tail, None)
}
/// `commit_tail` that leaves the tail node ending at `keep_end` tokens standing. The decode-end checkpoint of a request extends
/// the same request's prompt-end checkpoint; when the client resends the history without the reply's reasoning, the next prompt
/// shares only the prompt part, so the prompt-end node must survive (the next request's own tails supersede it as usual).
pub fn commit_tail_keeping(&mut self, candidate: Candidate, tokens: &[i32], state: N, blocks: Vec<(usize, B)>, tail: B, keep_end: Option<usize>) -> Result<(), Reject> {
pub fn commit_tail_keeping(
&mut self,
candidate: Candidate,
tokens: &[i32],
state: N,
blocks: Vec<(usize, B)>,
tail: B,
keep_end: Option<usize>,
) -> Result<(), Reject> {
if candidate.tail_len == 0 {
return Err(Reject::Mismatch);
}
self.insert(candidate, tokens, state, blocks, Some(tail), keep_end)
}
pub(in super::super) fn insert(&mut self, candidate: Candidate, tokens: &[i32], state: N, blocks: Vec<(usize, B)>, tail: Option<B>, keep_end: Option<usize>) -> Result<(), Reject> {
pub(in super::super) fn insert(
&mut self,
candidate: Candidate,
tokens: &[i32],
state: N,
blocks: Vec<(usize, B)>,
tail: Option<B>,
keep_end: Option<usize>,
) -> Result<(), Reject> {
let g = self.cfg.block_tokens;
if tokens.len() != candidate.path.len() * g + candidate.tail_len
|| 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]))
|| 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);
@@ -193,7 +295,15 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
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 });
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);
@@ -203,12 +313,22 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
None => return Err(Reject::Mismatch),
}
}
let superseded = if candidate.tail_len > 0 { self.superseded_tails(&candidate.path, tokens, keep_end) } else { Vec::new() };
let tail = tail.map(|payload| Tail { tokens: tokens[tokens.len() - candidate.tail_len..].into(), payload });
let superseded = if candidate.tail_len > 0 {
self.superseded_tails(&candidate.path, tokens, keep_end)
} else {
Vec::new()
};
let tail = tail.map(|payload| Tail {
tokens: tokens[tokens.len() - candidate.tail_len..].into(),
payload,
});
let bytes = state.byte_size() + tail.as_ref().map_or(0, |t| t.payload.byte_size());
self.node_bytes += bytes;
if tail.is_some() {
self.tails.entry(*candidate.path.last().expect("a tail extends a block")).or_default().push(candidate.key);
self.tails
.entry(*candidate.path.last().expect("a tail extends a block"))
.or_default()
.push(candidate.key);
}
self.nodes.insert(
candidate.key,
@@ -235,15 +355,23 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
}
/// Tail nodes whose tokens are a strict prefix of `tokens` (the history this tail node continues).
pub(in super::super) fn superseded_tails(&self, path: &[u64], tokens: &[i32], keep_end: Option<usize>) -> Vec<u64> {
pub(in super::super) fn superseded_tails(
&self,
path: &[u64],
tokens: &[i32],
keep_end: Option<usize>,
) -> Vec<u64> {
let g = self.cfg.block_tokens;
let mut out = Vec::new();
for (j, parent) in path.iter().enumerate() {
let start = (j + 1) * g;
for key in self.tails.get(parent).into_iter().flatten() {
let Some(tail) = self.nodes.get(key).and_then(|n| n.tail.as_ref()) else { continue };
let Some(tail) = self.nodes.get(key).and_then(|n| n.tail.as_ref()) else {
continue;
};
let end = start + tail.tokens.len();
if end < tokens.len() && Some(end) != keep_end && tokens[start..end] == *tail.tokens {
if end < tokens.len() && Some(end) != keep_end && tokens[start..end] == *tail.tokens
{
out.push(*key);
}
}
@@ -3,10 +3,7 @@
#[allow(unused_imports)]
use super::*;
impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
pub(in super::super) fn enforce_budget(&mut self, fresh: u64) {
while self.bytes() > self.cfg.budget_bytes || self.nodes.len() > self.cfg.max_nodes {
let victim = self
@@ -44,7 +41,9 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
/// `evict`, except that blocks in `keep` stay (as orphans) when this was their last node.
pub(in super::super) fn evict_keeping(&mut self, key: u64, keep: &HashSet<u64>) {
let Some(node) = self.nodes.remove(&key) else { return };
let Some(node) = self.nodes.remove(&key) else {
return;
};
self.node_bytes -= node.bytes;
self.stats.evicted += 1;
if node.tail.is_some() {
@@ -91,8 +90,8 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
self.enforce_budget(0);
}
#[cfg(test)]
pub(crate) fn check_invariants(&self) {
#[cfg(any(test, feature = "testing"))]
pub fn check_invariants(&self) {
let mut refs: HashMap<u64, u32> = HashMap::new();
let mut node_bytes = 0;
for node in self.nodes.values() {
@@ -104,10 +103,20 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
}
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");
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));
assert_eq!(
(node_bytes, block_bytes),
(self.node_bytes, self.block_bytes)
);
}
}
@@ -75,10 +75,21 @@ pub fn hex(h: u64) -> String {
}
impl PrefixSummary {
pub fn build<N: ByteSize, B: ByteSize>(store: &PrefixStore<N, B>, namespace: u64, max_heads: usize) -> Self {
pub fn build<N: ByteSize, B: ByteSize>(
store: &PrefixStore<N, B>,
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();
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,
@@ -97,8 +108,16 @@ impl PrefixSummary {
/// 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)
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)
}
}
@@ -125,10 +144,17 @@ mod tests {
}
fn filled() -> (PrefixStore<P, P>, Vec<i32>) {
let mut s = PrefixStore::new(StoreConfig { block_tokens: 8, budget_bytes: 1 << 20, max_nodes: 16, policy: PolicyParams::default() });
let mut s = PrefixStore::new(StoreConfig {
block_tokens: 8,
budget_bytes: 1 << 20,
max_nodes: 16,
policy: PolicyParams::default(),
});
let tokens: Vec<i32> = (0..48).collect();
for k in [2usize, 6] {
let Consider::Admit(c) = s.consider(&tokens[..k * 8], true, 10, 5) else { panic!() };
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();
}
@@ -139,13 +165,25 @@ mod tests {
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.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(&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);
@@ -163,8 +201,18 @@ mod tests {
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::<PrefixMatch>(&serde_json::to_string(&m).unwrap()).unwrap(), m);
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::<PrefixMatch>(&serde_json::to_string(&m).unwrap()).unwrap(),
m
);
}
}
+2
View File
@@ -13,6 +13,7 @@ serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["float_roundtrip"] }
sha2 = "0.11"
leleka-backend-api = { path = "../backend-api" }
leleka-engine-core = { path = "../engine-core" }
leleka-tokenizer = { path = "../tokenizer" }
leleka-model-format = { path = "../model-format" }
leleka-quant-core = { path = "../quant-core" }
@@ -38,5 +39,6 @@ workspace = true
[dev-dependencies]
serde_json = "1"
leleka-engine-core = { path = "../engine-core", features = ["testing"] }
# Model-free device probe of the VRAM expert tier (test builds only).
leleka-cuda-driver = { path = "../cuda-driver", features = ["cuda-driver", "expert-tier-probe"] }
@@ -52,10 +52,7 @@ pub fn mem_available(mut meminfo: impl BufRead) -> Option<u64> {
result
}
/// Whether `allocation` fits in `available` while leaving `floor` free.
pub fn memory_admit(available: Option<u64>, allocation: u64, floor: u64) -> bool {
available.is_some_and(|available| available >= floor && allocation <= available - floor)
}
pub use leleka_engine_core::memory::memory_admit;
/// Available host physical memory right now; `None` when unknown (any
/// non-Linux target, unreadable or malformed `/proc/meminfo`).
+1 -1
View File
@@ -25,7 +25,7 @@ pub(crate) mod settings;
pub mod backend;
pub use leleka_context::{context_policy, memory_plan, rope_scaling};
pub mod conversation;
pub mod prefix_cache;
pub use leleka_engine_core::prefix_cache;
pub mod serve_tuning;
#[cfg_attr(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")), allow(dead_code))]
pub(crate) mod serve_meta;