test(prefix-cache): GPU smoke harness for interleaved agent sessions, model-free GPU round-trip of the K/V and index transfer
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
8ad4dd5d75
commit
d53db650fd
@@ -374,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<u8> {
|
||||
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<u8> {
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3475,6 +3475,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"))]
|
||||
|
||||
@@ -0,0 +1,410 @@
|
||||
//! 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).
|
||||
//!
|
||||
//! 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 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::<u64>().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<u32> {
|
||||
let mut ids: Vec<u32> = 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<u32>,
|
||||
turn: usize,
|
||||
}
|
||||
|
||||
/// What one request returned.
|
||||
struct Served {
|
||||
tokens: Vec<i32>,
|
||||
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<usize>,
|
||||
cancel_rounds: Option<usize>,
|
||||
) -> Result<Served, ServeError> {
|
||||
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::<f64>);
|
||||
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::<Vec<_>>().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 fd: u32 = env::var("LELEKA_STRA169_KAR_FD").expect("missing inherited sealed archive descriptor").parse().expect("invalid descriptor");
|
||||
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 inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_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");
|
||||
binding.load_resident_expert_source().expect("resident expert source load failed");
|
||||
let budget_gib = number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 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<Session> = 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<usize> = Vec::new();
|
||||
let mut grow: Vec<Vec<usize>> = 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<f64> = (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;
|
||||
match mode.as_str() {
|
||||
"prefix" => {
|
||||
let budget = match text("LELEKA_PFX_MIB", "auto").as_str() {
|
||||
"auto" => PrefixBudget::Auto,
|
||||
other => PrefixBudget::Bytes(other.parse::<u64>().expect("LELEKA_PFX_MIB: auto or MiB") << 20),
|
||||
};
|
||||
config.prefix = Some(PrefixConfig { budget, block_tokens: number("LELEKA_PFX_BLOCK", 0), ..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<String> = Vec::new();
|
||||
let mut decode_rates: Vec<f64> = Vec::new();
|
||||
let mut reused_total = 0usize;
|
||||
let mut prompt_total = 0usize;
|
||||
let mut ttft_sum = 0.0;
|
||||
let last_of: Vec<usize> = (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!("<tool_call>shell {{\"cmd\": \"cargo test -p mod_{s} --lib\"}}</tool_call><|im_end|>\n<|im_start|>user\n<tool_response>\n"), true));
|
||||
next.extend(filler(&tokenizer, &mut rng, kind, size));
|
||||
next.extend(tok("\n</tool_response><|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}"));
|
||||
}
|
||||
}
|
||||
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::<f64>() / 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::<Vec<_>>(), 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("<tool_call>shell {\"cmd\": \"ls\"}</tool_call><|im_end|>\n<|im_start|>user\n<tool_response>\n", true));
|
||||
next.extend(filler(&tokenizer, &mut rng, 1, 3 * capacity.min(2048)));
|
||||
next.extend(tok("\n</tool_response><|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:?}");
|
||||
}
|
||||
@@ -142,6 +142,8 @@ pub(super) struct PrefixServe<S: ByteSize, B: ByteSize> {
|
||||
seen_block_bytes: Option<usize>,
|
||||
park_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,
|
||||
}
|
||||
|
||||
fn lcp(a: &[i32], b: &[i32]) -> usize {
|
||||
@@ -171,9 +173,15 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
|
||||
seen_block_bytes: None,
|
||||
park_ms_request: 0.0,
|
||||
admitted_request: 0,
|
||||
bypass: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
@@ -231,6 +239,10 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
|
||||
let g = self.block_tokens;
|
||||
self.park_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 });
|
||||
|
||||
@@ -540,6 +540,15 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<PrefixSummary> {
|
||||
|
||||
Reference in New Issue
Block a user