Files
leleka/control-plane/src/wire.rs
T

309 lines
11 KiB
Rust

//! Typed boundary for the resident Strata `--serve` stdin/stdout protocol.
use leleka_sampler_ref::RequestSampling;
pub use leleka_gateway_domain::EngineTune;
/// 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>,
/// Keeps the request's temporary embeddings file until the request (and its wrap-up passes) is gone.
pub keep: crate::vision::Keep,
/// Reasoning-budget wrap-up, executed by the worker; never sent to the engine.
pub reasoning: Option<ReasoningPlan>,
/// The text `token_ids` was produced from (`encode(text, true)`), when the HTTP layer still has it. A text-level
/// engine is sent this text after a cheap check that the ids decode to it, instead of decoding the ids and
/// tokenizing the result again to prove they round-trip.
pub prompt_text: Option<std::sync::Arc<str>>,
/// The request's log record (`request_log`); empty outside the HTTP generation routes.
pub obs: crate::request_log::ObsHandle,
}
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> {
self.check_inputs()?;
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(' ');
self.push_token_ids(&mut line);
line.push('\n');
Ok(line)
}
/// The prompt must have tokens and a budget, and a GENI embeddings path must be one plain word.
fn check_inputs(&self) -> Result<(), &'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 '='");
}
Ok(())
}
/// The prompt token ids, comma separated.
fn push_token_ids(&self, line: &mut String) {
for (index, id) in self.token_ids.iter().enumerate() {
if index > 0 {
line.push(',');
}
line.push_str(&id.to_string());
}
}
}
// The worker-to-gateway event grammar lives in leleka-worker-protocol, shared with the CPU worker that writes it.
pub use leleka_worker_protocol::{Done, Event, Finish, parse_line};
#[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),
}
}
/// The `Generate` that one case of the golden fixture describes.
fn generate_of_case(case: &serde_json::Value) -> Generate {
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),
});
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),
keep: Default::default(),
reasoning: None,
prompt_text: None,
obs: Default::default(),
}
}
/// 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 request = generate_of_case(case);
assert_eq!(
request.line().unwrap(),
case["line"].as_str().unwrap(),
"case {case}"
);
}
}
fn out_of_contract_base() -> Generate {
Generate {
token_ids: vec![1],
max_new: 1,
..Default::default()
}
}
fn out_of_contract_samplings() -> Vec<RequestSampling> {
vec![
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()
},
]
}
fn out_of_contract_tunes() -> Vec<EngineTune> {
vec![
EngineTune {
pcie_frac: Some(1.5),
spec_min_p: None,
},
EngineTune {
pcie_frac: None,
spec_min_p: Some(f64::NAN),
},
]
}
#[test]
fn out_of_contract_generate_fields_are_refused_before_the_pipe() {
let base = out_of_contract_base();
for bad in out_of_contract_samplings() {
let request = Generate {
sampling: bad,
..base.clone()
};
assert!(request.line().is_err(), "{request:?}");
}
for tune in out_of_contract_tunes() {
let request = Generate {
tune: Some(tune),
..base.clone()
};
assert!(request.line().is_err());
}
for path in [
"", "a b", "a=b", "a
b",
] {
let request = Generate {
embeddings: Some(path.into()),
..base.clone()
};
assert!(request.line().is_err(), "{path:?}");
}
}
}