fix(prefix-cache): a hit counts as shared evidence only on a branch point (histories fork below it), not because another session ran in between
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
b3da9af763
commit
dba10288dc
@@ -63,7 +63,7 @@ pub struct StoreConfig {
|
||||
pub struct Stats {
|
||||
pub requests: u64,
|
||||
pub hits: u64,
|
||||
/// Hits whose deepest node was built by another session (the live buffer did not already hold it).
|
||||
/// 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,
|
||||
@@ -274,9 +274,23 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
|
||||
self.stats.misses += 1;
|
||||
}
|
||||
|
||||
/// A request resumed from `m`. `shared`: the live buffer did not already hold this prefix, i.e. another
|
||||
/// session built it.
|
||||
pub fn record_hit(&mut self, m: &Match, shared: bool) {
|
||||
/// 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;
|
||||
@@ -663,6 +677,27 @@ mod tests {
|
||||
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);
|
||||
@@ -708,7 +743,7 @@ mod tests {
|
||||
for _ in 0..3 {
|
||||
s.tick(10);
|
||||
let m = s.longest_match(&other, other.len() + 1).unwrap();
|
||||
s.record_hit(&m, false);
|
||||
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");
|
||||
@@ -727,7 +762,7 @@ mod tests {
|
||||
for _ in 0..4 {
|
||||
s.tick(10);
|
||||
let m = s.longest_match(&hot, 100).unwrap();
|
||||
s.record_hit(&m, true);
|
||||
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);
|
||||
@@ -757,7 +792,7 @@ mod tests {
|
||||
let t = tokens(session, 2, 4);
|
||||
let m = s.longest_match(&t, t.len()).unwrap();
|
||||
assert!(m.tokens >= 2 * G);
|
||||
s.record_hit(&m, true);
|
||||
s.record_hit_as(&m, true);
|
||||
put(&mut s, &t, 4, true);
|
||||
s.check_invariants();
|
||||
assert!(s.bytes() <= s.config().budget_bytes);
|
||||
@@ -881,7 +916,7 @@ mod tests {
|
||||
for k in 1..=40 {
|
||||
s.tick(100);
|
||||
if let Some(m) = s.longest_match(&t, k * G) {
|
||||
s.record_hit(&m, false);
|
||||
s.record_hit_as(&m, false);
|
||||
}
|
||||
put(&mut s, &t, k, true);
|
||||
assert!(s.bytes() <= s.config().budget_bytes);
|
||||
|
||||
@@ -104,8 +104,10 @@ pub(super) trait PrefixDevice {
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(super) struct Start {
|
||||
pub(super) resume: usize,
|
||||
/// The checkpoint was built by another session (the positional buffer did not hold its prefix).
|
||||
pub(super) shared: bool,
|
||||
/// 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,
|
||||
@@ -279,11 +281,13 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
|
||||
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; one that leaves it somewhere inside is another session (or a
|
||||
// rewrite of history), and its hit counts as a shared one.
|
||||
// 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 shared = !continuation;
|
||||
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();
|
||||
@@ -301,8 +305,8 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
|
||||
self.live.clear();
|
||||
self.live.extend_from_slice(&prompt[..hit.tokens]);
|
||||
self.last_match_us = match_us;
|
||||
self.store.record_hit(&hit, shared);
|
||||
Ok(Some(Start { resume: hit.tokens, shared, copied_tokens, import_ms, 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.
|
||||
@@ -577,7 +581,7 @@ mod tests {
|
||||
d.log.clear();
|
||||
let (start, digest) = request(&mut s, &mut d, &b, None);
|
||||
let start = start.unwrap();
|
||||
assert_eq!((start.resume, start.shared), (4 * G, true));
|
||||
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);
|
||||
@@ -643,7 +647,7 @@ mod tests {
|
||||
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.shared, start.copied_tokens), (6 * G, false, 0));
|
||||
assert_eq!((start.resume, start.switched, start.branch, start.copied_tokens), (6 * G, false, false, 0));
|
||||
assert_eq!(digest, full_digest(&p));
|
||||
}
|
||||
|
||||
@@ -659,7 +663,7 @@ mod tests {
|
||||
let (start, digest) = request(&mut s, &mut d, &a, None);
|
||||
let start = start.unwrap();
|
||||
assert_eq!(start.resume, 8 * G);
|
||||
assert!(start.shared);
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -1266,9 +1266,10 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
||||
self.reused = start.resume;
|
||||
self.resume_point = start.resume;
|
||||
operator_text(&format!(
|
||||
"prefix request: n={n} hit=yes resume={} shared={} copied_tokens={} import_ms={:.1} (state+kv {:.1}, draft {:.1}) match_us={:.0} live_tokens={}",
|
||||
"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.shared,
|
||||
start.switched,
|
||||
start.branch,
|
||||
start.copied_tokens,
|
||||
start.import_ms,
|
||||
prefix.last_import_split().0,
|
||||
|
||||
+15
-9
@@ -23,7 +23,8 @@ see "Results".
|
||||
|
||||
### One token grid
|
||||
|
||||
The prompt is read on a fixed grid (`PromptOptions::grid`, `--prefix-cache-block`, default `min(prefill capacity, 2048)`):
|
||||
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:
|
||||
|
||||
@@ -32,7 +33,9 @@ last prompt token starts the first verify window). There are no turn or root cut
|
||||
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).
|
||||
* 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
|
||||
|
||||
@@ -100,12 +103,15 @@ shared roots surviving churn, a long session settling on a sparse chain, oversiz
|
||||
|
||||
### Budget
|
||||
|
||||
`--prefix-cache-mib auto|N|0`. `auto` takes 60% of what `MemAvailable` has above a 16 GiB floor when the stack opens (server
|
||||
profile, ceiling 96 GiB; laptop profile 50% above 6 GiB, ceiling 24 GiB), and is off when that is under 512 MiB. `MemAvailable`
|
||||
already excludes the sealed KAR memfd (shmem) and the pinned K/V, so on the 5090 server (121 GB, 55 GB sealed memfd, ~50 GB
|
||||
expert source) it comes out around 30 GB, i.e. about 11 sessions of 180k tokens (2.6 GB of blocks + 120 MB of state each) or
|
||||
more than 200 8k-token sessions that share a system prompt. Before every insertion the live `MemAvailable` is checked again
|
||||
against a floor (8 GiB): an insertion that would breach it is skipped, and unknown telemetry fails closed.
|
||||
`--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
|
||||
|
||||
@@ -133,7 +139,7 @@ physical owner invalidates it with the stack.
|
||||
| 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` | `min(prefill capacity, 2048)` | Block size and chunk grid; a multiple of 256, at most the prefill capacity. |
|
||||
| `--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=
|
||||
|
||||
Reference in New Issue
Block a user