prefix cache: log why a checkpoint is not taken; re-judge a LowMemory refusal after the working-set trim (turn 2 resumes at the prompt-end tail)
The prompt-end tail and some grid points were refused against the admit floor (soft + reserve) while the host read 8.9 GiB: on Windows the mapped expert pages count as used, and the periodic trim only runs below the soft floor. Which checkpoint was lost varied from run to run (turn 2 reused 43,008 / 36,864 tokens). Now the refusal is re-judged once after Governor::available_after_relief. after_prefill / after_decode always log their outcome with available / additional / floor; the admit line of the prompt-end tail is no longer behind LELEKA_PREFIX_TRACE. Smoke under the shipped defaults: 7 grid points + tail admitted, turn 2 cached_tokens 45,765. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
d97185089b
commit
03794d5fa8
@@ -547,6 +547,18 @@ impl Governor {
|
||||
/// a shed evicts prefix-cache blocks, and live runs showed it firing every few seconds at the floor (laptop 256k session, 2026-10-26: 113 blocks
|
||||
/// evicted, the fourth turn re-read 223k tokens in 32 minutes).
|
||||
fn relieve_working_set(&self, facts: HostFacts) -> HostFacts {
|
||||
self.relieve_working_set_below(facts, self.policy().soft_floor)
|
||||
}
|
||||
|
||||
/// The available memory after handing the engine's trimmable working-set pages back, for a cache owner that needs `needed` bytes of it
|
||||
/// (a prefix-cache checkpoint must leave the admit floor free: a reading of 8.9 GiB against a floor of 9.2 GiB refused a 0.2 GiB checkpoint
|
||||
/// that the very next trim would have admitted, because the periodic trim only runs below the soft floor). At most one trim per 250 ms.
|
||||
pub fn available_after_relief(&self, needed: u64) -> Option<u64> {
|
||||
let facts = self.probe();
|
||||
self.relieve_working_set_below(facts, needed).effective_available()
|
||||
}
|
||||
|
||||
fn relieve_working_set_below(&self, facts: HostFacts, threshold: u64) -> HostFacts {
|
||||
if !cfg!(windows) {
|
||||
return facts;
|
||||
}
|
||||
@@ -556,7 +568,7 @@ impl Governor {
|
||||
return facts;
|
||||
}
|
||||
let Some(available) = facts.effective_available() else { return facts };
|
||||
if available >= self.policy().soft_floor {
|
||||
if available >= threshold {
|
||||
return facts;
|
||||
}
|
||||
let now = self.now_ms();
|
||||
|
||||
@@ -147,6 +147,24 @@ pub(super) struct Start {
|
||||
pub(super) match_us: f64,
|
||||
}
|
||||
|
||||
/// The available memory a checkpoint of `additional` bytes is judged against. On Windows the engine's touched mapped expert pages sit in its
|
||||
/// working set and count as used although they are trimmable, and the periodic trim only runs below the soft floor: a host that reads a little
|
||||
/// above the soft floor and below the admit floor (soft + reserve) refused every checkpoint (the prompt-end tail of turn 1 of the laptop session,
|
||||
/// 0.2 GiB, was refused at 8.9 GiB against a floor of 9.2 GiB, and turn 2 re-read 2,753 tokens from the last grid point). So a refusal is
|
||||
/// re-judged once after the governor hands the trimmable pages back.
|
||||
fn admission_reading(reading: Option<u64>, additional: u64, floor: u64) -> Option<u64> {
|
||||
let needed = additional.saturating_add(floor);
|
||||
// unknown telemetry stays closed
|
||||
let Some(have) = reading else { return None };
|
||||
if have >= needed {
|
||||
return reading;
|
||||
}
|
||||
match leleka_memory::Governor::global() {
|
||||
Some(governor) => governor.available_after_relief(needed).or(reading),
|
||||
None => reading,
|
||||
}
|
||||
}
|
||||
|
||||
/// What `after_chunk` did.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(super) enum ChunkOutcome {
|
||||
@@ -189,6 +207,8 @@ pub(super) struct PrefixServe<S: ByteSize, B: ByteSize> {
|
||||
configured_budget: usize,
|
||||
/// The memory governor asked to shed and the budget is currently below `configured_budget`.
|
||||
shed: bool,
|
||||
/// Why the last checkpoint attempt was not taken, with the numbers (read once by the stack for its log line).
|
||||
note: Option<String>,
|
||||
}
|
||||
|
||||
/// Milliseconds since the first call, on the monotonic clock (the store's wall-time scale for session retention).
|
||||
@@ -230,6 +250,7 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
|
||||
last_import_split: (0.0, 0.0),
|
||||
configured_budget: usize::try_from(budget_bytes).unwrap_or(usize::MAX),
|
||||
shed: false,
|
||||
note: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -415,6 +436,7 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
|
||||
self.live.extend_from_slice(&prompt[have..end]);
|
||||
}
|
||||
let Some(req) = self.req.as_ref() else { return Ok(ChunkOutcome::Nothing) };
|
||||
self.note = None;
|
||||
if end == 0 || end % g != 0 || end > req.limit {
|
||||
return Ok(ChunkOutcome::Nothing);
|
||||
}
|
||||
@@ -427,12 +449,22 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
|
||||
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::Rejected(why) => {
|
||||
self.note = Some(format!("grid point {end} rejected by the policy: {why:?} (store {} MiB of {} MiB)", self.store.bytes() >> 20, self.configured_budget >> 20));
|
||||
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) {
|
||||
let available = admission_reading(device.available_memory(), additional, self.cfg.memory_floor);
|
||||
if !budget::admit_growth(available, additional, self.cfg.memory_floor) {
|
||||
self.store.abort(candidate);
|
||||
self.note = Some(format!(
|
||||
"grid point {end}: low memory, available {} MiB, additional {} MiB, floor {} MiB",
|
||||
available.map_or_else(|| "unknown".to_owned(), |b| (b >> 20).to_string()),
|
||||
additional >> 20,
|
||||
self.cfg.memory_floor >> 20
|
||||
));
|
||||
return Ok(ChunkOutcome::LowMemory);
|
||||
}
|
||||
let started = Instant::now();
|
||||
@@ -460,7 +492,9 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
|
||||
/// The end of the prompt's prefill: the session stands at `prompt.len() - 1`. With `TailMode::Prompt` or `Reply`, checkpoint
|
||||
/// there (a request-end checkpoint), unless that is a grid point.
|
||||
pub(super) fn after_prefill<D: PrefixDevice<State = S, Block = B>>(&mut self, device: &mut D, prompt: &[i32]) -> Result<ChunkOutcome, Error> {
|
||||
self.note = None;
|
||||
if self.cfg.tail == TailMode::Off || self.bypass || self.req.is_none() {
|
||||
self.note = Some(format!("no tail checkpoint: tail {:?}, bypass {}, request {}", self.cfg.tail, self.bypass, self.req.is_some()));
|
||||
return Ok(ChunkOutcome::Nothing);
|
||||
}
|
||||
let end = prompt.len().saturating_sub(1);
|
||||
@@ -469,7 +503,13 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
|
||||
|
||||
/// The end of the decode: the session stands at `consumed.len()` (the prompt and the committed reply), settled, with the draft
|
||||
/// ring in step. With `TailMode::Reply`, checkpoint there; the cells past the prompt are decode-produced.
|
||||
/// The reason the last checkpoint attempt was not taken, with the numbers; read once.
|
||||
pub(super) fn take_note(&mut self) -> Option<String> {
|
||||
self.note.take()
|
||||
}
|
||||
|
||||
pub(super) fn after_decode<D: PrefixDevice<State = S, Block = B>>(&mut self, device: &mut D, consumed: &[i32]) -> Result<ChunkOutcome, Error> {
|
||||
self.note = None;
|
||||
if self.cfg.tail != TailMode::Reply || self.bypass || self.req.is_none() {
|
||||
return Ok(ChunkOutcome::Nothing);
|
||||
}
|
||||
@@ -488,7 +528,9 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
|
||||
fn admit_tail<D: PrefixDevice<State = S, Block = B>>(&mut self, device: &mut D, tokens: &[i32], keep_end: Option<usize>) -> Result<ChunkOutcome, Error> {
|
||||
let g = self.block_tokens;
|
||||
// a grid point is a pure checkpoint of its own (and a node below one block has no blocks to hang on)
|
||||
if tokens.len() <= g || tokens.len() % g == 0 || device.position()? != tokens.len() as u64 {
|
||||
let position = device.position()?;
|
||||
if tokens.len() <= g || tokens.len() % g == 0 || position != tokens.len() as u64 {
|
||||
self.note = Some(format!("not a tail position: {} tokens, grid {g}, the session stands at {position}", tokens.len()));
|
||||
return Ok(ChunkOutcome::Nothing);
|
||||
}
|
||||
let (est_state, est_block) = device.estimate(g);
|
||||
@@ -498,13 +540,31 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
|
||||
let verdict = self.store.consider_tail(tokens, true, 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::Exists => {
|
||||
self.note = Some(format!("a checkpoint at {} tokens exists already", tokens.len()));
|
||||
return Ok(ChunkOutcome::Exists);
|
||||
}
|
||||
Consider::Rejected(why) => {
|
||||
self.note = Some(format!("rejected by the policy at {} tokens: {why:?} (store {} MiB of {} MiB)", tokens.len(), self.store.bytes() >> 20, self.configured_budget >> 20));
|
||||
return Ok(ChunkOutcome::Rejected(why));
|
||||
}
|
||||
Consider::Admit(candidate) => candidate,
|
||||
};
|
||||
let additional = (est_state + candidate.missing.len() * est_block + est_block) as u64;
|
||||
if !budget::admit_growth(device.available_memory(), additional, self.cfg.memory_floor) {
|
||||
let available = admission_reading(device.available_memory(), additional, self.cfg.memory_floor);
|
||||
let missing = candidate.missing.len();
|
||||
if !budget::admit_growth(available, additional, self.cfg.memory_floor) {
|
||||
self.store.abort(candidate);
|
||||
self.note = Some(format!(
|
||||
"low memory at {} tokens: available {} MiB, additional {} MiB (state {} + {} new blocks of {} MiB + the tail), floor {} MiB",
|
||||
tokens.len(),
|
||||
available.map_or_else(|| "unknown".to_owned(), |b| (b >> 20).to_string()),
|
||||
additional >> 20,
|
||||
est_state >> 20,
|
||||
missing,
|
||||
est_block >> 20,
|
||||
self.cfg.memory_floor >> 20
|
||||
));
|
||||
return Ok(ChunkOutcome::LowMemory);
|
||||
}
|
||||
let started = Instant::now();
|
||||
|
||||
@@ -1431,11 +1431,9 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
||||
let _span = profile::span("prefix.after_prefill");
|
||||
match prefix.after_prefill(self, prompt) {
|
||||
Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => {
|
||||
if std::env::var_os("LELEKA_PREFIX_TRACE").is_some() {
|
||||
operator_text(&format!("prefix tail admit (prompt end): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20));
|
||||
}
|
||||
operator_text(&format!("prefix tail admit (prompt end): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20));
|
||||
}
|
||||
Ok(_) => {}
|
||||
Ok(other) => operator_text(&format!("prefix tail (prompt end) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())),
|
||||
Err(error) => operator_text(&format!("prefix cache: {error:?} while checkpointing the end of the prefill; skipped")),
|
||||
}
|
||||
self.prefix = Some(prefix);
|
||||
@@ -1450,7 +1448,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
||||
Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => {
|
||||
operator_text(&format!("prefix tail admit (decode end): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20));
|
||||
}
|
||||
Ok(other) => operator_text(&format!("prefix tail (decode end) not taken: {other:?}")),
|
||||
Ok(other) => operator_text(&format!("prefix tail (decode end) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())),
|
||||
Err(error) => operator_text(&format!("prefix cache: {error:?} while checkpointing the end of the decode; skipped")),
|
||||
}
|
||||
self.prefix = Some(prefix);
|
||||
@@ -1467,7 +1465,11 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
||||
operator_text(&format!("prefix admit: tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20));
|
||||
}
|
||||
}
|
||||
Ok(_) => {}
|
||||
Ok(other) => {
|
||||
if std::env::var_os("LELEKA_PREFIX_TRACE").is_some() && !matches!(other, ChunkOutcome::Nothing) {
|
||||
operator_text(&format!("prefix admit (grid point {end}) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default()));
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
operator_text(&format!("prefix cache: {error:?} while checkpointing; dropping the cache"));
|
||||
prefix.invalidate();
|
||||
|
||||
@@ -172,3 +172,11 @@ Rule of the owner: the defaults are the speed-optimal ones. For each setting, wh
|
||||
**Correction of earlier statements.** cached_tokens on turn 2 is 43,008 (7 grid points of 6144), not the 45,761 of runs b, A and A3. In those three runs the `reconfigure` (which I used to set the chunk) reopened the stack with the prefix cache **off** (`prefix cache off (budget Auto, available host memory ~20 GiB)`: the automatic budget is 0 after the reopen), so their requests were served by the Original's conversation cache, which resumes exactly at the turn boundary (45,761, then 95,837 ...). My statements that `tail prompt` gave exact reuse were wrong: with the prefix cache on (the shipped path) a request resumes at the last grid checkpoint (43,008 of 45,761: 2,753 tokens, about 13 s more TTFT on turn 2; up to 6,143 tokens per turn), because the prompt-end checkpoint sits at n-1 while the next turn's prompt diverges at n-5 (the generation prompt of the template). So the shipped defaults are about 13 s per turn slower than runs A / A3 (about +5 % wall, estimate), and runs b / A / A3 measure the configuration chunk 6144 + prefix cache off + conversation cache. That configuration is faster on this single-conversation session; its cost is the loss of the cross-request prefix reuse (several agents sharing a prompt prefix) - the owner's call (`memory.prefix_cache_mib: "off"`), not changed here.
|
||||
|
||||
A second smoke with `prefix_cache_tail: reply` (to see whether that default is better): turn 1 TTFT 168.0 s, decode 6.38; turn 2 cached 36,864 (6 grid points: one block fewer admitted), TTFT 235.0 s, decode 7.08, **but the GPU's power limit fell from 110-126 W to 51 W (P3) during turn 2** (the guard watches P5 only), so turn 2 is not comparable. No data favours `reply`, so the shipped value stays `prompt`.
|
||||
|
||||
## 14. Why the prompt-end checkpoint went missing, and the fix (2026-10-28)
|
||||
|
||||
The coordinator was right that my "diverges at n-5" explanation was wrong: the tail is taken at `n - 1` and the 5090 resumes there (`resume=45765`). The laptop logs showed no `prefix tail admit (prompt end)` line for a trivial reason, that line was printed only with `LELEKA_PREFIX_TRACE`, and every non-admitted outcome of `after_prefill` was dropped silently (`Ok(_) => {}`). Now `after_prefill` / `after_decode` always log what they did, and a refusal carries its numbers (`prefix tail (prompt end) not taken: LowMemory: low memory at 45765 tokens: available X MiB, additional Y MiB (...), floor Z MiB`; grid points under `LELEKA_PREFIX_TRACE`).
|
||||
|
||||
**Cause, seen in the first run with the logging** (smoke without the fix): `prefix admit (grid point 36864) not taken: LowMemory: available 8895 MiB, additional 226 MiB, floor 9216 MiB`. The checkpoint admission wants `available - additional >= soft floor + reserve` (8192 + 1024 MiB). On Windows the engine's touched mapped expert pages sit in its working set and count as used, and the governor's trim only runs when the reading is below the **soft** floor, so a host that reads between the soft floor and the admit floor (the normal state of this laptop: 6.5-9 GiB between trims) refuses every checkpoint until the next trim happens to land. Which checkpoint is refused depends on the moment: the earlier smokes lost the 7th grid point or the tail (43,008 and 36,864 tokens reused), this one lost the 6th grid point but kept the tail (turn 2 reused 45,765). The tail refusal in the earlier smoke was inferred from the same mechanism, it was not logged then.
|
||||
|
||||
**Fix:** a refused checkpoint is judged again once after the governor hands the trimmable pages back (`Governor::available_after_relief(needed)`, at most one trim per 250 ms; unknown telemetry stays closed; no effect off Windows). Run with the fix, shipped defaults, `LELEKA_PREFIX_TRACE=1`: all seven grid points (6144 ... 43008) and the prompt-end tail (45765) admitted, no refusal; **turn 2 cached_tokens 45,765** (smoke: 43,008). TTFT 192.5 s / 218.9 s for turns 1 / 2 and decode 6.82 / 7.26 tok/s, **but the GPU power limit read 51 W (P3) for the whole run** (the cap is partly back, the guard only reacts to P5), so these times are not comparable with the 179.7 / 205.6 s of the 117-126 W smoke; the saving is the 2,757 tokens of turn 2 that are no longer re-read (about 10-13 s at the uncapped prefill speed). 71 prefix tests and the 545 runtime / 80 memory unit tests pass.
|
||||
|
||||
Reference in New Issue
Block a user