Files
leleka/crates/cpu-worker/examples/ab_slots.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 4725df5bdf feat: --cache-slots, one worker keeps the KV caches of several agents and picks the right one (STRA-220)
GptOssEngine holds up to N conversation caches (--cache-slots N on the four workers, default 1 =
unchanged). crates/cpu-worker/src/slots.rs chooses per prompt: continue in place a slot that is
wholly a prefix of the prompt (the same agent's next turn); otherwise take the slot sharing the
longest prefix as a donor and either continue it (losing its tail) or copy the shared part into
a new/empty/least recently used slot (State::copy_prefix_from), whichever discards fewer cached
tokens, so a new agent gets the shared system prompt without destroying another agent's cache.
Results are bit-identical to a fresh prefill (synthetic test: copied prefix continues bit for
bit, donor untouched).

Measured: CPU only, 3 agents, 36 requests: 1.37x/1.46x prompt time, outputs identical.
Through the control plane, 4 agents on one iGPU worker, 3 clean alternating pairs: 986/993/995 s
with 1 slot against 569/575/575 s with 4 slots (1.73x), answers identical in all six runs. The
first run of pair 1 was disturbed by the UTC date in the system prompt changing mid-run and was
repeated. Compare-ConcurrentEpisodes.ps1 takes -Agents, -SharedInstructionTokens and the
'slots' arm and records output hashes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-17 03:45:20 +02:00

268 lines
10 KiB
Rust

//! Paired A/B of one cache slot against several in one worker process, for a pool of agents sending requests one
//! after the other (CPU prefill only, so the outputs can be compared exactly).
//!
//! Run: `cargo run --release -p leleka-cpu-worker --example ab_slots -- <model.gguf> [agents] [turns] [pairs]
//! [max_new] [threads] [header chars] [tool chars]`
//!
//! `agents` agents share one system and developer prefix (`header chars` of instructions) and each has its own task.
//! They take turns round-robin. A turn's prompt is the previous prompt, then the assistant message re-rendered the
//! way Harmony history is (the generated reasoning is dropped: `<|channel|>final<|message|>Noted.<|end|>`), then a
//! new user message with `tool chars` characters of tool output. So the tokens the worker generated never match the
//! next prompt past their first token, and each agent's cache diverges from its next prompt right after the old
//! prompt, as in a real Harmony agent. Every prompt is tokenized whole, as the control plane does.
//!
//! Arm `1 slot` serves them with the worker's single cache, arm `N slots` with one slot per agent
//! (`GptOssEngine::set_cache_slots`). Each arm starts from a cold cache; arms alternate in order per pair. Prints per
//! request the prompt tokens, the tokens reused from the cache and the prompt time, then per arm the totals, and
//! whether the greedy outputs of the two arms are identical (they must be: reuse is bit-exact).
use leleka_cpu_worker::engine::{self, LoadOptions};
use leleka_cpu_worker::serve::serve;
use leleka_gguf::Gguf;
use leleka_tokenizer::gguf_bpe::GgufBpe;
use std::fs::File;
use std::io::{BufReader, Cursor, Read, Write};
use std::path::Path;
use std::sync::{Arc, Mutex, mpsc};
/// The worker's output; once a request is answered it sends `QUIT` on the input channel.
#[derive(Clone)]
struct Shared(Arc<Mutex<Vec<u8>>>, mpsc::Sender<Vec<u8>>);
impl Write for Shared {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(buf);
if buf.starts_with(b"DONE ") || buf.starts_with(b"ERR") {
let _ = self.1.send(b"QUIT\n".to_vec());
}
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
/// Input lines arriving on a channel; blocks until the next one.
struct Input(mpsc::Receiver<Vec<u8>>, Cursor<Vec<u8>>);
impl Read for Input {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
if self.1.position() as usize >= self.1.get_ref().len() {
match self.0.recv() {
Ok(line) => self.1 = Cursor::new(line),
Err(_) => return Ok(0),
}
}
self.1.read(buf)
}
}
struct Run {
tokens: Vec<u32>,
prompt_ms: f64,
decode_ms: f64,
reused: u64,
}
fn run(engine: &mut engine::GptOssEngine, stops: &[u32], prompt: &[u32], max_new: usize) -> Run {
let ids = prompt
.iter()
.map(u32::to_string)
.collect::<Vec<_>>()
.join(",");
let (tx, rx) = mpsc::channel();
tx.send(format!("GEN {max_new} temperature=0 {ids}\n").into_bytes())
.expect("send");
let out = Shared(Arc::default(), tx);
serve(
engine,
BufReader::new(Input(rx, Cursor::default())),
out.clone(),
stops,
0,
)
.expect("serve");
let text = String::from_utf8(out.0.lock().unwrap().clone()).expect("utf-8");
let mut tokens = Vec::new();
for line in text.lines() {
if let Some(t) = line.strip_prefix("T ") {
tokens.push(t.parse().expect("token id"));
} else if let Some(done) = line.strip_prefix("DONE ") {
let f: Vec<&str> = done.split(' ').collect();
return Run {
tokens,
prompt_ms: f[2].parse().expect("prompt ms"),
decode_ms: f[3].parse().expect("decode ms"),
reused: f[7].parse().expect("reused"),
};
} else if line.starts_with("ERR") {
panic!("worker error: {line}");
}
}
panic!("no DONE line in {text}");
}
/// Deterministic pseudo-source of about `chars` characters.
fn filler(seed: u64, chars: usize) -> String {
const WORDS: [&str; 24] = [
"fn", "let", "mut", "self", "return", "match", "impl", "struct", "Vec", "String", "Result",
"Option", "usize", "for", "in", "if", "else", "pub", "use", "mod", "const", "loop",
"while", "break",
];
let mut state = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;
let mut next = move |n: u64| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state % n
};
let mut out = String::new();
let mut line = 0;
while out.len() < chars {
out.push_str(&format!("{line} "));
for _ in 0..4 + next(6) {
out.push_str(&format!(
"{}{} ",
WORDS[next(WORDS.len() as u64) as usize],
next(99)
));
}
out.push_str(";\n");
line += 1;
}
out
}
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.is_empty() {
eprintln!(
"usage: ab_slots <model.gguf> [agents] [turns] [pairs] [max_new] [threads] [header chars] [tool chars]"
);
std::process::exit(2);
}
let arg =
|i: usize, default: usize| args.get(i).and_then(|s| s.parse().ok()).unwrap_or(default);
let (agents, turns, pairs, max_new) = (arg(1, 3), arg(2, 3), arg(3, 2), arg(4, 24));
let threads = arg(
5,
std::thread::available_parallelism().map_or(1, |n| n.get()),
);
let (header_chars, tool_chars) = (arg(6, 1600), arg(7, 2400));
let model = Path::new(&args[0]);
let size = std::fs::metadata(model).expect("model file").len();
let gguf = Gguf::read(
BufReader::with_capacity(1 << 20, File::open(model).expect("open")),
size,
)
.expect("valid GGUF");
let tokenizer = GgufBpe::from_gguf(&gguf).expect("tokenizer");
let header = format!(
"<|start|>system<|message|>You are ChatGPT, a large language model trained by OpenAI.\nKnowledge cutoff: 2024-06\nCurrent date: 2026-10-17\n\nReasoning: low\n\n# Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions\n\nYou are a coding agent in a Rust repository.\n{}<|end|>",
filler(7, header_chars)
);
// prompts[agent][turn]: each tokenized whole, as the control plane does
let prompts: Vec<Vec<Vec<u32>>> = (0..agents)
.map(|a| {
let mut text = format!(
"{header}<|start|>user<|message|>Task {a}: review module number {} and report what it does.<|end|><|start|>assistant",
a * 7 + 3
);
(0..turns)
.map(|t| {
if t > 0 {
text.push_str(&format!(
"<|channel|>final<|message|>Noted.<|end|><|start|>user<|message|>{}<|end|><|start|>assistant",
filler(100 + (a * 10 + t) as u64, tool_chars)
));
}
tokenizer.encode(&text, true)
})
.collect()
})
.collect();
let sizes: Vec<Vec<usize>> = prompts
.iter()
.map(|p| p.iter().map(Vec::len).collect())
.collect();
let shared = prompts[0][0]
.iter()
.zip(&prompts[agents - 1][0])
.take_while(|(a, b)| a == b)
.count();
println!(
"{agents} agents x {turns} turns, prompt tokens per agent and turn {sizes:?}, shared prefix {shared} tokens, max_new {max_new}, {threads} threads"
);
let longest = prompts.iter().flatten().map(Vec::len).max().unwrap_or(0);
let loaded = engine::load(&LoadOptions {
model,
threads,
context: longest + max_new + 64,
warm: true,
})
.expect("load");
let (mut engine, stops) = (loaded.engine, loaded.stop_tokens);
run(&mut engine, &stops, &prompts[0][0][..64], 1);
let mut reference: Vec<Vec<u32>> = Vec::new();
let mut identical = true;
let mut totals: [Vec<f64>; 2] = [Vec::new(), Vec::new()];
for pair in 0..pairs {
let order = if pair % 2 == 0 {
[1, agents]
} else {
[agents, 1]
};
for slots in order {
engine.set_cache_slots(slots);
engine.reset_cache();
let (mut prompt_ms, mut computed, mut reused_total, mut index) = (0.0, 0u64, 0u64, 0);
for t in 0..turns {
for (a, agent_prompts) in prompts.iter().enumerate() {
let prompt = &agent_prompts[t];
let r = run(&mut engine, &stops, prompt, max_new);
prompt_ms += r.prompt_ms;
reused_total += r.reused;
computed += prompt.len() as u64 - r.reused;
if reference.len() <= index {
reference.push(r.tokens.clone());
}
let same = reference[index] == r.tokens;
identical &= same;
println!(
"pair {pair} {} slot(s) agent {a} turn {t}: {} prompt tokens, {} reused, prompt {:.0} ms, decode {:.0} ms, {} tokens, identical={same}",
slots,
prompt.len(),
r.reused,
r.prompt_ms,
r.decode_ms,
r.tokens.len()
);
index += 1;
}
}
println!(
"pair {pair} {slots} slot(s): prompt time {:.1} s, {computed} tokens computed, {reused_total} reused",
prompt_ms / 1000.0
);
totals[usize::from(slots != 1)].push(prompt_ms / 1000.0);
}
}
let ratios: Vec<f64> = totals[0]
.iter()
.zip(&totals[1])
.map(|(a, b)| a / b)
.collect();
println!(
"total prompt time, 1 slot {:?} s, {agents} slots {:?} s; paired speed-up {:?}; outputs of all runs identical: {identical}",
totals[0].iter().map(|x| x.round()).collect::<Vec<_>>(),
totals[1].iter().map(|x| x.round()).collect::<Vec<_>>(),
ratios
.iter()
.map(|r| (r * 100.0).round() / 100.0)
.collect::<Vec<_>>()
);
}