control-plane serves /props, /slots, /v1/status, /api/health, /settings, /load, /unload, /v1/load, /v1/unload, model aliases, CORS with the preflight ahead of authentication and the own-page guard; replayed scenario by scenario against the real Python handlers. The worker supervisor gains load/unload, lazy start, idle unload, reload gates (before_load, min free VRAM), an outside stall watchdog and the reasoning-budget wrap-up (budget tracker golden-tested against the Python Detokenizer/OutputParser loop). leleka-serving-policy adds CORS, idle, stall watchdog, logits stride (golden vs the C++ header), request timings and alias rules. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
436 lines
15 KiB
Rust
436 lines
15 KiB
Rust
//! Typed boundary for the resident Strata `--serve` stdin/stdout protocol.
|
|
|
|
use leleka_sampler_ref::RequestSampling;
|
|
|
|
/// Per-request engine tuning (`strata_tune` in the Python server): the PCIe share of
|
|
/// missed experts and the draft-probability floor, both in `0..=1`.
|
|
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
|
pub struct EngineTune {
|
|
pub pcie_frac: Option<f64>,
|
|
pub spec_min_p: Option<f64>,
|
|
}
|
|
|
|
/// Reasoning-budget wrap-up (`reasoning_budget_tokens`, issue #123 of the Original): once the model
|
|
/// has thought for `budget` tokens, at a clean point the worker stops the pass, appends `wrap_up`
|
|
/// to the output and continues from `prompt + generated + wrap_up` so the engine keeps its prefix.
|
|
#[derive(Clone)]
|
|
pub struct ReasoningPlan {
|
|
pub budget: u64,
|
|
/// Token ids of `REASONING_WRAP_UP`.
|
|
pub wrap_up: Vec<u32>,
|
|
/// End-of-turn ids: they end the generation and are never counted as thinking.
|
|
pub stop_ids: Vec<u32>,
|
|
/// The bytes one token decodes to.
|
|
pub token_bytes: std::sync::Arc<dyn Fn(u32) -> Vec<u8> + Send + Sync>,
|
|
}
|
|
|
|
impl std::fmt::Debug for ReasoningPlan {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
f.debug_struct("ReasoningPlan")
|
|
.field("budget", &self.budget)
|
|
.field("wrap_up", &self.wrap_up)
|
|
.finish_non_exhaustive()
|
|
}
|
|
}
|
|
|
|
impl PartialEq for ReasoningPlan {
|
|
fn eq(&self, other: &Self) -> bool {
|
|
self.budget == other.budget
|
|
&& self.wrap_up == other.wrap_up
|
|
&& self.stop_ids == other.stop_ids
|
|
}
|
|
}
|
|
|
|
/// One `GEN` / `GENI` request. Every sampling key the Original's `--serve` loop
|
|
/// accepts is carried: `temperature`, `top_p`, `top_k`, `min_p`, the three penalties
|
|
/// with `penalty_last_n`, and `seed` (through [`RequestSampling::gen_keys`], which is
|
|
/// golden-tested against `StrataEngine.sampling_keys`), plus `strata_tune`
|
|
/// (`pcie_frac`, `spec_min_p`) and the per-request control-vector switch `cvec`.
|
|
#[derive(Debug, Clone, Default, PartialEq)]
|
|
pub struct Generate {
|
|
pub token_ids: Vec<u32>,
|
|
pub max_new: u32,
|
|
pub sampling: RequestSampling,
|
|
pub tune: Option<EngineTune>,
|
|
/// `experimental_speed_projection`: `Some(b)` emits `cvec=0|1`, `None` leaves the
|
|
/// engine default (on when a vector is loaded).
|
|
pub cvec: Option<bool>,
|
|
/// `GENI`: path of the SVE1 image-embeddings file for this request.
|
|
pub embeddings: Option<String>,
|
|
/// Reasoning-budget wrap-up, executed by the worker; never sent to the engine.
|
|
pub reasoning: Option<ReasoningPlan>,
|
|
}
|
|
|
|
impl Generate {
|
|
/// The tuning and projection keys after the sampling keys, in the Python order.
|
|
fn engine_keys(&self) -> Result<String, &'static str> {
|
|
let mut keys = String::new();
|
|
if let Some(tune) = &self.tune {
|
|
for (name, value) in [
|
|
("pcie_frac", tune.pcie_frac),
|
|
("spec_min_p", tune.spec_min_p),
|
|
] {
|
|
if let Some(value) = value {
|
|
if !value.is_finite() || !(0.0..=1.0).contains(&value) {
|
|
return Err("strata_tune values must be finite and between 0 and 1");
|
|
}
|
|
keys.push_str(&format!(
|
|
" {name}={}",
|
|
leleka_sampler_ref::params::py_float_repr(value)
|
|
));
|
|
}
|
|
}
|
|
}
|
|
if let Some(on) = self.cvec {
|
|
keys.push_str(&format!(" cvec={}", u8::from(on)));
|
|
}
|
|
Ok(keys)
|
|
}
|
|
|
|
pub fn line(&self) -> Result<String, &'static str> {
|
|
if self.token_ids.is_empty() || self.max_new == 0 {
|
|
return Err("GEN needs prompt tokens and a positive max_new");
|
|
}
|
|
// The engine reads the first whitespace-delimited token without `=` as the path.
|
|
if self.embeddings.as_ref().is_some_and(|path| {
|
|
path.is_empty() || path.contains(|c: char| c.is_whitespace() || c == '=')
|
|
}) {
|
|
return Err("GENI embeddings path must be nonempty, without whitespace or '='");
|
|
}
|
|
let keys = self
|
|
.sampling
|
|
.gen_keys()
|
|
.map_err(|_| "sampling parameters are out of range")?;
|
|
let mut line = match &self.embeddings {
|
|
Some(_) => format!("GENI {}", self.max_new),
|
|
None => format!("GEN {}", self.max_new),
|
|
};
|
|
line.push_str(&keys);
|
|
line.push_str(&self.engine_keys()?);
|
|
if let Some(path) = &self.embeddings {
|
|
line.push(' ');
|
|
line.push_str(path);
|
|
}
|
|
line.push(' ');
|
|
for (index, id) in self.token_ids.iter().enumerate() {
|
|
if index > 0 {
|
|
line.push(',');
|
|
}
|
|
line.push_str(&id.to_string());
|
|
}
|
|
line.push('\n');
|
|
Ok(line)
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub enum Event {
|
|
Token(u32),
|
|
PromptProgress { read: u64, total: u64 },
|
|
Done(Done),
|
|
Error(String),
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct Done {
|
|
pub generated: u64,
|
|
pub prompt_tokens: u64,
|
|
pub prompt_ms: f64,
|
|
pub decode_ms: f64,
|
|
pub finish: Finish,
|
|
pub drafts_accepted: Option<u64>,
|
|
pub drafts_offered: Option<u64>,
|
|
pub reused: Option<u64>,
|
|
pub expert_hits: Option<u64>,
|
|
pub expert_lookups: Option<u64>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum Finish {
|
|
Stop,
|
|
Length,
|
|
Cancel,
|
|
}
|
|
|
|
pub fn parse_line(line: &str) -> Result<Option<Event>, String> {
|
|
let line = line.trim_end_matches(['\r', '\n']);
|
|
let Some((tag, rest)) = line.split_once(' ') else {
|
|
return Err(format!("invalid engine line: {line}"));
|
|
};
|
|
match tag {
|
|
"T" => Ok(Some(Event::Token(
|
|
rest.parse().map_err(|_| "invalid T token id")?,
|
|
))),
|
|
"PP" => {
|
|
let fields: Vec<_> = rest.split_whitespace().collect();
|
|
if fields.len() < 2 {
|
|
return Err("invalid PP progress line".to_owned());
|
|
}
|
|
let read: u64 = fields[0].parse().map_err(|_| "invalid PP read count")?;
|
|
let total: u64 = fields[1].parse().map_err(|_| "invalid PP total count")?;
|
|
if read > total {
|
|
return Err("PP read count exceeds total".to_owned());
|
|
}
|
|
Ok(Some(Event::PromptProgress { read, total }))
|
|
}
|
|
"DONE" => Ok(Some(Event::Done(parse_done(rest)?))),
|
|
"ERR" => Ok(Some(Event::Error(rest.to_owned()))),
|
|
// Upstream announces prefix reuse both before and after prefill.
|
|
// Final usage is reported by DONE; these are nonterminal metadata.
|
|
"RESUME" | "REUSED" => {
|
|
rest.parse::<u64>()
|
|
.map_err(|_| format!("invalid {tag} prefix count"))?;
|
|
Ok(None)
|
|
}
|
|
"INFO" => Ok(None),
|
|
_ => Err(format!("unknown engine line tag: {tag}")),
|
|
}
|
|
}
|
|
|
|
fn parse_done(rest: &str) -> Result<Done, String> {
|
|
let fields: Vec<_> = rest.split_whitespace().collect();
|
|
if fields.len() < 5 {
|
|
return Err("DONE needs generated, prompt, timings, and finish".to_owned());
|
|
}
|
|
let count = |index: usize| -> Result<u64, String> {
|
|
fields[index]
|
|
.parse()
|
|
.map_err(|_| format!("invalid DONE count at field {index}"))
|
|
};
|
|
let timing = |index: usize| -> Result<f64, String> {
|
|
let value: f64 = fields[index]
|
|
.parse()
|
|
.map_err(|_| format!("invalid DONE timing at field {index}"))?;
|
|
if !value.is_finite() || value < 0.0 {
|
|
return Err(format!("invalid DONE timing at field {index}"));
|
|
}
|
|
Ok(value)
|
|
};
|
|
let optional_count = |index: usize| -> Result<Option<u64>, String> {
|
|
if fields.len() > index {
|
|
count(index).map(Some)
|
|
} else {
|
|
Ok(None)
|
|
}
|
|
};
|
|
let finish = match fields[4] {
|
|
"stop" => Finish::Stop,
|
|
"length" => Finish::Length,
|
|
"cancel" => Finish::Cancel,
|
|
other => return Err(format!("unknown DONE finish: {other}")),
|
|
};
|
|
let done = Done {
|
|
generated: count(0)?,
|
|
prompt_tokens: count(1)?,
|
|
prompt_ms: timing(2)?,
|
|
decode_ms: timing(3)?,
|
|
finish,
|
|
drafts_accepted: optional_count(5)?,
|
|
drafts_offered: optional_count(6)?,
|
|
reused: optional_count(7)?,
|
|
expert_hits: optional_count(8)?,
|
|
expert_lookups: optional_count(9)?,
|
|
};
|
|
if done
|
|
.drafts_accepted
|
|
.zip(done.drafts_offered)
|
|
.is_some_and(|(a, b)| a > b)
|
|
|| done
|
|
.reused
|
|
.is_some_and(|reused| reused > done.prompt_tokens)
|
|
{
|
|
return Err("inconsistent DONE counters".to_owned());
|
|
}
|
|
Ok(done)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn gen_line_uses_upstream_sampling_spelling() {
|
|
let request = Generate {
|
|
token_ids: vec![101, 42, 7],
|
|
max_new: 256,
|
|
sampling: RequestSampling {
|
|
temperature: Some(0.7),
|
|
top_p: Some(0.9),
|
|
..Default::default()
|
|
},
|
|
..Default::default()
|
|
};
|
|
assert_eq!(
|
|
request.line().unwrap(),
|
|
"GEN 256 temperature=0.7 top_p=0.9 101,42,7\n"
|
|
);
|
|
assert!(
|
|
Generate {
|
|
token_ids: vec![],
|
|
..request
|
|
}
|
|
.line()
|
|
.is_err()
|
|
);
|
|
}
|
|
|
|
fn sampling_of(v: &serde_json::Value) -> RequestSampling {
|
|
let f = |k: &str| v.get(k).and_then(serde_json::Value::as_f64);
|
|
let i = |k: &str| v.get(k).and_then(serde_json::Value::as_i64);
|
|
RequestSampling {
|
|
temperature: f("temperature"),
|
|
top_p: f("top_p"),
|
|
top_k: i("top_k"),
|
|
min_p: f("min_p"),
|
|
repetition_penalty: f("repetition_penalty"),
|
|
frequency_penalty: f("frequency_penalty"),
|
|
presence_penalty: f("presence_penalty"),
|
|
penalty_last_n: i("penalty_last_n"),
|
|
seed: v.get("seed").and_then(serde_json::Value::as_u64),
|
|
}
|
|
}
|
|
|
|
/// Every GEN/GENI line equals what the Original's `StrataEngine.generate` writes to the pipe
|
|
/// (fixture from `tests/golden/gen_goldens.py`, which runs that real code with a fake pipe).
|
|
#[test]
|
|
fn gen_lines_equal_the_python_servers_for_every_sampling_key() {
|
|
let fixture: serde_json::Value =
|
|
serde_json::from_str(include_str!("../tests/fixtures/golden/gen_lines.json")).unwrap();
|
|
let cases = fixture["cases"].as_array().unwrap();
|
|
assert!(cases.len() >= 60);
|
|
for case in cases {
|
|
let sampling = &case["sampling"];
|
|
let tune = sampling.get("strata_tune").map(|t| EngineTune {
|
|
pcie_frac: t.get("pcie_frac").and_then(serde_json::Value::as_f64),
|
|
spec_min_p: t.get("spec_min_p").and_then(serde_json::Value::as_f64),
|
|
});
|
|
let request = Generate {
|
|
token_ids: case["token_ids"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.map(|v| v.as_u64().unwrap() as u32)
|
|
.collect(),
|
|
max_new: case["max_new"].as_u64().unwrap() as u32,
|
|
sampling: sampling_of(sampling),
|
|
tune,
|
|
cvec: sampling
|
|
.get("experimental_speed_projection")
|
|
.and_then(serde_json::Value::as_bool),
|
|
embeddings: case["embeddings"].as_str().map(str::to_owned),
|
|
reasoning: None,
|
|
};
|
|
assert_eq!(
|
|
request.line().unwrap(),
|
|
case["line"].as_str().unwrap(),
|
|
"case {case}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn out_of_contract_generate_fields_are_refused_before_the_pipe() {
|
|
let base = Generate {
|
|
token_ids: vec![1],
|
|
max_new: 1,
|
|
..Default::default()
|
|
};
|
|
for bad in [
|
|
RequestSampling {
|
|
temperature: Some(2.5),
|
|
..Default::default()
|
|
},
|
|
RequestSampling {
|
|
top_p: Some(1.5),
|
|
..Default::default()
|
|
},
|
|
RequestSampling {
|
|
top_k: Some(-1),
|
|
..Default::default()
|
|
},
|
|
RequestSampling {
|
|
repetition_penalty: Some(0.0),
|
|
..Default::default()
|
|
},
|
|
RequestSampling {
|
|
presence_penalty: Some(f64::NAN),
|
|
..Default::default()
|
|
},
|
|
] {
|
|
let request = Generate {
|
|
sampling: bad,
|
|
..base.clone()
|
|
};
|
|
assert!(request.line().is_err(), "{request:?}");
|
|
}
|
|
for tune in [
|
|
EngineTune {
|
|
pcie_frac: Some(1.5),
|
|
spec_min_p: None,
|
|
},
|
|
EngineTune {
|
|
pcie_frac: None,
|
|
spec_min_p: Some(f64::NAN),
|
|
},
|
|
] {
|
|
let request = Generate {
|
|
tune: Some(tune),
|
|
..base.clone()
|
|
};
|
|
assert!(request.line().is_err());
|
|
}
|
|
for path in ["", "a b", "a=b", "a\nb"] {
|
|
let request = Generate {
|
|
embeddings: Some(path.into()),
|
|
..base.clone()
|
|
};
|
|
assert!(request.line().is_err(), "{path:?}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn parses_current_and_older_done_lines() {
|
|
let current = parse_line("DONE 12 300 45.1 88.2 stop 7 10 240 90 100 2 0 0.0\n")
|
|
.unwrap()
|
|
.unwrap();
|
|
let Event::Done(done) = current else {
|
|
panic!("expected DONE")
|
|
};
|
|
assert_eq!(done.finish, Finish::Stop);
|
|
assert_eq!(done.drafts_accepted, Some(7));
|
|
assert_eq!(done.reused, Some(240));
|
|
assert_eq!(done.expert_hits, Some(90));
|
|
assert_eq!(done.expert_lookups, Some(100));
|
|
let Event::Done(older) = parse_line("DONE 2 4 1.0 3.0 length\n").unwrap().unwrap() else {
|
|
panic!("expected DONE")
|
|
};
|
|
assert_eq!(older.reused, None);
|
|
assert_eq!(older.finish, Finish::Length);
|
|
}
|
|
|
|
#[test]
|
|
fn parses_tokens_progress_and_errors_without_losing_terminal_state() {
|
|
assert_eq!(parse_line("T 123\n").unwrap(), Some(Event::Token(123)));
|
|
assert_eq!(
|
|
parse_line("PP 64 128 10 5.0\n").unwrap(),
|
|
Some(Event::PromptProgress {
|
|
read: 64,
|
|
total: 128
|
|
})
|
|
);
|
|
assert_eq!(
|
|
parse_line("ERR bad request\n").unwrap(),
|
|
Some(Event::Error("bad request".into()))
|
|
);
|
|
assert_eq!(parse_line("INFO engine=0.1.8\n").unwrap(), None);
|
|
assert_eq!(parse_line("RESUME 0\n").unwrap(), None);
|
|
assert_eq!(parse_line("REUSED 262144\n").unwrap(), None);
|
|
assert!(parse_line("RESUME -1").is_err());
|
|
assert!(parse_line("REUSED 1 2").is_err());
|
|
assert!(parse_line("REUSED 18446744073709551616").is_err());
|
|
assert!(parse_line("UNKNOWN 0").is_err());
|
|
assert!(parse_line("DONE 1 2 NaN 3 stop").is_err());
|
|
assert!(parse_line("PP 129 128").is_err());
|
|
}
|
|
}
|