Files
leleka/crates/cpu-worker/src/protocol.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 c2a2166fa5 feat: add the CPU worker that serves gpt-oss-20b over the control plane's line protocol (STRA-199, STRA-217)
New crate leleka-cpu-worker (executable leleka-cpu-worker --serve --model <gguf>): loads the GGUF through
the read-only mapping, runs the gpt-oss decoder on the AVX2 / AVX-VNNI kernels, and speaks the stdin/stdout
protocol of Strata's --serve mode (READY, GEN with temperature, top_p and seed, STOP, QUIT, PP, REUSED, T,
DONE, ERR). Prefix reuse across requests, cancellation between prefill chunks and between tokens, a stale
STOP while idle is ignored, the end-of-generation marker is emitted as the last token.

leleka-gptoss gains sampling (greedy, or temperature and top-p over the 1,024 best logits, with a seeded
generator) and prefill_reuse_with (progress and cancellation). A stray NUL byte left in a doc comment by an
earlier shell edit is removed.

Tests: protocol parsing, the request loop against a mock decoder (stop token, length, reuse, STOP, QUIT,
engine failure, broken pipe), and an end-to-end run on the real model (needs LELEKA_GPTOSS_GGUF) that gets
llama.cpp's 16 greedy tokens for "The capital of France is" and reuses the prefix of a longer prompt.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 19:14:31 +02:00

236 lines
6.9 KiB
Rust

