Files
leleka/control-plane/src/sampling.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 cce433339d feat(serving): forward all Original GEN sampling fields end to end
control-plane wire.rs builds GEN/GENI lines through RequestSampling::gen_keys plus
strata_tune and the per-request cvec switch (golden-tested against the real
StrataEngine.generate); Responses, Chat Completions and Messages accept and validate
top_k, min_p, repetition/frequency/presence penalties, penalty_last_n, seed and the
engine knobs with the Original's defaults and ranges; server-wide defaults (config
sampling block plus POST /settings shared values) merge under the request. The desktop
runtime gRPC contract carries the full sampling set and the gateway no longer refuses
temperature != 0. New crate leleka-serving-policy holds the pure Original policies
(shared settings, reasoning budget tracker, fixed-point sampling conversion) with
fixtures generated by running the Python handlers.

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

217 lines
6.9 KiB
Rust

//! Request sampling plumbing shared by the Responses, Chat Completions and Messages routes.
//!
//! The Original's Python server takes every sampling field from the top level of the request body
//! (`StrataEngine.sampling_keys`): `temperature`, `top_p`, `top_k`, `min_p`, `repetition_penalty`,
//! `frequency_penalty`, `presence_penalty`, `penalty_last_n`, `seed`, plus the engine knobs
//! `strata_tune` and `experimental_speed_projection`, and `reasoning_budget_tokens`. This module
//! validates them against the Original's defaults and ranges (`leleka-sampler-ref`) and turns them
//! into the `GEN` request. Chat and Messages forward those keys verbatim into the native Responses
//! request, so one type validates everything.
use leleka_sampler_ref::RequestSampling;
use serde::Deserialize;
use serde_json::{Map, Value};
use crate::wire::EngineTune;
/// Top-level body keys that the Chat and Messages adapters pass through to the native request
/// unchanged. Removed before their own `deny_unknown_fields` parse.
pub const EXTENSION_KEYS: [&str; 10] = [
"top_k",
"min_p",
"repetition_penalty",
"frequency_penalty",
"presence_penalty",
"penalty_last_n",
"seed",
"strata_tune",
"experimental_speed_projection",
"reasoning_budget_tokens",
];
/// Split an adapter request body into `(rest, extensions)`.
pub fn split_extensions(mut body: Value) -> (Value, Map<String, Value>) {
let mut extensions = Map::new();
if let Some(object) = body.as_object_mut() {
for key in EXTENSION_KEYS {
if let Some(value) = object.remove(key) {
extensions.insert(key.to_owned(), value);
}
}
}
(body, extensions)
}
/// `strata_tune`: engine settings for this request only (setup's calibration).
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Tune {
pub pcie_frac: Option<f64>,
pub spec_min_p: Option<f64>,
}
impl From<Tune> for EngineTune {
fn from(tune: Tune) -> Self {
Self {
pcie_frac: tune.pcie_frac,
spec_min_p: tune.spec_min_p,
}
}
}
pub fn validate_tune(tune: &Tune) -> Result<(), (&'static str, &'static str)> {
for (name, value) in [
("pcie_frac", tune.pcie_frac),
("spec_min_p", tune.spec_min_p),
] {
if value.is_some_and(|v| !v.is_finite() || !(0.0..=1.0).contains(&v)) {
return Err((
"strata_tune",
if name == "pcie_frac" {
"strata_tune.pcie_frac must be between 0 and 1"
} else {
"strata_tune.spec_min_p must be between 0 and 1"
},
));
}
}
Ok(())
}
/// Validate request sampling against the Original's contract; the message is static so it can
/// travel in the Responses `(param, message)` error pair.
pub fn validate(sampling: &RequestSampling) -> Result<(), (&'static str, &'static str)> {
sampling.validate().map_err(|error| match error.field {
"temperature" => ("temperature", "temperature must be between 0 and 2"),
"top_p" => ("top_p", "top_p must be between 0 and 1"),
"min_p" => ("min_p", "min_p must be between 0 and 1"),
"top_k" => (
"top_k",
"top_k must be an integer >= 0 (0 or above 64 use 64)",
),
"repetition_penalty" => (
"repetition_penalty",
"repetition_penalty must be greater than 0 (1 is off)",
),
"frequency_penalty" => (
"frequency_penalty",
"frequency_penalty must be between -2 and 2",
),
"presence_penalty" => (
"presence_penalty",
"presence_penalty must be between -2 and 2",
),
"penalty_last_n" => (
"penalty_last_n",
"penalty_last_n must be an integer between 0 and 2147483647",
),
_ => ("sampling", "sampling parameters are out of range"),
})
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn extensions_are_split_out_of_adapter_bodies() {
let (rest, extensions) = split_extensions(json!({
"model": "m", "temperature": 0.5, "top_k": 40, "seed": 3, "min_p": null,
"strata_tune": {"pcie_frac": 0.1}
}));
assert_eq!(rest, json!({"model": "m", "temperature": 0.5}));
assert_eq!(extensions.len(), 4);
assert_eq!(extensions["top_k"], 40);
assert!(extensions["min_p"].is_null());
let (same, none) = split_extensions(json!([1, 2]));
assert_eq!(same, json!([1, 2]));
assert!(none.is_empty());
}
#[test]
fn every_sampling_field_has_its_own_error() {
for (bad, field) in [
(
RequestSampling {
temperature: Some(3.0),
..Default::default()
},
"temperature",
),
(
RequestSampling {
top_p: Some(-0.1),
..Default::default()
},
"top_p",
),
(
RequestSampling {
min_p: Some(1.5),
..Default::default()
},
"min_p",
),
(
RequestSampling {
top_k: Some(-1),
..Default::default()
},
"top_k",
),
(
RequestSampling {
repetition_penalty: Some(0.0),
..Default::default()
},
"repetition_penalty",
),
(
RequestSampling {
frequency_penalty: Some(2.5),
..Default::default()
},
"frequency_penalty",
),
(
RequestSampling {
presence_penalty: Some(-2.5),
..Default::default()
},
"presence_penalty",
),
(
RequestSampling {
penalty_last_n: Some(-1),
..Default::default()
},
"penalty_last_n",
),
] {
assert_eq!(validate(&bad).unwrap_err().0, field);
}
assert!(validate(&RequestSampling::default()).is_ok());
}
#[test]
fn tune_is_bounded_and_strict() {
assert!(validate_tune(&Tune::default()).is_ok());
assert!(
validate_tune(&Tune {
pcie_frac: Some(1.1),
spec_min_p: None
})
.is_err()
);
assert!(
validate_tune(&Tune {
pcie_frac: None,
spec_min_p: Some(-0.1)
})
.is_err()
);
assert!(serde_json::from_value::<Tune>(json!({"pcie_frac": 0.5, "x": 1})).is_err());
}
}