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>
This commit is contained in:
Pavlo Ratushnyi
2026-10-14 19:14:31 +02:00
co-authored by Claude Sonnet 5.5
parent d661812b09
commit c2a2166fa5
13 changed files with 1463 additions and 11 deletions
Generated
+11
View File
@@ -1021,6 +1021,17 @@ dependencies = [
"cc",
]
[[package]]
name = "leleka-cpu-worker"
version = "0.1.0"
dependencies = [
"leleka-cpu-kernels",
"leleka-cpu-sys",
"leleka-gguf",
"leleka-gptoss",
"leleka-tokenizer",
]
[[package]]
name = "leleka-gguf"
version = "0.1.0"
+2 -2
View File
@@ -1,7 +1,7 @@
[workspace]
resolver = "3"
members = ["crates/backend-api", "crates/cpu-kernels", "crates/cpu-sys", "crates/gguf", "crates/gptoss", "crates/harmony", "crates/tokenizer", "control-plane", "desktop-core"]
default-members = ["crates/backend-api", "crates/cpu-kernels", "crates/cpu-sys", "crates/gguf", "crates/gptoss", "crates/harmony", "crates/tokenizer", "control-plane", "desktop-core"]
members = ["crates/backend-api", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/harmony", "crates/tokenizer", "control-plane", "desktop-core"]
default-members = ["crates/backend-api", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/harmony", "crates/tokenizer", "control-plane", "desktop-core"]
[workspace.package]
edition = "2024"
+21
View File
@@ -0,0 +1,21 @@
[package]
name = "leleka-cpu-worker"
version = "0.1.0"
description = "Leleka CPU (AVX2 / AVX-VNNI) inference worker: serves the control plane's line protocol on stdin/stdout"
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[[bin]]
name = "leleka-cpu-worker"
path = "src/main.rs"
[dependencies]
leleka-cpu-kernels = { path = "../cpu-kernels" }
leleka-cpu-sys = { path = "../cpu-sys" }
leleka-gguf = { path = "../gguf" }
leleka-gptoss = { path = "../gptoss" }
leleka-tokenizer = { path = "../tokenizer" }
[lints]
workspace = true
+115
View File
@@ -0,0 +1,115 @@
//! The real engine: the gpt-oss decoder behind the [`Decoder`] trait.
use crate::serve::Decoder;
use leleka_cpu_kernels::Dispatch;
use leleka_cpu_sys::mapping::Mapping;
use leleka_gguf::Gguf;
use leleka_gptoss::{Model, State};
use leleka_tokenizer::gguf_bpe::GgufBpe;
use std::fs::File;
use std::io::BufReader;
use std::path::Path;
use std::sync::Arc;
use std::time::Instant;
pub struct GptOssEngine {
model: Model,
state: State,
context: usize,
}
/// What loading found out, for the log and the stop tokens.
pub struct Loaded {
pub engine: GptOssEngine,
/// Tokens that end a generation: the end-of-generation markers of the Harmony format.
pub stop_tokens: Vec<u32>,
}
pub struct LoadOptions<'a> {
pub model: &'a Path,
pub threads: usize,
pub context: usize,
/// Read every page of the model file once at startup, so the first requests do not page it in.
pub warm: bool,
}
pub fn load(options: &LoadOptions) -> Result<Loaded, String> {
let size = std::fs::metadata(options.model)
.map_err(|e| format!("cannot read the model file: {e}"))?
.len();
let file = File::open(options.model).map_err(|e| format!("cannot open the model file: {e}"))?;
let gguf = Gguf::read(BufReader::with_capacity(1 << 20, file), size)
.map_err(|e| format!("invalid GGUF: {e}"))?;
let tokenizer = GgufBpe::from_gguf(&gguf).map_err(|e| e.to_string())?;
let mut stop_tokens = Vec::new();
for marker in ["<|return|>", "<|call|>", "<|endoftext|>"] {
if let Some(id) = tokenizer.token_id(marker) {
stop_tokens.push(id);
}
}
if let Some(eos) = tokenizer.eos
&& !stop_tokens.contains(&eos)
{
stop_tokens.push(eos);
}
if stop_tokens.is_empty() {
return Err("the vocabulary has no end-of-generation token".into());
}
let mapping = Mapping::open(options.model).map_err(|e| format!("cannot map the model: {e}"))?;
if options.warm {
let started = Instant::now();
let checksum = mapping.touch_pages();
eprintln!(
"leleka-cpu-worker: read {} bytes of the model in {:.1} s (checksum {checksum})",
mapping.len(),
started.elapsed().as_secs_f64()
);
}
let dispatch = Dispatch::from_env().map_err(|e| format!("kernel level: {e}"))?;
let model = Model::load(Arc::new(mapping), &gguf, dispatch, options.threads)
.map_err(|e| e.to_string())?;
let context = options.context.min(model.config.context_length);
let state = State::new(&model.config, context);
eprintln!(
"leleka-cpu-worker: gpt-oss loaded; kernels {}, {} threads, context {context}, stop tokens {stop_tokens:?}",
dispatch.isa(),
model.threads()
);
Ok(Loaded {
engine: GptOssEngine {
model,
state,
context,
},
stop_tokens,
})
}
impl Decoder for GptOssEngine {
fn max_context(&self) -> usize {
self.context
}
fn prefill(
&mut self,
prompt: &[u32],
progress: &mut dyn FnMut(usize, usize) -> bool,
) -> Result<Option<usize>, String> {
self.model
.prefill_reuse_with(&mut self.state, prompt, progress)
.map(|r| r.map(|r| r.reused))
.map_err(|e| e.to_string())
}
fn logits(&self) -> &[f32] {
&self.state.logits
}
fn advance(&mut self, token: u32) -> Result<(), String> {
let position = self.state.cached_tokens().len();
self.model
.forward(&mut self.state, token, position)
.map(|_| ())
.map_err(|e| e.to_string())
}
}
+6
View File
@@ -0,0 +1,6 @@
//! The Leleka CPU inference worker: a gpt-oss decoder on the AVX2 / AVX-VNNI kernels, served over the
//! control plane's stdin/stdout line protocol.
pub mod engine;
pub mod protocol;
pub mod serve;
+99
View File
@@ -0,0 +1,99 @@
//! `leleka-cpu-worker --serve --model <gpt-oss.gguf> [--threads N] [--ctx N] [--no-warm] [--seed N]`
//!
//! Started by the control plane, which writes requests to its standard input and reads protocol lines
//! from its standard output (see `protocol`). Logs go to standard error.
use leleka_cpu_worker::engine::{self, LoadOptions};
use leleka_cpu_worker::serve::serve;
use std::io::{self, BufReader};
use std::path::PathBuf;
use std::process::ExitCode;
const DEFAULT_CONTEXT: usize = 16_384;
struct Args {
model: PathBuf,
threads: usize,
context: usize,
warm: bool,
seed: u64,
}
fn usage() -> &'static str {
"usage: leleka-cpu-worker --serve --model <gpt-oss.gguf> [--threads N] [--ctx N] [--no-warm] [--seed N]"
}
fn parse_args() -> Result<Args, String> {
let mut args = std::env::args().skip(1);
let mut model = None;
let mut threads = std::thread::available_parallelism().map_or(1, |n| n.get());
let mut context = DEFAULT_CONTEXT;
let mut warm = true;
let mut seed = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0x5EED, |d| d.as_nanos() as u64);
let mut serving = false;
let number = |name: &str, value: Option<String>| -> Result<u64, String> {
value
.and_then(|v| v.parse::<u64>().ok())
.ok_or_else(|| format!("{name} needs a number"))
};
while let Some(arg) = args.next() {
match arg.as_str() {
"--serve" => serving = true,
"--model" => model = Some(PathBuf::from(args.next().ok_or("--model needs a path")?)),
"--threads" => threads = number("--threads", args.next())?.max(1) as usize,
"--ctx" => context = number("--ctx", args.next())?.max(16) as usize,
"--no-warm" => warm = false,
"--seed" => seed = number("--seed", args.next())?,
other => return Err(format!("unknown argument {other}")),
}
}
if !serving {
return Err("only --serve mode exists".into());
}
Ok(Args {
model: model.ok_or("--model is required")?,
threads,
context,
warm,
seed,
})
}
fn main() -> ExitCode {
let args = match parse_args() {
Ok(args) => args,
Err(message) => {
eprintln!("leleka-cpu-worker: {message}\n{}", usage());
return ExitCode::from(2);
}
};
let loaded = match engine::load(&LoadOptions {
model: &args.model,
threads: args.threads,
context: args.context,
warm: args.warm,
}) {
Ok(loaded) => loaded,
Err(message) => {
eprintln!("leleka-cpu-worker: {message}");
return ExitCode::FAILURE;
}
};
let mut engine = loaded.engine;
let stdin = BufReader::new(io::stdin());
match serve(
&mut engine,
stdin,
io::stdout(),
&loaded.stop_tokens,
args.seed,
) {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("leleka-cpu-worker: {e}");
ExitCode::FAILURE
}
}
}
+235
View File
@@ -0,0 +1,235 @@
//! 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");
}
}
+219
View File
@@ -0,0 +1,219 @@
//! The request loop: reads commands, runs generations on a [`Decoder`], writes protocol lines.
use crate::protocol::{self, Command, Finish, Generate};
use leleka_gptoss::sampling::{Rng, sample};
use std::io::{self, BufRead, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::time::Instant;
/// Headroom the control plane keeps between the prompt plus output budget and the context.
const CONTEXT_MARGIN: usize = 8;
/// What the loop needs from an inference engine.
pub trait Decoder {
fn max_context(&self) -> usize;
/// Make the engine hold `prompt` (reusing a cached prefix) so that [`Decoder::logits`] are the
/// logits after its last token. `progress(done, total)` is called as it goes; if it returns `false`
/// the prefill stops and `Ok(None)` is returned. `Ok(Some(n))` reports `n` reused tokens.
fn prefill(
&mut self,
prompt: &[u32],
progress: &mut dyn FnMut(usize, usize) -> bool,
) -> Result<Option<usize>, String>;
/// Logits after the most recent token fed.
fn logits(&self) -> &[f32];
/// Feed one generated token.
fn advance(&mut self, token: u32) -> Result<(), String>;
}
/// Control state shared between the stdin reader thread and the generation loop.
#[derive(Default)]
pub struct Control {
/// A generation is running (a `STOP` while idle is stale and must not hit the next request).
active: AtomicBool,
stop: AtomicBool,
quit: AtomicBool,
}
/// Serve requests from `input` until `QUIT` or end of input. Writes `READY` first.
pub fn serve<D, R, W>(
decoder: &mut D,
input: R,
output: W,
stop_tokens: &[u32],
base_seed: u64,
) -> io::Result<()>
where
D: Decoder,
R: BufRead + Send + 'static,
W: Write,
{
let output = Arc::new(Mutex::new(output));
write_line(&output, &protocol::ready_line(decoder.max_context()))?;
let control = Arc::new(Control::default());
let (commands, requests) = mpsc::channel::<Result<Generate, String>>();
let reader_control = control.clone();
let reader = std::thread::Builder::new()
.name("leleka-stdin".into())
.spawn(move || {
for line in input.lines() {
let Ok(line) = line else { break };
if line.trim().is_empty() {
continue;
}
match protocol::parse_command(&line) {
Ok(Command::Stop) => {
if reader_control.active.load(Ordering::SeqCst) {
reader_control.stop.store(true, Ordering::SeqCst);
}
}
Ok(Command::Quit) => break,
Ok(Command::Generate(g)) => {
if commands.send(Ok(g)).is_err() {
break;
}
}
Err(message) => {
if commands.send(Err(message)).is_err() {
break;
}
}
}
}
// QUIT or end of input: finish nothing new, abandon what runs
reader_control.quit.store(true, Ordering::SeqCst);
reader_control.stop.store(true, Ordering::SeqCst);
drop(commands);
})?;
let mut counter = 0u64;
while let Ok(request) = requests.recv() {
if control.quit.load(Ordering::SeqCst) {
break;
}
match request {
Err(message) => write_line(&output, &protocol::error_line(&message))?,
Ok(request) => {
counter += 1;
let seed = request
.seed
.unwrap_or_else(|| base_seed.wrapping_add(counter.wrapping_mul(0x9E37_79B9)));
control.stop.store(false, Ordering::SeqCst);
control.active.store(true, Ordering::SeqCst);
let outcome = generate(decoder, &request, stop_tokens, seed, &control, &output);
control.active.store(false, Ordering::SeqCst);
match outcome {
Ok(()) => {}
Err(GenerationError::Protocol(e)) => return Err(e),
Err(GenerationError::Engine(message)) => {
write_line(&output, &protocol::error_line(&message))?
}
}
}
}
}
drop(requests);
let _ = reader.join();
Ok(())
}
enum GenerationError {
/// The output pipe failed: nothing more can be reported.
Protocol(io::Error),
/// The request failed; answered with an `ERR` line.
Engine(String),
}
impl From<io::Error> for GenerationError {
fn from(e: io::Error) -> Self {
Self::Protocol(e)
}
}
fn write_line<W: Write>(output: &Mutex<W>, line: &str) -> io::Result<()> {
let mut out = output.lock().expect("output lock");
out.write_all(line.as_bytes())?;
out.flush()
}
fn generate<D: Decoder, W: Write>(
decoder: &mut D,
request: &Generate,
stop_tokens: &[u32],
seed: u64,
control: &Control,
output: &Mutex<W>,
) -> Result<(), GenerationError> {
let budget = request
.prompt
.len()
.saturating_add(request.max_new as usize)
.saturating_add(CONTEXT_MARGIN);
if budget > decoder.max_context() {
return Err(GenerationError::Engine(
"prompt, output budget, and 8-token margin exceed context".into(),
));
}
let started = Instant::now();
let mut write_failed: Option<io::Error> = None;
let reused = decoder
.prefill(&request.prompt, &mut |done, total| {
if let Err(e) = write_line(output, &protocol::progress_line(done, total)) {
write_failed = Some(e);
return false;
}
!control.stop.load(Ordering::SeqCst)
})
.map_err(GenerationError::Engine)?;
if let Some(e) = write_failed {
return Err(e.into());
}
let prompt_ms = started.elapsed().as_secs_f64() * 1000.0;
let prompt_tokens = request.prompt.len() as u64;
let Some(reused) = reused else {
write_line(
output,
&protocol::done_line(0, prompt_tokens, prompt_ms, 0.0, Finish::Cancel, 0),
)?;
return Ok(());
};
write_line(output, &protocol::reused_line(reused))?;
let decode_started = Instant::now();
let mut rng = Rng::new(seed);
let mut generated = 0u64;
let finish = loop {
if control.stop.load(Ordering::SeqCst) {
break Finish::Cancel;
}
let token = sample(
decoder.logits(),
request.temperature,
request.top_p,
&mut rng,
);
write_line(output, &protocol::token_line(token))?;
generated += 1;
if stop_tokens.contains(&token) {
break Finish::Stop;
}
if generated >= u64::from(request.max_new) {
break Finish::Length;
}
decoder.advance(token).map_err(GenerationError::Engine)?;
};
write_line(
output,
&protocol::done_line(
generated,
prompt_tokens,
prompt_ms,
decode_started.elapsed().as_secs_f64() * 1000.0,
finish,
reused as u64,
),
)?;
Ok(())
}
+112
View File
@@ -0,0 +1,112 @@
//! End to end with the real gpt-oss-20b file: spawn the worker, speak the line protocol to it.
//!
//! Needs `LELEKA_GPTOSS_GGUF=<path to gpt-oss-20b-MXFP4.gguf>` (about 12 GB); skipped otherwise.
//! The expected tokens are llama.cpp's greedy continuation of "The capital of France is" (verified
//! against llama.cpp when the decoder was written).
use std::io::{BufRead, BufReader, Write};
use std::process::{Child, ChildStdin, Command, Stdio};
const PROMPT: [u32; 5] = [976, 9029, 328, 10128, 382];
const EXPECTED: [u32; 16] = [
12650, 14396, 271, 1069, 4674, 483, 261, 2893, 130142, 3011, 198, 271, 3100, 314, 12011, 3567,
];
struct Worker {
child: Child,
stdin: ChildStdin,
stdout: BufReader<std::process::ChildStdout>,
}
impl Worker {
fn start(model: &str) -> Self {
let mut child = Command::new(env!("CARGO_BIN_EXE_leleka-cpu-worker"))
.args([
"--serve",
"--model",
model,
"--threads",
"4",
"--ctx",
"512",
"--no-warm",
])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.expect("spawn the worker");
let stdin = child.stdin.take().unwrap();
let mut stdout = BufReader::new(child.stdout.take().unwrap());
let mut line = String::new();
stdout.read_line(&mut line).expect("READY line");
assert_eq!(line.trim_end(), "READY 512 stop");
Self {
child,
stdin,
stdout,
}
}
/// Send one GEN line; return the generated tokens and the DONE line.
fn generate(&mut self, max_new: u32, prompt: &[u32]) -> (Vec<u32>, String, usize) {
let ids: Vec<String> = prompt.iter().map(u32::to_string).collect();
writeln!(self.stdin, "GEN {max_new} {}", ids.join(",")).unwrap();
self.stdin.flush().unwrap();
let (mut tokens, mut reused) = (Vec::new(), 0);
loop {
let mut line = String::new();
assert!(
self.stdout.read_line(&mut line).unwrap() > 0,
"worker exited"
);
let line = line.trim_end().to_owned();
if let Some(t) = line.strip_prefix("T ") {
tokens.push(t.parse().unwrap());
} else if let Some(n) = line.strip_prefix("REUSED ") {
reused = n.parse().unwrap();
} else if line.starts_with("DONE ") {
return (tokens, line, reused);
} else {
assert!(line.starts_with("PP "), "unexpected line {line:?}");
}
}
}
}
impl Drop for Worker {
fn drop(&mut self) {
let _ = writeln!(self.stdin, "QUIT");
let _ = self.stdin.flush();
let _ = self.child.wait();
}
}
#[test]
fn the_worker_continues_a_prompt_like_llama_cpp_and_reuses_the_prefix() {
let Ok(model) = std::env::var("LELEKA_GPTOSS_GGUF") else {
eprintln!("skipped: set LELEKA_GPTOSS_GGUF to the gpt-oss-20b GGUF to run this test");
return;
};
let mut worker = Worker::start(&model);
let (tokens, done, reused) = worker.generate(16, &PROMPT);
assert_eq!(tokens, EXPECTED);
assert_eq!(reused, 0);
let fields: Vec<&str> = done.split_whitespace().collect();
assert_eq!(&fields[1..3], ["16", "5"], "{done}");
assert_eq!(fields[5], "length");
// the prompt plus the first four generated tokens: everything cached is reused, and the
// continuation is exactly what the first request produced
let mut longer = PROMPT.to_vec();
longer.extend_from_slice(&EXPECTED[..4]);
let (tokens, done, reused) = worker.generate(12, &longer);
assert_eq!(reused, longer.len() - 1, "{done}");
assert_eq!(tokens, EXPECTED[4..16]);
// a different prompt shares nothing but still works after the reuse
let (tokens, _, reused) = worker.generate(3, &[976, 9029]);
assert_eq!(tokens.len(), 3);
assert_eq!(reused, 1);
}
+358
View File
@@ -0,0 +1,358 @@
//! 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(mut decoder: Mock) -> 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());
}
+31 -9
View File
@@ -13,6 +13,7 @@
pub mod ops;
pub mod pool;
pub mod sampling;
use leleka_cpu_kernels::Dispatch;
use leleka_gguf::{Gguf, TensorInfo, TensorType};
@@ -461,7 +462,7 @@ pub struct State {
capacity: usize,
k: Vec<Arc<RwLock<Vec<f32>>>>,
v: Vec<Arc<RwLock<Vec<f32>>>>,
/// The tokens whose keys and values are in the cache, at positions ..tokens.len().
/// The tokens whose keys and values are in the cache, at positions `0..tokens.len()`.
tokens: Vec<u32>,
/// Logits of the last forward pass.
pub logits: Vec<f32>,
@@ -699,11 +700,25 @@ impl Model {
Ok(next)
}
/// Run prompt through the model, keeping the cached keys and values of the longest common prefix
/// with what state already holds (the previous prompt and its generated tokens). The last prompt
/// Run `prompt` through the model, keeping the cached keys and values of the longest common prefix
/// with what `state` already holds (the previous prompt and its generated tokens). The last prompt
/// token is always recomputed, because its logits are needed. The result is bit for bit what a fresh
/// state gives for the same prompt.
pub fn prefill_reuse(&self, state: &mut State, prompt: &[u32]) -> Result<Reuse, ModelError> {
Ok(self
.prefill_reuse_with(state, prompt, &mut |_, _| true)?
.expect("the progress callback never cancels"))
}
/// As [`Model::prefill_reuse`], calling `progress(done, total)` after every chunk (`done` counts the
/// reused tokens too). If it returns `false` the prefill stops and `None` is returned; the cache then
/// holds the tokens processed so far.
pub fn prefill_reuse_with(
&self,
state: &mut State,
prompt: &[u32],
progress: &mut dyn FnMut(usize, usize) -> bool,
) -> Result<Option<Reuse>, ModelError> {
if prompt.is_empty() {
return Err(ModelError::Invalid("empty prompt".into()));
}
@@ -715,14 +730,21 @@ impl Model {
.count();
let reused = common.min(prompt.len() - 1);
state.truncate(reused);
let next = self
.prefill(state, &prompt[reused..], reused)?
.expect("a non-empty suffix");
Ok(Reuse {
let mut next = None;
let mut done = reused;
while done < prompt.len() {
let end = (done + self.prefill_chunk).min(prompt.len());
next = self.forward_chunk(state, &prompt[done..end], done, end == prompt.len())?;
done = end;
if !progress(done, prompt.len()) {
return Ok(None);
}
}
Ok(Some(Reuse {
reused,
computed: prompt.len() - reused,
next,
})
next: next.expect("the last chunk produces logits"),
}))
}
/// Tokens per prefill chunk.
+203
View File
@@ -0,0 +1,203 @@
//! Token sampling from logits: greedy, or temperature with nucleus (top-p) filtering.
//!
//! Sampling looks at the 1,024 largest logits only (a partial selection over the vocabulary is far
//! cheaper than a full sort of 201,088 entries per token). With top-p and the usual temperatures the
//! nucleus lies far inside that set; at very high temperature the mass beyond rank 1,024 is ignored.
/// Candidates considered when sampling.
const CANDIDATES: usize = 1024;
/// A small deterministic random generator (SplitMix64); one stream per seed.
#[derive(Clone, Debug)]
pub struct Rng(u64);
impl Rng {
pub fn new(seed: u64) -> Self {
Self(seed)
}
pub fn next_u64(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
/// Uniform in `[0, 1)` with 53 bits.
pub fn next_f64(&mut self) -> f64 {
(self.next_u64() >> 11) as f64 / (1u64 << 53) as f64
}
}
/// The index of the first largest logit.
pub fn argmax(logits: &[f32]) -> u32 {
let mut best = 0usize;
for (i, l) in logits.iter().enumerate() {
if *l > logits[best] {
best = i;
}
}
best as u32
}
/// Choose a token. `temperature <= 0` (or a non-finite one) is greedy; `top_p >= 1` keeps every candidate.
pub fn sample(logits: &[f32], temperature: f64, top_p: f64, rng: &mut Rng) -> u32 {
if !(temperature.is_finite() && temperature > 0.0) || logits.len() <= 1 {
return argmax(logits);
}
// the CANDIDATES largest logits, best first (ties by lower index, like argmax)
let mut best: Vec<(f32, u32)> = if logits.len() > CANDIDATES {
let mut copy: Vec<f32> = logits.to_vec();
let (_, kth, _) = copy.select_nth_unstable_by(CANDIDATES - 1, |a, b| b.total_cmp(a));
let threshold = *kth;
logits
.iter()
.enumerate()
.filter(|(_, l)| **l >= threshold)
.map(|(i, l)| (*l, i as u32))
.collect()
} else {
logits
.iter()
.enumerate()
.map(|(i, l)| (*l, i as u32))
.collect()
};
best.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1)));
best.truncate(CANDIDATES);
let max = best[0].0;
let weights: Vec<f64> = best
.iter()
.map(|(l, _)| ((f64::from(*l) - f64::from(max)) / temperature).exp())
.collect();
let total: f64 = weights.iter().sum();
// nucleus: the smallest prefix whose probability reaches top_p
let mut keep = best.len();
if top_p.is_finite() && top_p < 1.0 {
let target = top_p.max(0.0) * total;
let mut cumulative = 0.0;
for (i, w) in weights.iter().enumerate() {
cumulative += w;
if cumulative >= target {
keep = i + 1;
break;
}
}
}
let kept_total: f64 = weights[..keep].iter().sum();
let mut draw = rng.next_f64() * kept_total;
for (i, w) in weights[..keep].iter().enumerate() {
draw -= w;
if draw < 0.0 {
return best[i].1;
}
}
best[keep - 1].1
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn greedy_cases_return_the_first_maximum() {
let logits = [0.5f32, 2.0, 2.0, -1.0];
assert_eq!(argmax(&logits), 1);
let mut rng = Rng::new(1);
assert_eq!(sample(&logits, 0.0, 1.0, &mut rng), 1);
assert_eq!(sample(&logits, f64::NAN, 1.0, &mut rng), 1);
assert_eq!(sample(&logits, -1.0, 0.5, &mut rng), 1);
assert_eq!(sample(&[3.0], 1.0, 1.0, &mut rng), 0);
}
#[test]
fn the_generator_is_deterministic_and_uniform_enough() {
let (mut a, mut b) = (Rng::new(42), Rng::new(42));
for _ in 0..100 {
assert_eq!(a.next_u64(), b.next_u64());
}
let mut rng = Rng::new(7);
let mut buckets = [0u32; 10];
for _ in 0..100_000 {
let x = rng.next_f64();
assert!((0.0..1.0).contains(&x));
buckets[(x * 10.0) as usize] += 1;
}
for count in buckets {
assert!((9_500..=10_500).contains(&count), "{buckets:?}");
}
}
#[test]
fn sampling_follows_the_softmax_probabilities() {
// probabilities proportional to exp(logit / T): 1 : e : e^2 at T = 1
let logits = [0.0f32, 1.0, 2.0];
let mut rng = Rng::new(3);
let mut counts = [0u32; 3];
let n = 60_000;
for _ in 0..n {
counts[sample(&logits, 1.0, 1.0, &mut rng) as usize] += 1;
}
let z = 1.0 + std::f64::consts::E + std::f64::consts::E.powi(2);
for (i, expected) in [
1.0 / z,
std::f64::consts::E / z,
std::f64::consts::E.powi(2) / z,
]
.into_iter()
.enumerate()
{
let got = f64::from(counts[i]) / f64::from(n);
assert!(
(got - expected).abs() < 0.01,
"token {i}: {got} vs {expected}"
);
}
}
#[test]
fn a_low_temperature_concentrates_on_the_best_token() {
let logits = [0.0f32, 1.0, 2.0];
let mut rng = Rng::new(5);
let hits = (0..2_000)
.filter(|_| sample(&logits, 0.05, 1.0, &mut rng) == 2)
.count();
assert!(hits > 1_990, "{hits}");
}
#[test]
fn top_p_cuts_the_tail_but_keeps_at_least_one_token() {
// probabilities about 0.665, 0.245, 0.090 at T = 1
let logits = [2.0f32, 1.0, 0.0];
let mut rng = Rng::new(9);
for _ in 0..2_000 {
// top_p 0.5 keeps only the best token; 0.8 keeps the first two
assert_eq!(sample(&logits, 1.0, 0.5, &mut rng), 0);
assert_ne!(sample(&logits, 1.0, 0.8, &mut rng), 2);
assert_eq!(sample(&logits, 1.0, 0.0, &mut rng), 0);
}
let seen_second = (0..2_000).any(|_| sample(&logits, 1.0, 0.8, &mut rng) == 1);
assert!(seen_second);
}
#[test]
fn large_vocabularies_use_the_candidate_window() {
let mut logits = vec![-10.0f32; 201_088];
logits[123_456] = 5.0;
logits[7] = 4.9;
let mut rng = Rng::new(11);
let mut counts = std::collections::HashMap::new();
for _ in 0..1_000 {
*counts
.entry(sample(&logits, 1.0, 1.0, &mut rng))
.or_insert(0u32) += 1;
}
// two tokens dominate; anything else is far below one percent
assert!(counts[&123_456] > 400 && counts[&7] > 400, "{counts:?}");
// exact ties beyond the window do not break selection
let tied = vec![1.0f32; 5_000];
let t = sample(&tied, 1.0, 1.0, &mut rng);
assert!((t as usize) < 5_000);
}
}
+51
View File
@@ -0,0 +1,51 @@
# Leleka CPU runtime (AVX2 / AVX-VNNI)
Status on 2026-10-14: runs gpt-oss-20b (MXFP4 GGUF, the lmstudio-community file with SHA-256
`65d06d31a3977d553cb3af137b5c26b5f1e9297a6aaa29ae7caa98788cde53ab`) end to end through the control plane's
worker protocol. Not wired into the control plane's request path yet (see "Not done").
## Crates (a separate runtime; shares only `crates/backend-api` with others)
| Crate | Role |
| --- | --- |
| `leleka-cpu-sys` | The only `unsafe` code of this runtime: SIMD kernels (`std::arch`, AVX2 and AVX-VNNI plus a portable level), read-only file mapping, core topology. Every public function is safe and checks lengths and CPU support. Optional test features: `c-reference` (the first, C implementation, compared bit for bit) and `ggml-oracle` (llama.cpp's quantizers). |
| `leleka-cpu-kernels` | Runtime dispatch by CPUID (`LELEKA_CPU_ISA` overrides and fails rather than silently switching). |
| `leleka-gguf` | Bounded GGUF reader and per-token byte inventory. |
| `leleka-gptoss` | The decoder: persistent thread pool, chunked prefill, prefix reuse, f32 KV cache, sampling. |
| `leleka-tokenizer` | `gguf_bpe`: gpt-oss tokenizer from the GGUF vocabulary. |
| `leleka-harmony` | Prompt rendering and output parsing of the Harmony chat format. |
| `leleka-cpu-worker` | The executable: `leleka-cpu-worker --serve --model <gguf> [--threads N] [--ctx N] [--no-warm] [--seed N]`. |
## Worker protocol
Same lines as Strata's `--serve` mode (`control-plane/src/wire.rs`). The worker prints `READY <ctx> stop`
after loading (and, unless `--no-warm`, reading every page of the model once), then per request:
`PP <done> <total>` after every prefill chunk, `REUSED <n>`, `T <id>` per generated token, and one
`DONE <generated> <prompt_tokens> <prompt_ms> <decode_ms> stop|length|cancel 0 0 <reused> 0 0` (or `ERR`).
Input: `GEN <max_new> [temperature=] [top_p=] [seed=] <ids>`, `STOP`, `QUIT`. The end-of-generation marker
(`<|return|>`, `<|call|>` or `<|endoftext|>`) is emitted as the last `T` so the caller can tell an answer
from a tool call. A `STOP` while no request runs is ignored. Tokenization and Harmony rendering/parsing
belong to the caller (the crates above are the pieces for it).
## What was measured (Core Ultra 7 265U, 15 W, 32 GB class laptop; one noisy machine, no quiet gate for
every number; see the work results on STRA-214 and STRA-217 for the paired runs)
* Decode, 10 threads, warm pages: 85-100 ms per token (10-11.7 tokens/s). Bionic's llama.cpp measured
7.6-8.7 tokens/s on the same prompt on this machine (STRA-209, partial baseline).
* Prefill, 10 threads, chunk 64: about 51 ms per token (19.6 tokens/s) on 256 random-id tokens. Bionic's
iGPU engine measured about 90 tokens/s; its CPU engine about 14.8 tokens/s. Prefix reuse makes the
second and later requests of a conversation cheap.
* Correctness: first 16 greedy tokens equal llama.cpp's for "The capital of France is"; chunked prefill and
prefix reuse are bit-identical to feeding tokens one at a time; kernels at every instruction-set level
are tested against exact integer references and against llama.cpp's quantizers.
## Known limits / not done
* The first-step log-probabilities differ slightly from llama.cpp's (0.4 vs 0.45 for the top token); the
teacher-forced logit comparison that would explain it is still to be done. Greedy tokens agreed on the
prompts tried, but near-ties can flip.
* KV cache is f32 (about 98 KB per token): the default context is 16,384 tokens (1.6 GB). Long contexts
need f16/q8 KV and the RAM planning of STRA-204/205/210. Cold-expert streaming (KAR) is not implemented.
* One request at a time (by decision); sampling is temperature and top-p over the 1,024 best logits.
* The control plane still tokenizes with its Qwen assets and parses Qwen output; pointing it at this worker
needs gpt-oss tokenizer and Harmony handling there. iGPU/NPU helpers for prefill (STRA-207) are a spike.