//! The line protocol the control plane speaks to an inference worker (the format of Strata's
//! `--serve` mode, see `control-plane/src/wire.rs`).
//!
//! Input lines: `GEN <max_new> [temperature=<f>] [top_p=<f>] [seed=<n>] <id>,<id>,...`, `STOP` (abandon
//! the running generation), `QUIT`. Output lines: `READY <max_context> stop` once, then per request any
//! number of `PP <read> <total>`, `REUSED <n>`, `T <id>`, and exactly one `DONE ...` or `ERR <message>`.
use std::fmt::Write as _;
#[derive(Clone, Debug, PartialEq)]
pub struct Generate {
pub max_new: u32,
pub temperature: f64,
pub top_p: f64,
pub seed: Option<u64>,
pub prompt: Vec<u32>,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Command {
Generate(Generate),
Stop,
Quit,
}
/// Parse one input line. Errors are the text of the `ERR` line to answer with.
pub fn parse_command(line: &str) -> Result<Command, String> {
let line = line.trim_end_matches(['\r', '\n']).trim();
match line {
"STOP" => return Ok(Command::Stop),
"QUIT" => return Ok(Command::Quit),
_ => {}
}
let mut fields = line.split_whitespace();
if fields.next() != Some("GEN") {
return Err(format!("unknown command: {line}"));
}
let max_new: u32 = fields
.next()
.and_then(|f| f.parse().ok())
.filter(|n| *n > 0)
.ok_or("GEN needs a positive max_new")?;
let mut temperature = 0.0;
let mut top_p = 1.0;
let mut seed = None;
let mut ids = None;
for field in fields {
if let Some((key, value)) = field.split_once('=') {
let number = || {
value
.parse::<f64>()
.ok()
.filter(|v| v.is_finite())
.ok_or_else(|| format!("invalid {key} value"))
};
match key {
"temperature" => {
temperature = number()?;
if !(0.0..=2.0).contains(&temperature) {
return Err("temperature must be between 0 and 2".into());
}
}
"top_p" => {
top_p = number()?;
if !(0.0..=1.0).contains(&top_p) {
return Err("top_p must be between 0 and 1".into());
}
}
"seed" => {
seed = Some(
value
.parse::<u64>()
.map_err(|_| "invalid seed value".to_owned())?,
);
}
other => return Err(format!("unknown GEN option: {other}")),
}
} else if ids.is_none() {
ids = Some(field);
} else {
return Err("GEN has more than one token list".into());
}
}
let ids = ids.ok_or("GEN needs prompt tokens")?;
let prompt = ids
.split(',')
.map(|id| {
id.parse::<u32>()
.map_err(|_| format!("invalid token id: {id}"))
})
.collect::<Result<Vec<_>, _>>()?;
if prompt.is_empty() {
return Err("GEN needs prompt tokens".into());
}
Ok(Command::Generate(Generate {
max_new,
temperature,
top_p,
seed,
prompt,
}))
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Finish {
Stop,
Length,
Cancel,
}
impl Finish {
fn word(self) -> &'static str {
match self {
Self::Stop => "stop",
Self::Length => "length",
Self::Cancel => "cancel",
}
}
}
pub fn ready_line(max_context: usize) -> String {
format!("READY {max_context} stop\n")
}
pub fn token_line(id: u32) -> String {
format!("T {id}\n")
}
pub fn progress_line(read: usize, total: usize) -> String {
format!("PP {read} {total}\n")
}
pub fn reused_line(reused: usize) -> String {
format!("REUSED {reused}\n")
}
/// An error line; newlines in the message would break the protocol, so they are flattened.
pub fn error_line(message: &str) -> String {
format!("ERR {}\n", message.replace(['\r', '\n'], " "))
}
/// The terminal line of a request. The draft and expert counters are zero: this worker has neither.
pub fn done_line(
generated: u64,
prompt_tokens: u64,
prompt_ms: f64,
decode_ms: f64,
finish: Finish,
reused: u64,
) -> String {
let mut line = String::new();
write!(
line,
"DONE {generated} {prompt_tokens} {prompt_ms:.1} {decode_ms:.1} {} 0 0 {reused} 0 0",
finish.word()
)
.expect("writing to a String");
line.push('\n');
line
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gen_lines_parse_in_the_format_the_control_plane_writes() {
assert_eq!(
parse_command("GEN 256 temperature=0.7 top_p=0.9 101,42,7\n"),
Ok(Command::Generate(Generate {
max_new: 256,
temperature: 0.7,
top_p: 0.9,
seed: None,
prompt: vec![101, 42, 7]
}))
);
assert_eq!(
parse_command("GEN 1 5\r\n"),
Ok(Command::Generate(Generate {
max_new: 1,
temperature: 0.0,
top_p: 1.0,
seed: None,
prompt: vec![5]
}))
);
let Ok(Command::Generate(g)) = parse_command("GEN 4 seed=77 temperature=1 1,2") else {
panic!("seed option");
};
assert_eq!(g.seed, Some(77));
}
#[test]
fn bad_commands_are_answered_with_a_reason() {
for bad in [
"",
"HELLO",
"GEN",
"GEN 0 1,2",
"GEN x 1,2",
"GEN 5",
"GEN 5 1,x",
"GEN 5 1,2 3,4",
"GEN 5 temperature=3 1",
"GEN 5 temperature=nan 1",
"GEN 5 top_p=1.5 1",
"GEN 5 seed=-1 1",
"GEN 5 colour=red 1",
"GEN 5 ,",
] {
assert!(parse_command(bad).is_err(), "{bad:?}");
}
}
#[test]
fn stop_and_quit_are_recognized() {
assert_eq!(parse_command("STOP\n"), Ok(Command::Stop));
assert_eq!(parse_command("QUIT"), Ok(Command::Quit));
}
#[test]
fn output_lines_have_the_shape_the_control_plane_parses() {
assert_eq!(ready_line(16384), "READY 16384 stop\n");
assert_eq!(token_line(42), "T 42\n");
assert_eq!(progress_line(64, 4096), "PP 64 4096\n");
assert_eq!(error_line("bad\nthing"), "ERR bad thing\n");
let done = done_line(12, 300, 45.12, 88.26, Finish::Stop, 200);
assert_eq!(done, "DONE 12 300 45.1 88.3 stop 0 0 200 0 0\n");
// at least five fields; reused is the field the control plane reads at index 7
let fields: Vec<&str> = done.split_whitespace().skip(1).collect();
assert_eq!(fields.len(), 10);
assert_eq!(fields[7], "200");
}
}