Files
leleka/crates/cpu-worker/tests/serve_loop.rs
T
Pavlo RatushnyiandClaude Opus 5.5 b0f2b23d4e feat: exact prompt-lookup speculative decoding in the worker loop, cost-aware and off by default (STRA-220)
--speculate on leleka-cpu-worker, leleka-igpu-worker and leleka-npu-worker drafts from
prompt lookup, verifies the sampled token plus the draft in one batch
(Model::logits_after_each, bit-identical to one-at-a-time feeding), samples every
emitted token from the real logits and truncates rejected positions from the cache,
so output equals plain decoding. The drafter estimates acceptance per matched-context
length and drafts only the length whose expected tokens per pass beat the pass cost
(measured ratios, then observed pass times). Drafts are clipped to the output budget.
speculate::replay runs a policy over a recorded output without a model.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 12:11:02 +02:00

478 lines
14 KiB
Rust

//! The request loop against a mock decoder: protocol lines, stop tokens, prefix reuse, STOP and QUIT.
use leleka_cpu_worker::serve::{Decoder, serve};
use std::io::{self, BufReader, Read, Write};
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
const VOCAB: usize = 10;
/// A decoder whose next token is always `last + 1` (mod 10); it keeps the fed tokens like the real one.
struct Mock {
cache: Vec<u32>,
logits: Vec<f32>,
context: usize,
step_delay: Duration,
fail_at: Option<usize>,
}
impl Mock {
fn new() -> Self {
Self {
cache: Vec::new(),
logits: vec![0.0; VOCAB],
context: 64,
step_delay: Duration::ZERO,
fail_at: None,
}
}
fn set_logits(&mut self, last: u32) {
self.logits = vec![0.0; VOCAB];
self.logits[(last as usize + 1) % VOCAB] = 5.0;
}
}
impl Decoder for Mock {
fn max_context(&self) -> usize {
self.context
}
fn prefill(
&mut self,
prompt: &[u32],
progress: &mut dyn FnMut(usize, usize) -> bool,
) -> Result<Option<usize>, String> {
let common = self
.cache
.iter()
.zip(prompt)
.take_while(|(a, b)| a == b)
.count()
.min(prompt.len() - 1);
self.cache.truncate(common);
let mut done = common;
while done < prompt.len() {
let end = (done + 2).min(prompt.len());
self.cache.extend_from_slice(&prompt[done..end]);
done = end;
if !progress(done, prompt.len()) {
return Ok(None);
}
}
self.set_logits(*prompt.last().unwrap());
Ok(Some(common))
}
fn logits(&self) -> &[f32] {
&self.logits
}
fn advance(&mut self, token: u32) -> Result<(), String> {
std::thread::sleep(self.step_delay);
if self.fail_at == Some(self.cache.len()) {
return Err("engine exploded".into());
}
self.cache.push(token);
self.set_logits(token);
Ok(())
}
}
/// A reader fed from a channel, so a test can type lines while the server runs.
struct ChannelReader {
rx: Receiver<Vec<u8>>,
pending: Vec<u8>,
}
impl Read for ChannelReader {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if self.pending.is_empty() {
match self.rx.recv() {
Ok(bytes) => self.pending = bytes,
Err(_) => return Ok(0), // sender dropped: end of input
}
}
let n = buf.len().min(self.pending.len());
buf[..n].copy_from_slice(&self.pending[..n]);
self.pending.drain(..n);
Ok(n)
}
}
#[derive(Clone, Default)]
struct SharedOut(Arc<Mutex<Vec<u8>>>);
impl Write for SharedOut {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl SharedOut {
fn lines(&self) -> Vec<String> {
String::from_utf8(self.0.lock().unwrap().clone())
.unwrap()
.lines()
.map(str::to_owned)
.collect()
}
fn wait_for(&self, what: &str, test: impl Fn(&[String]) -> bool) {
let deadline = Instant::now() + Duration::from_secs(10);
while Instant::now() < deadline {
if test(&self.lines()) {
return;
}
std::thread::sleep(Duration::from_millis(5));
}
panic!(
"timed out waiting for {what}; output so far: {:?}",
self.lines()
);
}
}
struct Session {
out: SharedOut,
tx: Option<Sender<Vec<u8>>>,
handle: Option<std::thread::JoinHandle<io::Result<()>>>,
}
impl Session {
fn start<D: Decoder + Send + 'static>(mut decoder: D) -> Self {
let (tx, rx) = mpsc::channel();
let out = SharedOut::default();
let (writer, stops) = (out.clone(), [9u32]);
let handle = std::thread::spawn(move || {
let input = BufReader::new(ChannelReader {
rx,
pending: Vec::new(),
});
serve(&mut decoder, input, writer, &stops, 1)
});
Self {
out,
tx: Some(tx),
handle: Some(handle),
}
}
fn send(&self, line: &str) {
self.tx
.as_ref()
.unwrap()
.send(format!("{line}\n").into_bytes())
.unwrap();
}
fn finish(mut self) -> Vec<String> {
drop(self.tx.take()); // end of input
self.handle.take().unwrap().join().unwrap().unwrap();
self.out.lines()
}
fn done_count(&self) -> usize {
self.out
.lines()
.iter()
.filter(|l| l.starts_with("DONE "))
.count()
}
}
fn tokens(lines: &[String]) -> Vec<u32> {
lines
.iter()
.filter_map(|l| l.strip_prefix("T "))
.map(|t| t.parse().unwrap())
.collect()
}
#[test]
fn a_generation_streams_tokens_until_the_stop_token() {
let s = Session::start(Mock::new());
s.send("GEN 50 4,5,6");
s.out
.wait_for("DONE", |l| l.iter().any(|x| x.starts_with("DONE")));
let lines = s.finish();
assert_eq!(lines[0], "READY 64 stop");
assert!(lines.contains(&"PP 2 3".to_string()) && lines.contains(&"PP 3 3".to_string()));
assert!(lines.contains(&"REUSED 0".to_string()));
// 7, 8, 9: the stop token is emitted and ends the generation
assert_eq!(tokens(&lines), vec![7, 8, 9]);
let done = lines.last().unwrap();
let fields: Vec<&str> = done.split_whitespace().collect();
assert_eq!(&fields[..2], ["DONE", "3"]); // generated
assert_eq!(fields[2], "3"); // prompt tokens
assert_eq!(fields[5], "stop");
assert_eq!(fields[8], "0"); // reused
}
#[test]
fn the_output_budget_ends_a_generation_with_length() {
let s = Session::start(Mock::new());
s.send("GEN 2 1,2,3 4");
s.send("GEN 2 1,2");
s.out
.wait_for("DONE", |l| l.iter().any(|x| x.starts_with("DONE")));
let lines = s.finish();
assert!(
lines.iter().any(|l| l.starts_with("ERR ")),
"a second token list is refused"
);
assert_eq!(tokens(&lines), vec![3, 4]);
assert!(lines.last().unwrap().contains(" length "));
}
#[test]
fn a_repeated_prefix_is_reused_and_reported() {
let s = Session::start(Mock::new());
s.send("GEN 1 1,2,3,4,5,6");
s.out.wait_for("first DONE", |l| {
l.iter().filter(|x| x.starts_with("DONE")).count() == 1
});
s.send("GEN 1 1,2,3,4,5,6,7,8");
s.out.wait_for("second DONE", |l| {
l.iter().filter(|x| x.starts_with("DONE")).count() == 2
});
let lines = s.finish();
let reused: Vec<&String> = lines.iter().filter(|l| l.starts_with("REUSED")).collect();
assert_eq!(reused, ["REUSED 0", "REUSED 6"]);
let done: Vec<&String> = lines.iter().filter(|l| l.starts_with("DONE")).collect();
assert!(done[1].split_whitespace().nth(8) == Some("6"));
}
#[test]
fn stop_cancels_a_running_generation_and_a_stale_stop_is_ignored() {
let mut mock = Mock::new();
mock.step_delay = Duration::from_millis(15);
mock.context = 100_000;
let s = Session::start(mock);
s.send("GEN 5000 0");
s.out.wait_for("some tokens", |l| {
l.iter().filter(|x| x.starts_with("T ")).count() >= 3
});
s.send("STOP");
s.out.wait_for("DONE after STOP", |l| {
l.iter().any(|x| x.starts_with("DONE"))
});
assert!(s.out.lines().last().unwrap().contains(" cancel "));
// a STOP while idle must not cancel the next request
s.send("STOP");
std::thread::sleep(Duration::from_millis(50));
s.send("GEN 2 1");
s.out.wait_for("second DONE", |l| {
l.iter().filter(|x| x.starts_with("DONE")).count() == 2
});
let lines = s.finish();
assert!(
lines.last().unwrap().contains(" length "),
"{:?}",
lines.last()
);
}
#[test]
fn errors_are_reported_and_the_loop_keeps_serving() {
let mut mock = Mock::new();
mock.context = 20;
let s = Session::start(mock);
s.send("HELLO");
s.send("GEN 30 1,2");
s.send("GEN 1 1,2");
s.out
.wait_for("DONE", |l| l.iter().any(|x| x.starts_with("DONE")));
let lines = s.finish();
let errors: Vec<&String> = lines.iter().filter(|l| l.starts_with("ERR ")).collect();
assert_eq!(errors.len(), 2);
assert!(errors[0].contains("unknown command"));
assert!(errors[1].contains("exceed context"));
assert_eq!(tokens(&lines), vec![3]);
}
#[test]
fn an_engine_failure_becomes_an_err_line_and_the_next_request_still_runs() {
let mut mock = Mock::new();
mock.fail_at = Some(3);
let s = Session::start(mock);
s.send("GEN 5 1,2,3");
s.out
.wait_for("ERR", |l| l.iter().any(|x| x.starts_with("ERR ")));
s.send("GEN 1 5,6");
s.out
.wait_for("DONE", |l| l.iter().any(|x| x.starts_with("DONE")));
let lines = s.finish();
assert!(lines.iter().any(|l| l == "ERR engine exploded"));
assert_eq!(s_done(&lines), 1);
}
fn s_done(lines: &[String]) -> usize {
lines.iter().filter(|l| l.starts_with("DONE ")).count()
}
#[test]
fn quit_ends_the_loop_without_waiting_for_more_input() {
let s = Session::start(Mock::new());
s.send("GEN 1 1,2");
s.out
.wait_for("DONE", |l| l.iter().any(|x| x.starts_with("DONE")));
assert_eq!(s.done_count(), 1);
s.send("QUIT");
// the sender stays open: serve must return on QUIT alone
let handle = s.handle;
let deadline = Instant::now() + Duration::from_secs(10);
let handle = handle.unwrap();
while !handle.is_finished() {
assert!(Instant::now() < deadline, "serve did not return after QUIT");
std::thread::sleep(Duration::from_millis(5));
}
handle.join().unwrap().unwrap();
}
#[test]
fn a_broken_output_pipe_ends_serving_with_an_error() {
struct Broken;
impl Write for Broken {
fn write(&mut self, _: &[u8]) -> io::Result<usize> {
Err(io::Error::new(io::ErrorKind::BrokenPipe, "gone"))
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
let mut mock = Mock::new();
let result = serve(
&mut mock,
BufReader::new(&b"GEN 1 1\n"[..]),
Broken,
&[9],
1,
);
assert!(result.is_err());
}
/// A decoder whose next token is a hash of the last four fed tokens (so repeated three-token contexts can still
/// continue differently), with batch decoding and truncation for speculative decoding.
struct Hashing {
cache: Vec<u32>,
logits: Vec<f32>,
speculate: bool,
batches: Arc<Mutex<(usize, usize)>>, // (advance_many calls, truncate calls)
}
impl Hashing {
fn new(speculate: bool, batches: Arc<Mutex<(usize, usize)>>) -> Self {
Self {
cache: Vec::new(),
logits: vec![0.0; VOCAB],
speculate,
batches,
}
}
fn logits_of(cache: &[u32]) -> Vec<f32> {
let at = |back: usize| cache.len().checked_sub(back).map_or(0, |i| cache[i]);
let next = (at(1) + 2 * at(2) + 3 * at(3) + 5 * at(4)) % 9; // never the stop token 9
// temperature 0.8 samples below; the shape keeps the choice deterministic per context
let mut logits = vec![-50.0; VOCAB];
logits[next as usize] = 3.0;
logits[((next + 4) % 9) as usize] = 2.0;
logits
}
}
impl Decoder for Hashing {
fn max_context(&self) -> usize {
4096
}
fn prefill(
&mut self,
prompt: &[u32],
progress: &mut dyn FnMut(usize, usize) -> bool,
) -> Result<Option<usize>, String> {
self.cache = prompt.to_vec();
self.logits = Self::logits_of(&self.cache);
progress(prompt.len(), prompt.len());
Ok(Some(0))
}
fn logits(&self) -> &[f32] {
&self.logits
}
fn advance(&mut self, token: u32) -> Result<(), String> {
self.cache.push(token);
self.logits = Self::logits_of(&self.cache);
Ok(())
}
fn speculating(&self) -> bool {
self.speculate
}
fn cached_len(&self) -> usize {
self.cache.len()
}
fn advance_many(&mut self, tokens: &[u32]) -> Result<Vec<Vec<f32>>, String> {
self.batches.lock().unwrap().0 += 1;
let mut all = Vec::new();
for token in tokens {
self.cache.push(*token);
all.push(Self::logits_of(&self.cache));
}
self.logits = all.last().unwrap().clone();
Ok(all)
}
fn truncate(&mut self, len: usize) {
self.batches.lock().unwrap().1 += 1;
self.cache.truncate(len);
}
}
fn run_hashing(speculate: bool, request: &str) -> (Vec<u32>, (usize, usize)) {
let counters = Arc::new(Mutex::new((0, 0)));
let s = Session::start(Hashing::new(speculate, counters.clone()));
s.send(request);
s.out
.wait_for("DONE", |l| l.iter().any(|x| x.starts_with("DONE")));
let lines = s.finish();
let counts = *counters.lock().unwrap();
(tokens(&lines), counts)
}
#[test]
fn speculative_decoding_emits_exactly_the_tokens_plain_decoding_does() {
for request in [
"GEN 300 1,2,3,4,5,6,7,8",
"GEN 300 temperature=0.8 seed=7 1,2,3,4,5,6,7,8",
"GEN 300 temperature=1.5 top_p=0.9 seed=99 4,4,4,1,2,3",
] {
let (plain, plain_counts) = run_hashing(false, request);
let (speculative, counts) = run_hashing(true, request);
assert_eq!(plain.len(), 300, "{request}");
assert_eq!(speculative, plain, "{request}");
assert_eq!(plain_counts, (0, 0));
assert!(counts.0 > 0, "no draft was ever verified for {request}");
}
}
#[test]
fn wrong_drafts_are_rolled_back_out_of_the_cache() {
// low-temperature sampling follows the hash, so repeated contexts mostly match, but the second choice is taken
// now and then; the rollback must leave the cache consistent for the run to equal the plain one
let request = "GEN 400 temperature=1.0 seed=3 0,1,2,3,0,1,2,3,0,1,2,3";
let (plain, _) = run_hashing(false, request);
let (speculative, counts) = run_hashing(true, request);
assert_eq!(speculative, plain);
assert!(counts.1 > 0, "no draft was ever rejected: {counts:?}");
}