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:
co-authored by
Claude Sonnet 5.5
parent
d661812b09
commit
c2a2166fa5
Generated
+11
@@ -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
@@ -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"
|
||||
|
||||
@@ -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
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
@@ -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 | ||||