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>
This commit is contained in:
Pavlo Ratushnyi
2026-10-14 15:17:04 +02:00
co-authored by Claude Sonnet 5.5
parent 7d90e0cc4f
commit cce433339d
33 changed files with 6667 additions and 108 deletions
Generated
+12
View File
@@ -1061,6 +1061,14 @@ dependencies = [
"serde_json",
]
[[package]]
name = "leleka-serving-policy"
version = "0.1.0"
dependencies = [
"leleka-sampler-ref",
"serde_json",
]
[[package]]
name = "leleka-tokenizer"
version = "0.1.0"
@@ -2061,6 +2069,8 @@ dependencies = [
"jsonschema",
"leleka-model-format",
"leleka-quant-core",
"leleka-sampler-ref",
"leleka-serving-policy",
"leleka-tokenizer",
"libc",
"regex",
@@ -2085,6 +2095,8 @@ dependencies = [
"jsonschema",
"leleka-backend-api",
"leleka-runtime",
"leleka-sampler-ref",
"leleka-serving-policy",
"prost",
"protoc-bin-vendored",
"regex",
+2 -2
View File
@@ -1,7 +1,7 @@
[workspace]
resolver = "3"
members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/cuda-driver", "crates/leleka-runtime", "crates/native-cpu-expert", "crates/sampler-ref", "control-plane", "desktop-core"]
default-members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/sampler-ref", "control-plane", "desktop-core"]
members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/cuda-driver", "crates/leleka-runtime", "crates/native-cpu-expert", "crates/sampler-ref", "crates/serving-policy", "control-plane", "desktop-core"]
default-members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/sampler-ref", "crates/serving-policy", "control-plane", "desktop-core"]
[workspace.package]
edition = "2024"
+2
View File
@@ -14,6 +14,8 @@ axum = "0.8"
futures-core = "0.3"
hex = "0.4"
leleka-tokenizer = { path = "../crates/tokenizer" }
leleka-sampler-ref = { path = "../crates/sampler-ref" }
leleka-serving-policy = { path = "../crates/serving-policy" }
leleka-model-format = { path = "../crates/model-format" }
leleka-quant-core = { path = "../crates/quant-core" }
http-body = "1"
+3 -2
View File
@@ -27,6 +27,7 @@ pub struct AppState {
pub tokenizer: Option<Arc<Tokenizer>>,
pub generation: Option<mpsc::Sender<GenerationCommand>>,
pub response_history: Arc<RwLock<responses::ResponseHistory>>,
pub settings: Arc<crate::settings::Settings>,
}
impl Default for AppState {
@@ -40,6 +41,7 @@ impl Default for AppState {
tokenizer: None,
generation: None,
response_history: Arc::new(RwLock::new(responses::ResponseHistory::default())),
settings: Arc::new(crate::settings::Settings::default()),
}
}
}
@@ -380,8 +382,7 @@ mod tests {
request: crate::wire::Generate {
token_ids: vec![10],
max_new: 1,
temperature: None,
top_p: None,
..Default::default()
},
result: crate::worker::GenerationResult::Buffered(result),
})
+6 -11
View File
@@ -41,8 +41,6 @@ struct Request {
store: Option<bool>,
stop: Option<Value>,
logprobs: Option<bool>,
frequency_penalty: Option<f64>,
presence_penalty: Option<f64>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
@@ -151,14 +149,6 @@ impl Request {
if self.logprobs == Some(true) {
return Err(invalid("logprobs", "log probabilities are not supported"));
}
if self.frequency_penalty.is_some_and(|x| x != 0.0)
|| self.presence_penalty.is_some_and(|x| x != 0.0)
{
return Err(invalid(
"frequency_penalty",
"nonzero frequency/presence penalties are not supported",
));
}
if !self.stream && self.stream_options.is_some() {
return Err(invalid(
"stream_options",
@@ -389,6 +379,8 @@ pub async fn create(
Ok(body) => body,
Err(e) => return error(e.status(), "invalid_json", None, &e.to_string()),
};
// Sampling extensions (top_k, min_p, penalties, seed, ...) are validated once, by the native request.
let (body, extensions) = crate::sampling::split_extensions(body);
let request: Request = match serde_json::from_value(body) {
Ok(r) => r,
Err(e) => {
@@ -400,7 +392,7 @@ pub async fn create(
);
}
};
let (request, stream, include_usage) = match request.into_responses() {
let (mut request, stream, include_usage) = match request.into_responses() {
Ok(r) => r,
Err((p, m)) => {
return error(
@@ -411,6 +403,9 @@ pub async fn create(
);
}
};
for (key, value) in extensions {
request[key] = value;
}
let response = responses::create(State(state), Ok(Json(request))).await;
if stream && response.status().is_success() {
return stream_response(response.into_body(), include_usage);
+4
View File
@@ -60,3 +60,7 @@ pub mod cuda_memory;
pub mod service_switch;
pub mod queue;
pub mod sampling;
pub mod settings;
+6 -1
View File
@@ -415,14 +415,19 @@ pub async fn create(
Ok(v) => v,
Err(e) => return error(e.status(), &e.to_string()),
};
// Anthropic's own top_k plus the Original server's extensions go to the native request as written.
let (value, extensions) = crate::sampling::split_extensions(value);
let r: Request = match serde_json::from_value(value) {
Ok(r) => r,
Err(e) => return error(StatusCode::BAD_REQUEST, &e.to_string()),
};
let (r, stream) = match r.into_responses() {
let (mut r, stream) = match r.into_responses() {
Ok(r) => r,
Err(e) => return error(StatusCode::BAD_REQUEST, &e),
};
for (key, value) in extensions {
r[key] = value;
}
let response = responses::create(State(state), Ok(Json(r))).await;
if !response.status().is_success() {
return response;
+1 -2
View File
@@ -104,8 +104,7 @@ mod tests {
request: Generate {
token_ids: vec![65],
max_new: 1,
temperature: None,
top_p: None,
..Default::default()
},
result: GenerationResult::Buffered(result),
},
+279 -11
View File
@@ -500,6 +500,17 @@ pub struct CreateRequest {
pub tool_choice: Option<Value>,
pub temperature: Option<f64>,
pub top_p: Option<f64>,
/// Original-server sampling extensions (top level, like `serve/server.py`): see `sampling`.
pub top_k: Option<i64>,
pub min_p: Option<f64>,
pub repetition_penalty: Option<f64>,
pub frequency_penalty: Option<f64>,
pub presence_penalty: Option<f64>,
pub penalty_last_n: Option<i64>,
pub seed: Option<u64>,
pub strata_tune: Option<crate::sampling::Tune>,
pub experimental_speed_projection: Option<bool>,
pub reasoning_budget_tokens: Option<Value>,
pub truncation: Option<String>,
pub metadata: Option<Map<String, Value>>,
pub store: Option<bool>,
@@ -528,6 +539,53 @@ pub enum TextFormat {
}
impl CreateRequest {
/// The request's sampling fields as the Original's serving layer reads them.
pub fn sampling(&self) -> leleka_sampler_ref::RequestSampling {
leleka_sampler_ref::RequestSampling {
temperature: self.temperature,
top_p: self.top_p,
top_k: self.top_k,
min_p: self.min_p,
repetition_penalty: self.repetition_penalty,
frequency_penalty: self.frequency_penalty,
presence_penalty: self.presence_penalty,
penalty_last_n: self.penalty_last_n,
seed: self.seed,
}
}
/// Fill what the request left out from the server defaults: the config's `sampling` block,
/// then the shared Chat settings (`{**config, **shared}`, request fields win, an explicit
/// `temperature: 0` stays greedy), the shared `max_tokens`, and the shared reasoning effort.
pub fn apply_defaults(&mut self, settings: &crate::settings::Settings) {
let merged = settings.merged();
let shared = settings.shared();
let effective =
leleka_sampler_ref::RequestSampling::overlay(&merged.sampling, &self.sampling());
self.temperature = effective.temperature;
self.top_p = effective.top_p;
self.top_k = effective.top_k;
self.min_p = effective.min_p;
self.repetition_penalty = effective.repetition_penalty;
self.frequency_penalty = effective.frequency_penalty;
self.presence_penalty = effective.presence_penalty;
self.penalty_last_n = effective.penalty_last_n;
self.seed = effective.seed;
self.experimental_speed_projection = self
.experimental_speed_projection
.or(merged.experimental_speed_projection);
if self.max_output_tokens.is_none()
&& let Some(limit) = shared.max_tokens
{
self.max_output_tokens = Some(limit.min(u64::from(u32::MAX)) as u32);
}
if self.reasoning.is_none()
&& let Some(effort) = &shared.reasoning_effort
{
self.reasoning = Some(json!({"effort": effort}));
}
}
fn forced_tool(&self) -> Option<&str> {
self.tool_choice
.as_ref()
@@ -608,17 +666,20 @@ impl CreateRequest {
if self.max_output_tokens == Some(0) {
return Err(("max_output_tokens", "max_output_tokens must be positive"));
}
if self
.temperature
.is_some_and(|value| !value.is_finite() || !(0.0..=2.0).contains(&value))
{
return Err(("temperature", "temperature must be between 0 and 2"));
crate::sampling::validate(&self.sampling())?;
if let Some(tune) = &self.strata_tune {
crate::sampling::validate_tune(tune)?;
}
if self
.top_p
.is_some_and(|value| !value.is_finite() || !(0.0..=1.0).contains(&value))
if leleka_serving_policy::reasoning::parse_budget(
self.reasoning_budget_tokens.as_ref(),
None,
)
.is_err()
{
return Err(("top_p", "top_p must be between 0 and 1"));
return Err((
"reasoning_budget_tokens",
"reasoning_budget_tokens must be a whole number of tokens (0: no budget)",
));
}
if let Some(TextOptions {
format: TextFormat::JsonSchema { name, schema, .. },
@@ -937,6 +998,7 @@ pub async fn create(
message,
);
}
request.apply_defaults(&state.settings);
let token_ids = match prepare_input_tokens(&state, &mut request, tokenizer.clone()).await {
Ok(ids) => ids,
Err(error) => return *error,
@@ -957,8 +1019,10 @@ pub async fn create(
max_new: request
.max_output_tokens
.unwrap_or(32768.min(remaining).max(1)),
temperature: request.temperature,
top_p: request.top_p,
sampling: request.sampling(),
tune: request.strata_tune.map(Into::into),
cvec: request.experimental_speed_projection,
embeddings: None,
};
if request.stream {
let (events, received) = mpsc::channel(16);
@@ -4115,6 +4179,210 @@ mod tests {
fs::remove_dir_all(root).unwrap();
}
/// Run one request through `route` against a fake worker and return the `Generate` it was handed.
async fn captured_generate<F, Fut>(
settings: crate::settings::Settings,
body: Value,
route: F,
) -> (StatusCode, Option<Generate>)
where
F: FnOnce(
State<AppState>,
Result<Json<Value>, axum::extract::rejection::JsonRejection>,
) -> Fut,
Fut: std::future::Future<Output = Response>,
{
let (tokenizer, root) = test_tokenizer();
let (sender, mut receiver) = mpsc::channel(1);
let mut state = AppState::default();
state.worker.write().await.state = WorkerState::Ready;
state.tokenizer = Some(tokenizer);
state.generation = Some(sender);
state.settings = Arc::new(settings);
let worker = tokio::spawn(async move {
let command: GenerationCommand = receiver.recv().await?;
let request = command.request.clone();
let prompt_tokens = command.request.token_ids.len() as u64;
let events = vec![
Event::Token(79),
Event::Token(75),
Event::Done(Done {
generated: 2,
prompt_tokens,
prompt_ms: 1.0,
decode_ms: 2.0,
finish: Finish::Stop,
drafts_accepted: None,
drafts_offered: None,
reused: Some(0),
expert_hits: None,
expert_lookups: None,
}),
];
match command.result {
GenerationResult::Buffered(result) => {
let _ = result.send(Ok(events));
}
GenerationResult::Streaming(sender) => {
for event in events {
let _ = sender.send(Ok(event)).await;
}
}
GenerationResult::Finished => {}
}
Some(request)
});
let response = route(State(state), Ok(Json(body))).await;
let status = response.status();
let _ = to_bytes(response.into_body(), usize::MAX).await;
let generate = if status.is_success() {
worker.await.unwrap()
} else {
worker.abort();
None
};
fs::remove_dir_all(root).unwrap();
(status, generate)
}
fn all_sampling_fields() -> Value {
json!({"temperature": 0.7, "top_p": 0.9, "top_k": 40, "min_p": 0.05,
"repetition_penalty": 1.1, "frequency_penalty": 0.25, "presence_penalty": 0.5,
"penalty_last_n": 128, "seed": 42,
"strata_tune": {"pcie_frac": 0.0, "spec_min_p": 0.25}, "experimental_speed_projection": false})
}
const FULL_KEYS: &str = " temperature=0.7 top_p=0.9 top_k=40 min_p=0.05 penalty_repeat=1.1 penalty_freq=0.25 penalty_present=0.5 penalty_last_n=128 seed=42 pcie_frac=0.0 spec_min_p=0.25 cvec=0";
fn merge(mut base: Value, extra: Value) -> Value {
base.as_object_mut()
.unwrap()
.extend(extra.as_object().unwrap().clone());
base
}
#[tokio::test]
async fn responses_forward_every_original_gen_field() {
for stream in [false, true] {
let body = merge(
json!({"model": "strata-local", "input": "Hello", "reasoning": {"effort": "none"}, "stream": stream}),
all_sampling_fields(),
);
let (status, generate) = captured_generate(Default::default(), body, create).await;
assert_eq!(status, StatusCode::OK);
let line = generate.unwrap().line().unwrap();
assert!(
line.starts_with(&format!("GEN 32768{FULL_KEYS} ")),
"{line}"
);
}
}
#[tokio::test]
async fn chat_completions_forward_penalties_and_extensions() {
let body = merge(
json!({"model": "strata-local", "messages": [{"role": "user", "content": "Hello"}]}),
all_sampling_fields(),
);
let (status, generate) =
captured_generate(Default::default(), body, crate::chat::create).await;
assert_eq!(status, StatusCode::OK);
let line = generate.unwrap().line().unwrap();
assert!(
line.starts_with(&format!("GEN 32768{FULL_KEYS} ")),
"{line}"
);
}
#[tokio::test]
async fn messages_forward_anthropic_top_k_and_extensions() {
let body = json!({"model": "strata-local", "max_tokens": 64,
"messages": [{"role": "user", "content": "Hello"}],
"temperature": 0.5, "top_p": 0.8, "top_k": 30, "seed": 9, "repetition_penalty": 1.2});
let (status, generate) =
captured_generate(Default::default(), body, crate::messages::create).await;
assert_eq!(status, StatusCode::OK);
let line = generate.unwrap().line().unwrap();
assert!(
line.starts_with(
"GEN 64 temperature=0.5 top_p=0.8 top_k=30 penalty_repeat=1.2 penalty_last_n=64 seed=9 "
),
"{line}"
);
}
#[tokio::test]
async fn out_of_range_sampling_is_refused_before_the_worker() {
for bad in [
json!({"temperature": 2.5}),
json!({"top_p": 1.5}),
json!({"top_k": -1}),
json!({"min_p": 1.5}),
json!({"repetition_penalty": 0}),
json!({"frequency_penalty": 3}),
json!({"presence_penalty": -3}),
json!({"penalty_last_n": -1}),
json!({"seed": -1}),
json!({"strata_tune": {"pcie_frac": 2}}),
json!({"strata_tune": {"unknown": 1}}),
json!({"reasoning_budget_tokens": "many"}),
] {
let body = merge(
json!({"model": "strata-local", "input": "Hello"}),
bad.clone(),
);
let (status, generate) = captured_generate(Default::default(), body, create).await;
assert_eq!(status, StatusCode::BAD_REQUEST, "{bad}");
assert!(generate.is_none());
}
}
#[tokio::test]
async fn server_defaults_fill_what_the_request_leaves_out() {
use leleka_serving_policy::shared::sampling_defaults_from_config;
let config =
sampling_defaults_from_config(&json!({"temperature": 0.3, "min_p": 0.1, "top_k": 10}))
.unwrap();
let settings = crate::settings::Settings::new(config);
settings
.set_shared(&json!({"temperature": 0.9, "seed": 4, "max_tokens": 77}))
.unwrap();
let body =
json!({"model": "strata-local", "input": "Hello", "reasoning": {"effort": "none"}});
let (_, generate) = captured_generate(settings, body.clone(), create).await;
let generate = generate.unwrap();
assert_eq!(generate.max_new, 77);
assert!(
generate
.line()
.unwrap()
.starts_with("GEN 77 temperature=0.9 top_k=10 min_p=0.1 seed=4 "),
"{}",
generate.line().unwrap()
);
// The request wins, and an explicit 0 stays greedy.
let settings = crate::settings::Settings::default();
settings
.set_shared(&json!({"temperature": 0.9, "max_tokens": 77}))
.unwrap();
let (_, generate) = captured_generate(
settings,
merge(body, json!({"temperature": 0, "max_output_tokens": 5})),
create,
)
.await;
assert_eq!(
generate
.unwrap()
.line()
.unwrap()
.split(' ')
.take(2)
.collect::<Vec<_>>(),
["GEN", "5"]
);
}
#[tokio::test]
async fn nonstreaming_tool_call_keeps_typed_arguments() {
let (tokenizer, root) = test_tokenizer();
+216
View File
@@ -0,0 +1,216 @@
//! 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());
}
}
+179
View File
@@ -0,0 +1,179 @@
//! Server-wide sampling defaults: the run config's `sampling` block and the Chat settings every
//! client shares (`POST /settings`), kept next to the config between starts. Port of the
//! settings half of `serve/server.py` `Service` (`set_shared`, `with_shared`, the default merge in
//! `run`). The pure rules live in `leleka-serving-policy`.
use std::{
fs,
path::{Path, PathBuf},
sync::RwLock,
};
use leleka_serving_policy::shared::{
ConfigSampling, MergedDefaults, SharedDefaults, clean_shared_defaults, merged_defaults,
};
use serde_json::Value;
#[derive(Default)]
pub struct Settings {
config: ConfigSampling,
shared: RwLock<SharedDefaults>,
shared_path: Option<PathBuf>,
/// The config's `reasoning_budget_tokens` (raw, validated at startup).
reasoning_budget_default: Option<Value>,
}
impl Settings {
pub fn new(config: ConfigSampling) -> Self {
Self {
config,
..Default::default()
}
}
pub fn with_reasoning_budget(mut self, default: Option<Value>) -> Self {
self.reasoning_budget_default = default;
self
}
/// Persist shared settings in `path` and load what a previous run left there. A missing,
/// unreadable or invalid file means "clients use their own settings" (as in the Original).
pub fn with_shared_file(mut self, path: PathBuf) -> Self {
let loaded = fs::read_to_string(&path)
.ok()
.and_then(|text| serde_json::from_str::<Value>(&text).ok())
.and_then(|value| clean_shared_defaults(&value).ok())
.unwrap_or_default();
*self.shared.write().expect("settings lock") = loaded;
self.shared_path = Some(path);
self
}
pub fn shared(&self) -> SharedDefaults {
self.shared.read().expect("settings lock").clone()
}
pub fn config(&self) -> &ConfigSampling {
&self.config
}
pub fn reasoning_budget_default(&self) -> Option<&Value> {
self.reasoning_budget_default.as_ref()
}
/// `{**config sampling, **shared}`.
pub fn merged(&self) -> MergedDefaults {
merged_defaults(&self.config, &self.shared())
}
/// `POST /settings`: validate, replace and persist. `Err` is the 400 message.
pub fn set_shared(&self, defaults: &Value) -> Result<SharedDefaults, String> {
let cleaned = clean_shared_defaults(defaults)?;
*self.shared.write().expect("settings lock") = cleaned.clone();
if let Some(path) = &self.shared_path
&& let Err(error) = persist(path, &cleaned)
{
eprintln!("could not save the shared settings: {error}");
}
Ok(cleaned)
}
}
fn persist(path: &Path, shared: &SharedDefaults) -> std::io::Result<()> {
if shared.is_empty() {
match fs::remove_file(path) {
Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error),
_ => Ok(()),
}
} else {
// Written next to the destination and renamed, so a crash never leaves half a file.
let temporary = path.with_extension("tmp");
fs::write(&temporary, serde_json::to_string_pretty(&shared.to_json())?)?;
fs::rename(&temporary, path)
}
}
/// The shared-settings file the Original keeps next to its config: `<config minus extension>.shared-settings.json`.
pub fn default_shared_path(config: &Path) -> PathBuf {
let mut name = config.with_extension("").into_os_string();
name.push(".shared-settings.json");
PathBuf::from(name)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn temp(name: &str) -> PathBuf {
let dir =
std::env::temp_dir().join(format!("strata-settings-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn shared_settings_persist_across_starts_and_empty_removes_the_file() {
let dir = temp("persist");
let path = dir.join("strata.shared-settings.json");
let first = Settings::default().with_shared_file(path.clone());
assert!(first.shared().is_empty());
first
.set_shared(&json!({"temperature": 0.5, "max_tokens": 128}))
.unwrap();
assert!(path.exists());
let second = Settings::default().with_shared_file(path.clone());
assert_eq!(second.shared().temperature, Some(0.5));
assert_eq!(second.shared().max_tokens, Some(128));
second.set_shared(&json!({})).unwrap();
assert!(!path.exists());
assert!(
Settings::default()
.with_shared_file(path)
.shared()
.is_empty()
);
let _ = fs::remove_dir_all(dir);
}
#[test]
fn a_corrupt_file_means_no_shared_settings() {
let dir = temp("corrupt");
let path = dir.join("s.json");
fs::write(&path, "{not json").unwrap();
assert!(
Settings::default()
.with_shared_file(path.clone())
.shared()
.is_empty()
);
fs::write(&path, r#"{"temperature": 9}"#).unwrap();
assert!(
Settings::default()
.with_shared_file(path)
.shared()
.is_empty()
);
let _ = fs::remove_dir_all(dir);
}
#[test]
fn a_rejected_update_keeps_the_previous_settings() {
let settings = Settings::default();
settings.set_shared(&json!({"top_k": 10})).unwrap();
assert_eq!(
settings.set_shared(&json!({"top_k": 100})).unwrap_err(),
"top_k: an integer 1..64"
);
assert_eq!(settings.shared().top_k, Some(10));
}
#[test]
fn default_path_sits_next_to_the_config() {
assert_eq!(
default_shared_path(Path::new("/etc/strata/run.json")),
PathBuf::from("/etc/strata/run.shared-settings.json")
);
}
}
+185 -22
View File
@@ -1,36 +1,82 @@
//! Typed boundary for the resident Strata `--serve` stdin/stdout protocol.
#[derive(Debug, Clone, PartialEq)]
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>,
}
/// 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 temperature: Option<f64>,
pub top_p: Option<f64>,
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>,
}
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");
}
if self
.temperature
.is_some_and(|value| !value.is_finite() || !(0.0..=2.0).contains(&value))
{
return Err("temperature must be finite and between 0 and 2");
// 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 '='");
}
if self
.top_p
.is_some_and(|value| !value.is_finite() || !(0.0..=1.0).contains(&value))
{
return Err("top_p must be finite and between 0 and 1");
}
let mut line = format!("GEN {}", self.max_new);
if let Some(value) = self.temperature.filter(|value| *value > 0.0) {
line.push_str(&format!(" temperature={value}"));
}
if let Some(value) = self.top_p.filter(|value| *value < 1.0) {
line.push_str(&format!(" top_p={value}"));
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() {
@@ -174,8 +220,12 @@ mod tests {
let request = Generate {
token_ids: vec![101, 42, 7],
max_new: 256,
temperature: Some(0.7),
top_p: Some(0.9),
sampling: RequestSampling {
temperature: Some(0.7),
top_p: Some(0.9),
..Default::default()
},
..Default::default()
};
assert_eq!(
request.line().unwrap(),
@@ -191,6 +241,119 @@ mod tests {
);
}
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),
};
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")
+18 -26
View File
@@ -526,8 +526,7 @@ mod tests {
request: Generate {
token_ids: vec![10000; 200000],
max_new: 1,
temperature: None,
top_p: None,
..Default::default()
},
result: GenerationResult::Buffered(result),
})
@@ -570,8 +569,7 @@ mod tests {
request: Generate {
token_ids: vec![10],
max_new: 100,
temperature: None,
top_p: None,
..Default::default()
},
result: GenerationResult::Streaming(events),
})
@@ -649,8 +647,12 @@ mod tests {
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
temperature: Some(0.5),
top_p: Some(0.9),
sampling: leleka_sampler_ref::RequestSampling {
temperature: Some(0.5),
top_p: Some(0.9),
..Default::default()
},
..Default::default()
},
result: GenerationResult::Buffered(result_tx),
})
@@ -684,8 +686,7 @@ mod tests {
request: Generate {
token_ids: vec![10, 20],
max_new: 300_000,
temperature: None,
top_p: None,
..Default::default()
},
result: GenerationResult::Buffered(result_tx),
})
@@ -745,8 +746,7 @@ mod tests {
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
temperature: None,
top_p: None,
..Default::default()
},
result: GenerationResult::Buffered(result_tx),
})
@@ -769,8 +769,7 @@ mod tests {
request: Generate {
token_ids: vec![99],
max_new: 1,
temperature: None,
top_p: None,
..Default::default()
},
result: GenerationResult::Buffered(result_tx),
})
@@ -822,8 +821,7 @@ mod tests {
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
temperature: None,
top_p: None,
..Default::default()
},
result: GenerationResult::Streaming(events_tx),
})
@@ -846,8 +844,7 @@ mod tests {
request: Generate {
token_ids: vec![99],
max_new: 1,
temperature: None,
top_p: None,
..Default::default()
},
result: GenerationResult::Buffered(result_tx),
})
@@ -900,8 +897,7 @@ mod tests {
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
temperature: None,
top_p: None,
..Default::default()
},
result: GenerationResult::Buffered(result_tx),
})
@@ -952,8 +948,7 @@ mod tests {
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
temperature: None,
top_p: None,
..Default::default()
},
result: GenerationResult::Streaming(events_tx),
})
@@ -984,8 +979,7 @@ mod tests {
request: Generate {
token_ids: vec![99],
max_new: 1,
temperature: None,
top_p: None,
..Default::default()
},
result: GenerationResult::Buffered(result_tx),
})
@@ -1037,8 +1031,7 @@ mod tests {
request: Generate {
token_ids,
max_new,
temperature: None,
top_p: None,
..Default::default()
},
result: GenerationResult::Buffered(sender),
},
@@ -1169,8 +1162,7 @@ mod tests {
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
temperature: None,
top_p: None,
..Default::default()
},
result: GenerationResult::Streaming(events_tx),
})
File diff suppressed because it is too large Load Diff
Vendored Regular → Executable
View File
+223
View File
@@ -0,0 +1,223 @@
"""Offline golden generator for the control-plane serving surface (Python is allowed for fixtures only).
Runs the REAL Python handlers of the pinned Strata (`engine/strata/serve/*.py`, mock engine, no GPU) over tables
of inputs and records what they answer. The Rust tests in `control-plane/tests/golden_*.rs` and the unit tests of
`crates/serving-policy` compare against these files.
python3 -I control-plane/tests/golden/gen_goldens.py [section ...]
Needs the packages in engine/strata/requirements.txt (jinja2, jsonschema, regex). The scratchpad venv has them.
Sections: gen_lines, shared, props_slots, cors, ...
"""
import json
import os
import queue
import sys
import threading
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.normpath(os.path.join(HERE, "..", "..", ".."))
ENGINE = os.path.join(REPO, "engine", "strata")
sys.path.insert(0, ENGINE)
sys.path.insert(0, os.path.join(ENGINE, "tools"))
OUT_CONTROL = os.path.join(HERE, "..", "fixtures", "golden")
OUT_POLICY = os.path.join(REPO, "crates", "serving-policy", "tests", "fixtures")
def write(name, obj, dest="control"):
out = OUT_POLICY if dest == "policy" else OUT_CONTROL
os.makedirs(out, exist_ok=True)
path = os.path.join(out, name + ".json")
with open(path, "w", encoding="utf-8") as f:
json.dump(obj, f, indent=1, ensure_ascii=False, sort_keys=False)
f.write("\n")
print("wrote", os.path.relpath(path, REPO), file=sys.stderr)
# ------------------------------------------------------------------------------------------------ gen_lines
def gen_lines():
from serve.server import StrataEngine
class Pipe:
def __init__(self):
self.sent = []
def write(self, text):
self.sent.append(text)
def flush(self):
pass
def capture(ids, max_new, sampling, embeddings=None):
eng = object.__new__(StrataEngine)
eng.proc = type("P", (), {"stdin": Pipe()})()
eng.lines = queue.Queue()
eng.lines.put("DONE 1 1 1.0 1.0 stop\n")
eng.can_stop = False
eng.progress = None
eng.prefill_tok_s_mean = None
eng.last = {}
list(eng.generate(ids, max_new, sampling, threading.Event(), embeddings=embeddings))
return "".join(eng.proc.stdin.sent)
cases = []
sampling_tables = [
{},
{"temperature": 0.0},
{"temperature": 0.7},
{"temperature": 0.7, "top_p": 0.9},
{"temperature": 1, "top_p": 1.0},
{"temperature": 0.8, "top_k": 40, "min_p": 0.05},
{"temperature": 0.8, "top_k": 0},
{"temperature": 0.8, "top_k": 1000},
{"temperature": 0.6, "top_p": 0.95, "top_k": 20, "min_p": 0.0},
{"repetition_penalty": 1.1},
{"repetition_penalty": 1.1, "penalty_last_n": 256},
{"presence_penalty": 0.5, "frequency_penalty": 0.25},
{"presence_penalty": -0.5},
{"frequency_penalty": 1.5, "penalty_last_n": 0},
{"temperature": 0.7, "seed": 42},
{"temperature": 0.7, "seed": 0},
{"temperature": 0.7, "seed": 18446744073709551615},
{"temperature": 0.9, "top_p": 0.8, "top_k": 33, "min_p": 0.02, "repetition_penalty": 1.05,
"presence_penalty": 0.1, "frequency_penalty": 0.2, "penalty_last_n": 128, "seed": 7},
{"strata_tune": {"pcie_frac": 0.0}},
{"strata_tune": {"pcie_frac": 0.35, "spec_min_p": 0.2}},
{"strata_tune": {"spec_min_p": 1.0}},
{"experimental_speed_projection": True},
{"experimental_speed_projection": False},
{"temperature": 0.5, "strata_tune": {"pcie_frac": 0.5}, "experimental_speed_projection": False},
]
for ids, max_new, emb in (([1, 2, 3], 16, None), ([248045, 872, 198, 9707], 4096, None),
([5, 248056, 248056, 6], 32, "/tmp/req-abc123.sve")):
for sampling in sampling_tables:
cases.append({"token_ids": ids, "max_new": max_new, "embeddings": emb, "sampling": sampling,
"line": capture(ids, max_new, sampling, emb)})
write("gen_lines", {"source": "serve/server.py StrataEngine.generate (real code, fake pipe)", "cases": cases})
# ------------------------------------------------------------------------------------------------ shared
def shared():
from serve.server import clean_shared_defaults, sampling_defaults_from_config
clean_cases = [
None, {}, [], "x", 5,
{"temperature": 0.7}, {"temperature": 1}, {"temperature": 0}, {"temperature": 2}, {"temperature": 2.5},
{"temperature": -0.1}, {"temperature": True}, {"temperature": "0.5"},
{"top_p": 0.9}, {"top_p": 1}, {"top_p": 0}, {"top_p": 1.5}, {"top_p": False},
{"top_k": 40}, {"top_k": 40.0}, {"top_k": 40.5}, {"top_k": 0}, {"top_k": 64}, {"top_k": 65}, {"top_k": "40"},
{"seed": 7}, {"seed": 7.0}, {"seed": 0}, {"seed": -3}, {"seed": 1.5}, {"seed": 18446744073709551615},
{"max_tokens": 512}, {"max_tokens": 0}, {"max_tokens": "10"},
{"reasoning_effort": "none"}, {"reasoning_effort": "low"}, {"reasoning_effort": "medium"},
{"reasoning_effort": "high"}, {"reasoning_effort": "xhigh"}, {"reasoning_effort": 3},
{"experimental_speed_projection": True}, {"experimental_speed_projection": False},
{"experimental_speed_projection": 1},
{"temperature": None, "top_p": "", "top_k": None}, {"unknown": 1}, {"unknown": None}, {"min_p": 0.1},
{"temperature": 0.7, "top_p": 0.9, "top_k": 20, "seed": 11, "max_tokens": 100,
"reasoning_effort": "medium", "experimental_speed_projection": False},
]
clean = []
for case in clean_cases:
try:
clean.append({"input": case, "ok": clean_shared_defaults(case)})
except ValueError as e:
clean.append({"input": case, "error": str(e)})
config_cases = [
None, {}, {"temperature": 0.7}, {"temperature": 0}, {"temperature": -1}, {"temperature": True},
{"top_p": 0.95}, {"top_p": 0}, {"top_p": 1.01}, {"min_p": 0.05}, {"min_p": 0}, {"min_p": 2},
{"top_k": 40}, {"top_k": 0}, {"top_k": 65}, {"top_k": 20.0}, {"top_k": 1.5},
{"presence_penalty": 0.5}, {"presence_penalty": -0.5}, {"frequency_penalty": 0.25},
{"frequency_penalty": -1}, {"repetition_penalty": 1.1}, {"repetition_penalty": 0},
{"penalty_last_n": 128}, {"penalty_last_n": 0}, {"penalty_last_n": -2}, {"penalty_last_n": 1.5},
{"seed": 5}, {"seed": 0}, {"seed": 5.5}, {"seed": "5"},
{"experimental_speed_projection": True}, {"experimental_speed_projection": "yes"},
{"temperature": None, "top_p": None}, {"nonsense": 3}, {"temperature": 0.6, "nonsense": 3},
{"temperature": 0.6, "top_p": 0.9, "top_k": 30, "min_p": 0.02, "presence_penalty": 0.1,
"frequency_penalty": 0.1, "repetition_penalty": 1.05, "penalty_last_n": 64, "seed": 9},
]
import contextlib
import io
config = []
for case in config_cases:
out = io.StringIO()
try:
with contextlib.redirect_stdout(out):
ok = sampling_defaults_from_config({"sampling": case} if case is not None else {})
config.append({"input": case, "ok": ok, "ignored": [ln for ln in out.getvalue().splitlines()
if "unknown key" in ln]})
except SystemExit as e:
config.append({"input": case, "error": str(e)})
write("shared", {"source": "serve/server.py clean_shared_defaults / sampling_defaults_from_config (real code)",
"clean": clean, "config": config}, dest="policy")
# ------------------------------------------------------------------------------------------------ reasoning
def reasoning():
import random
from serve.frontend import OutputParser
from serve.server import Detokenizer, Service, ByteTokenizer
class BytesTok:
"""Token i's bytes are the table's entry; what Detokenizer needs from the real tokenizer."""
def __init__(self, table):
self.table = table
def token_bytes(self, t):
return self.table[t]
pieces = [b"a", b"b", b" so ", b"think", b"</", b"/think>", b"</think>", b"</thi", b"nk>", b"<", b"/", b"\n",
b"\xc3", b"\xa9", "\u65e5".encode()[:1], "\u65e5".encode()[1:], b"\xff", b"\xe2\x82", b"\xac", b"<t",
b"hink>", b"x"]
rng = random.Random(1234)
seqs = [[0, 1, 2, 3], [4, 5], [6, 0, 1], [0, 4, 0, 1], [11, 12, 0, 0, 0], [13, 14, 0, 0], [16, 0, 0], [17, 18, 0],
[3, 4, 5, 3, 3], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
for _ in range(120):
seqs.append([rng.randrange(len(pieces)) for _ in range(rng.randrange(1, 14))])
cases = []
for seq in seqs:
row = {"pieces_hex": [pieces[i].hex() for i in seq], "wrap_at": {}}
for budget in (1, 2, 3, 5, 8):
parser = OutputParser(thinking=True, tools=None, stream_tools=True)
detok = Detokenizer(BytesTok(pieces))
thought, wrap_at = 0, None
for i, t in enumerate(seq):
parser.feed(detok.push(t))
if parser.state == "reasoning":
thought += 1
if thought >= budget and not parser.buf and not detok.pending():
wrap_at = i
break
row["wrap_at"][str(budget)] = wrap_at
cases.append(row)
parse = []
svc = Service.__new__(Service)
for req, default in [(None, 0), ({}, 0), ({"reasoning_budget_tokens": 20}, 0), ({"reasoning_budget_tokens": 20.0}, 0),
({"reasoning_budget_tokens": 0}, 50), ({"reasoning_budget_tokens": -1}, 50),
({}, 50), ({"reasoning_budget_tokens": None}, 50), ({"reasoning_budget_tokens": True}, 0),
({"reasoning_budget_tokens": "5"}, 0), ({"reasoning_budget_tokens": 2.5}, 0),
({"reasoning_budget_tokens": [1]}, 0), ({"reasoning_budget_tokens": 10000}, 0)]:
svc.reasoning_budget_tokens = default
try:
parse.append({"request": req, "default": default, "ok": svc.reasoning_budget(req)})
except ValueError as e:
parse.append({"request": req, "default": default, "error": str(e)})
from serve.server import REASONING_WRAP_UP
write("reasoning", {"source": "serve/server.py Service.reasoning_budget + Service.run budget branch (real "
"Detokenizer/OutputParser)", "wrap_up": REASONING_WRAP_UP, "cases": cases,
"parse": parse}, dest="policy")
SECTIONS = {"gen_lines": gen_lines, "shared": shared, "reasoning": reasoning}
def main(argv):
names = argv or list(SECTIONS)
for name in names:
SECTIONS[name]()
if __name__ == "__main__":
main(sys.argv[1:])
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "leleka-serving-policy"
version = "0.1.0"
description = "Pure Rust ports of the Original Strata serving-layer policies: shared settings, reasoning budget, stall watchdog, CORS, idle unload, logits stride, image positions, control vectors"
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[dependencies]
leleka-sampler-ref = { path = "../sampler-ref" }
serde_json = "1"
[lints]
workspace = true
+258
View File
@@ -0,0 +1,258 @@
//! Sampling fields in the forms the in-process runtime protocol carries them: JSON request
//! fields -> [`RequestSampling`] -> fixed point ([`FixedPoint`], thousandths / millionths).
//!
//! The runtime gRPC contract (`runtime.proto` `GenerateRequest`) and `backend-api`
//! `SamplingOptions` keep requests `Eq` by using integers. A float that a client wrote with more
//! fractional digits than the field carries is *refused*, never rounded: rounding would silently
//! change the distribution the client asked for.
use leleka_sampler_ref::params::{FixedPoint, RequestSampling, SamplingError};
use serde_json::{Map, Value};
/// JSON keys of the sampling fields.
pub const SAMPLING_KEYS: [&str; 9] = [
"temperature",
"top_p",
"top_k",
"min_p",
"repetition_penalty",
"frequency_penalty",
"presence_penalty",
"penalty_last_n",
"seed",
];
fn err(field: &'static str, expected: &'static str) -> SamplingError {
SamplingError { field, expected }
}
/// `round(value * scale)` when `result / scale` is exactly `value` again.
fn exact(value: f64, scale: f64) -> Option<i64> {
let scaled = (value * scale).round();
if !scaled.is_finite() || scaled.abs() > 9.0e15 {
return None;
}
let candidate = scaled as i64;
(candidate as f64 / scale == value).then_some(candidate)
}
const PRECISION_MILLI: &str = "a decimal with at most 3 fractional digits";
const PRECISION_MICRO: &str = "a decimal with at most 6 fractional digits";
/// Validate and convert. Order of checks: the request contract first
/// ([`RequestSampling::validate`]), then representability.
pub fn to_fixed_point(sampling: &RequestSampling) -> Result<FixedPoint, SamplingError> {
sampling.validate()?;
let micro_u32 =
|field: &'static str, value: Option<f64>| -> Result<Option<u32>, SamplingError> {
value
.map(|v| {
exact(v, 1_000_000.0)
.and_then(|n| u32::try_from(n).ok())
.ok_or_else(|| err(field, PRECISION_MICRO))
})
.transpose()
};
let micro_i32 =
|field: &'static str, value: Option<f64>| -> Result<Option<i32>, SamplingError> {
value
.map(|v| {
exact(v, 1_000_000.0)
.and_then(|n| i32::try_from(n).ok())
.ok_or_else(|| err(field, PRECISION_MICRO))
})
.transpose()
};
let temperature_milli = match sampling.temperature {
None => 0,
Some(t) => exact(t, 1000.0)
.and_then(|n| u32::try_from(n).ok())
.ok_or_else(|| err("temperature", PRECISION_MILLI))?,
};
Ok(FixedPoint {
temperature_milli,
top_p_micro: micro_u32("top_p", sampling.top_p)?,
top_k: sampling.top_k.map(|k| u32::try_from(k).unwrap_or(u32::MAX)),
min_p_micro: micro_u32("min_p", sampling.min_p)?,
repetition_penalty_micro: micro_u32("repetition_penalty", sampling.repetition_penalty)?,
frequency_penalty_micro: micro_i32("frequency_penalty", sampling.frequency_penalty)?,
presence_penalty_micro: micro_i32("presence_penalty", sampling.presence_penalty)?,
penalty_last_n: sampling
.penalty_last_n
.map(|n| {
u32::try_from(n).map_err(|_| err("penalty_last_n", "an integer in 0..=2147483647"))
})
.transpose()?,
seed: sampling.seed,
})
}
fn number(object: &Map<String, Value>, key: &'static str) -> Result<Option<f64>, SamplingError> {
match object.get(key) {
None | Some(Value::Null) => Ok(None),
Some(Value::Number(n)) => n
.as_f64()
.map(Some)
.ok_or_else(|| err(key, "a finite number")),
Some(_) => Err(err(key, "a number")),
}
}
fn integer(object: &Map<String, Value>, key: &'static str) -> Result<Option<i64>, SamplingError> {
match object.get(key) {
None | Some(Value::Null) => Ok(None),
Some(Value::Number(n)) => n.as_i64().map(Some).ok_or_else(|| err(key, "an integer")),
Some(_) => Err(err(key, "an integer")),
}
}
/// Read the sampling fields of a JSON request object (unrelated keys are ignored here; the caller
/// owns the allow-list of the rest of its request). Types are strict: `top_k` must be an integer,
/// `seed` an unsigned integer. Ranges are checked by [`RequestSampling::validate`].
pub fn sampling_from_object(object: &Map<String, Value>) -> Result<RequestSampling, SamplingError> {
let seed = match object.get("seed") {
None | Some(Value::Null) => None,
Some(Value::Number(n)) => Some(
n.as_u64()
.ok_or_else(|| err("seed", "an unsigned integer"))?,
),
Some(_) => return Err(err("seed", "an unsigned integer")),
};
let sampling = RequestSampling {
temperature: number(object, "temperature")?,
top_p: number(object, "top_p")?,
top_k: integer(object, "top_k")?,
min_p: number(object, "min_p")?,
repetition_penalty: number(object, "repetition_penalty")?,
frequency_penalty: number(object, "frequency_penalty")?,
presence_penalty: number(object, "presence_penalty")?,
penalty_last_n: integer(object, "penalty_last_n")?,
seed,
};
sampling.validate()?;
Ok(sampling)
}
/// A short stable error code for a rejected field (gateway error bodies carry codes, not prose).
pub fn error_code(error: &SamplingError) -> &'static str {
match error.field {
"temperature" => "invalid_temperature",
"top_p" => "invalid_top_p",
"top_k" => "invalid_top_k",
"min_p" => "invalid_min_p",
"repetition_penalty" => "invalid_repetition_penalty",
"frequency_penalty" => "invalid_frequency_penalty",
"presence_penalty" => "invalid_presence_penalty",
"penalty_last_n" => "invalid_penalty_last_n",
"seed" => "invalid_seed",
_ => "invalid_sampling",
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn obj(v: Value) -> Map<String, Value> {
v.as_object().unwrap().clone()
}
#[test]
fn decimals_round_trip_through_fixed_point() {
for t in [0.0, 0.1, 0.7, 0.8, 1.0, 1.5, 2.0, 0.123, 0.001] {
let s = RequestSampling {
temperature: Some(t),
..Default::default()
};
let f = to_fixed_point(&s).unwrap();
assert_eq!(
RequestSampling::from_fixed_point(&f).temperature,
Some(t),
"{t}"
);
}
let s = RequestSampling {
temperature: Some(0.6),
top_p: Some(0.95),
top_k: Some(20),
min_p: Some(0.05),
repetition_penalty: Some(1.05),
frequency_penalty: Some(-0.5),
presence_penalty: Some(0.25),
penalty_last_n: Some(256),
seed: Some(99),
};
assert_eq!(
RequestSampling::from_fixed_point(&to_fixed_point(&s).unwrap()),
s
);
}
#[test]
fn values_finer_than_the_wire_are_refused_not_rounded() {
for s in [
RequestSampling {
temperature: Some(0.1234),
..Default::default()
},
RequestSampling {
top_p: Some(0.9999999),
..Default::default()
},
RequestSampling {
frequency_penalty: Some(0.0000001),
..Default::default()
},
] {
assert!(to_fixed_point(&s).is_err(), "{s:?}");
}
}
#[test]
fn out_of_contract_values_are_refused() {
for s in [
RequestSampling {
temperature: Some(2.001),
..Default::default()
},
RequestSampling {
top_p: Some(1.5),
..Default::default()
},
RequestSampling {
penalty_last_n: Some(-1),
..Default::default()
},
] {
assert!(to_fixed_point(&s).is_err());
}
}
#[test]
fn json_fields_are_read_strictly() {
let s = sampling_from_object(&obj(json!({
"temperature": 0.7, "top_p": 0.9, "top_k": 40, "min_p": 0.05, "repetition_penalty": 1.1,
"frequency_penalty": 0.5, "presence_penalty": 0.5, "penalty_last_n": 64, "seed": 7,
"model": "ignored", "temperature_null": null
})))
.unwrap();
assert_eq!(s.top_k, Some(40));
assert_eq!(s.seed, Some(7));
for bad in [
json!({"top_k": 1.5}),
json!({"top_k": "5"}),
json!({"seed": -1}),
json!({"seed": 1.5}),
json!({"temperature": "hot"}),
json!({"temperature": 3}),
json!({"min_p": 2}),
] {
assert!(sampling_from_object(&obj(bad.clone())).is_err(), "{bad}");
}
assert_eq!(
sampling_from_object(&obj(json!({"temperature": null}))).unwrap(),
RequestSampling::default()
);
}
}
+9
View File
@@ -0,0 +1,9 @@
//! Pure Rust ports of the Original Strata serving-layer policies (`engine/strata/serve/*.py` and the
//! host-side parts of `src/program/generate.cpp`). No I/O, no async runtime, no `unsafe`.
//!
//! Each module cites the Original code it transcribes and is tested against fixtures produced by running
//! that code (see `control-plane/tests/golden/gen_goldens.py` and `oracle/`).
pub mod fixed;
pub mod reasoning;
pub mod shared;
+251
View File
@@ -0,0 +1,251 @@
//! Reasoning-budget wrap-up (issue #123 of the Original): `Service.reasoning_budget` and the
//! budget branch of `Service.run` in `serve/server.py`.
//!
//! A request may cap how many tokens the model spends thinking (`reasoning_budget_tokens`, else
//! the config default). When the thinking reaches the cap at a *clean point* - no part of a
//! `</think>` tag held back, no UTF-8 character split across tokens - generation is stopped, the
//! fixed [`WRAP_UP`] text (which ends the thinking the way the model would) is appended to the
//! output, and generation continues from `prompt + generated + wrap-up`, so the engine keeps the
//! prefix it already holds.
//!
//! [`BudgetTracker`] is the pure decision part: feed it each generated token's bytes, it answers
//! when to wrap up. It reproduces the interplay of the Original's incremental UTF-8 `Detokenizer`
//! and `OutputParser` (state `reasoning`, `buf` = a held prefix of `</think>`).
use serde_json::Value;
use crate::shared::py_repr;
/// What closes the thinking when the budget is reached (`REASONING_WRAP_UP`).
pub const WRAP_UP: &str =
"\n\nI have thought about this long enough; time to give my answer.\n</think>\n\n";
const THINK_END: &str = "</think>";
/// `Service.reasoning_budget`: the request's `reasoning_budget_tokens`, else the config's; `0` or
/// less means no budget (so a request can switch a configured one off); anything that is not a
/// whole number is an error (a 400 in the Original).
pub fn parse_budget(
request: Option<&Value>,
config_default: Option<&Value>,
) -> Result<Option<u64>, String> {
let value = match request {
Some(v) if !v.is_null() => Some(v),
_ => config_default.filter(|v| !v.is_null()),
};
let Some(value) = value else {
return Ok(None);
};
let whole = match value {
Value::Number(n) => n
.as_i64()
.map(i128::from)
.or_else(|| n.as_u64().map(i128::from))
.or_else(|| {
n.as_f64()
.filter(|f| f.is_finite() && f.fract() == 0.0 && f.abs() < 1e18)
.map(|f| f as i128)
}),
_ => None,
};
match whole {
Some(n) if n > 0 => Ok(Some(u64::try_from(n).unwrap_or(u64::MAX))),
Some(_) => Ok(None),
None => Err(format!(
"reasoning_budget_tokens={}: expected a whole number of tokens (0: no budget)",
py_repr(value)
)),
}
}
/// The verdict after one generated token.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Verdict {
Continue,
/// Stop now and append [`WRAP_UP`].
WrapUp,
}
#[derive(Clone, Debug)]
pub struct BudgetTracker {
budget: u64,
thought: u64,
reasoning: bool,
/// The parser's `buf` in the reasoning state: a held proper prefix of `</think>`.
held: String,
/// Bytes of a UTF-8 character not yet complete (`Detokenizer.pending`).
partial: Vec<u8>,
}
impl BudgetTracker {
/// `budget` must be positive (a missing budget means no tracker).
pub fn new(budget: u64) -> Self {
Self {
budget,
thought: 0,
reasoning: true,
held: String::new(),
partial: Vec::new(),
}
}
/// Reasoning tokens counted so far.
pub fn thought(&self) -> u64 {
self.thought
}
/// Still inside the thinking (before `</think>`).
pub fn in_reasoning(&self) -> bool {
self.reasoning
}
/// Feed the next generated token's bytes.
pub fn push(&mut self, token: &[u8]) -> Verdict {
if !self.reasoning {
return Verdict::Continue;
}
let text = self.decode(token);
self.held.push_str(&text);
if let Some(at) = self.held.find(THINK_END) {
self.held.drain(..at + THINK_END.len());
self.reasoning = false;
return Verdict::Continue;
}
let keep = hold(&self.held, THINK_END);
let cut = self.held.len() - keep;
self.held.drain(..cut);
self.thought += 1;
if self.thought >= self.budget && self.held.is_empty() && self.partial.is_empty() {
Verdict::WrapUp
} else {
Verdict::Continue
}
}
/// Incremental UTF-8 decode with replacement characters (Python's
/// `codecs.getincrementaldecoder("utf-8")(errors="replace")`).
fn decode(&mut self, token: &[u8]) -> String {
self.partial.extend_from_slice(token);
let mut out = String::new();
loop {
match std::str::from_utf8(&self.partial) {
Ok(valid) => {
out.push_str(valid);
self.partial.clear();
return out;
}
Err(error) => {
let valid = error.valid_up_to();
out.push_str(
std::str::from_utf8(&self.partial[..valid]).expect("valid prefix"),
);
match error.error_len() {
None => {
self.partial.drain(..valid);
return out;
}
Some(bad) => {
out.push('\u{FFFD}');
self.partial.drain(..valid + bad);
}
}
}
}
}
}
}
/// `OutputParser._hold`: the length of the longest suffix of `text` that is a proper prefix of `tag`.
fn hold(text: &str, tag: &str) -> usize {
(1..tag.len())
.rev()
.find(|n| text.ends_with(&tag[..*n]))
.unwrap_or(0)
}
/// What the wrap-up appends, for the caller to turn into token ids.
pub fn wrap_up_text() -> &'static str {
WRAP_UP
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn budget_parsing_follows_the_originals_rules() {
let none = None;
assert_eq!(parse_budget(none, none), Ok(None));
assert_eq!(parse_budget(Some(&json!(20)), none), Ok(Some(20)));
assert_eq!(parse_budget(Some(&json!(20.0)), none), Ok(Some(20)));
assert_eq!(parse_budget(Some(&json!(0)), Some(&json!(50))), Ok(None));
assert_eq!(parse_budget(Some(&json!(-3)), none), Ok(None));
assert_eq!(parse_budget(None, Some(&json!(50))), Ok(Some(50)));
assert_eq!(
parse_budget(Some(&json!(null)), Some(&json!(50))),
Ok(Some(50))
);
for bad in [json!(true), json!("5"), json!(2.5), json!([1])] {
let error = parse_budget(Some(&bad), none).unwrap_err();
assert!(error.starts_with("reasoning_budget_tokens="), "{error}");
assert!(error.ends_with("expected a whole number of tokens (0: no budget)"));
}
assert_eq!(
parse_budget(Some(&json!("5")), none).unwrap_err(),
"reasoning_budget_tokens='5': expected a whole number of tokens (0: no budget)"
);
}
#[test]
fn wraps_up_at_the_budget_on_a_clean_token() {
let mut t = BudgetTracker::new(3);
assert_eq!(t.push(b"a"), Verdict::Continue);
assert_eq!(t.push(b"b"), Verdict::Continue);
assert_eq!(t.push(b"c"), Verdict::WrapUp);
assert_eq!(t.thought(), 3);
}
#[test]
fn a_held_tag_prefix_delays_the_wrap_up() {
let mut t = BudgetTracker::new(2);
assert_eq!(t.push(b"x"), Verdict::Continue);
// the second token ends with "</": held back by the parser, not clean
assert_eq!(t.push(b"</"), Verdict::Continue);
assert_eq!(t.push(b"y"), Verdict::WrapUp);
}
#[test]
fn a_split_character_delays_the_wrap_up() {
let mut t = BudgetTracker::new(1);
assert_eq!(t.push(&[0xC3]), Verdict::Continue);
assert_eq!(t.push(&[0xA9]), Verdict::WrapUp);
}
#[test]
fn closing_the_thinking_ends_the_budget() {
let mut t = BudgetTracker::new(2);
assert_eq!(t.push(b"a"), Verdict::Continue);
assert_eq!(t.push(b"</think>"), Verdict::Continue);
assert!(!t.in_reasoning());
assert_eq!(t.push(b"b"), Verdict::Continue);
assert_eq!(t.push(b"c"), Verdict::Continue);
assert_eq!(t.thought(), 1);
}
#[test]
fn a_tag_split_over_tokens_is_still_found() {
let mut t = BudgetTracker::new(100);
for piece in [&b"</"[..], b"thi", b"nk", b">"] {
let _ = t.push(piece);
}
assert!(!t.in_reasoning());
}
#[test]
fn invalid_utf8_becomes_replacement_characters_not_a_stall() {
let mut t = BudgetTracker::new(2);
assert_eq!(t.push(&[0xFF]), Verdict::Continue);
assert_eq!(t.push(&[0xFF]), Verdict::WrapUp);
}
}
+501
View File
@@ -0,0 +1,501 @@
//! The server-wide Chat settings (`POST /settings`), the run config's `sampling` block, and how
//! both are merged under a request. Port of `serve/server.py` `clean_shared_defaults`,
//! `sampling_defaults_from_config`, `Service.with_shared`, `Service.run`'s default merge and
//! the `defaults` part of `GET /props`.
//!
//! Differences from the Original, all on the safe side:
//!
//! * integers wider than `u64` (a `seed`/`max_tokens`/`top_k` Python would keep as a big int)
//! are rejected;
//! * config `temperature` above 2 is rejected here (the Original accepts any `>= 0` in the
//! config but the request boundary of this port caps `temperature` at 2, so a larger default
//! could never be applied);
//! * error text mirrors the Original's for the common cases and is golden-tested.
use leleka_sampler_ref::RequestSampling;
use leleka_sampler_ref::params::py_float_repr;
use serde_json::{Map, Number, Value};
/// The keys `POST /settings` accepts (`SHARED_KEYS`).
pub const SHARED_KEYS: [&str; 7] = [
"reasoning_effort",
"temperature",
"top_p",
"top_k",
"seed",
"max_tokens",
"experimental_speed_projection",
];
/// `clean_shared_defaults` output: only the keys a client set.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SharedDefaults {
pub reasoning_effort: Option<String>,
pub temperature: Option<f64>,
pub top_p: Option<f64>,
pub top_k: Option<i64>,
pub seed: Option<u64>,
pub max_tokens: Option<u64>,
pub experimental_speed_projection: Option<bool>,
}
impl SharedDefaults {
pub fn is_empty(&self) -> bool {
*self == Self::default()
}
/// The JSON object `/settings` answers with and persists (`defaults`).
pub fn to_json(&self) -> Value {
let mut out = Map::new();
if let Some(v) = &self.reasoning_effort {
out.insert("reasoning_effort".into(), Value::String(v.clone()));
}
if let Some(v) = self.temperature {
out.insert("temperature".into(), float_value(v));
}
if let Some(v) = self.top_p {
out.insert("top_p".into(), float_value(v));
}
if let Some(v) = self.top_k {
out.insert("top_k".into(), Value::from(v));
}
if let Some(v) = self.seed {
out.insert("seed".into(), Value::from(v));
}
if let Some(v) = self.max_tokens {
out.insert("max_tokens".into(), Value::from(v));
}
if let Some(v) = self.experimental_speed_projection {
out.insert("experimental_speed_projection".into(), Value::Bool(v));
}
Value::Object(out)
}
/// The sampling subset the shared settings carry.
pub fn sampling(&self) -> RequestSampling {
RequestSampling {
temperature: self.temperature,
top_p: self.top_p,
top_k: self.top_k,
seed: self.seed,
..Default::default()
}
}
}
fn float_value(v: f64) -> Value {
Number::from_f64(v).map_or(Value::Null, Value::Number)
}
/// Python's `repr()` of a JSON-ish value, for the Original's error text.
pub fn py_repr(value: &Value) -> String {
match value {
Value::Null => "None".into(),
Value::Bool(true) => "True".into(),
Value::Bool(false) => "False".into(),
Value::Number(n) => match n.as_i64() {
Some(i) => i.to_string(),
None => match n.as_u64() {
Some(u) => u.to_string(),
None => py_float_repr(n.as_f64().unwrap_or(f64::NAN)),
},
},
Value::String(s) => py_str_repr(s),
Value::Array(items) => format!(
"[{}]",
items.iter().map(py_repr).collect::<Vec<_>>().join(", ")
),
Value::Object(map) => format!(
"{{{}}}",
map.iter()
.map(|(k, v)| format!("{}: {}", py_str_repr(k), py_repr(v)))
.collect::<Vec<_>>()
.join(", ")
),
}
}
/// Python's `repr(str)`: single quotes unless the text has a single and no double quote.
pub fn py_str_repr(s: &str) -> String {
let quote = if s.contains('\'') && !s.contains('"') {
'"'
} else {
'\''
};
let mut out = String::new();
out.push(quote);
for c in s.chars() {
match c {
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if c == quote => {
out.push('\\');
out.push(c);
}
c if (c as u32) < 0x20 || c as u32 == 0x7f => {
out.push_str(&format!("\\x{:02x}", c as u32));
}
c => out.push(c),
}
}
out.push(quote);
out
}
fn is_number(v: &Value) -> bool {
v.is_number()
}
fn as_f64(v: &Value) -> Option<f64> {
v.as_f64()
}
/// An integral number as `i128`, or `None`.
fn integral(v: &Value) -> Option<i128> {
if let Some(i) = v.as_i64() {
return Some(i128::from(i));
}
if let Some(u) = v.as_u64() {
return Some(i128::from(u));
}
let f = v.as_f64()?;
(f.is_finite() && f.fract() == 0.0 && f.abs() < 1e18).then_some(f as i128)
}
/// `clean_shared_defaults`: `Ok` with only the known, valid keys; `Err` names the first bad one
/// (the message the Original's `ValueError` carries).
pub fn clean_shared_defaults(defaults: &Value) -> Result<SharedDefaults, String> {
let map = match defaults {
Value::Null => return Ok(SharedDefaults::default()),
Value::Object(map) => map,
_ => return Err("defaults must be an object".into()),
};
let mut out = SharedDefaults::default();
for (key, value) in map {
if value.is_null() || value.as_str() == Some("") {
continue;
}
match key.as_str() {
"reasoning_effort" => match value.as_str() {
Some(e @ ("none" | "low" | "medium" | "high")) => {
out.reasoning_effort = Some(e.to_owned());
}
_ => return Err("reasoning_effort: none, low, medium or high".into()),
},
"temperature" => match as_f64(value) {
Some(t) if is_number(value) && (0.0..=2.0).contains(&t) => {
out.temperature = Some(t)
}
_ => return Err("temperature: 0..2".into()),
},
"top_p" => match as_f64(value) {
Some(p) if is_number(value) && p > 0.0 && p <= 1.0 => out.top_p = Some(p),
_ => return Err("top_p: 0 < top_p <= 1".into()),
},
"top_k" => match integral(value) {
Some(k) if is_number(value) && (1..=64).contains(&k) => out.top_k = Some(k as i64),
_ => return Err("top_k: an integer 1..64".into()),
},
"seed" => match integral(value) {
Some(s) if is_number(value) && s > 0 && s <= i128::from(u64::MAX) => {
out.seed = Some(s as u64);
}
_ => return Err("seed: a positive integer".into()),
},
"max_tokens" => match integral(value) {
Some(s) if is_number(value) && s > 0 && s <= i128::from(u64::MAX) => {
out.max_tokens = Some(s as u64);
}
_ => return Err("max_tokens: a positive integer".into()),
},
"experimental_speed_projection" => match value.as_bool() {
Some(b) => out.experimental_speed_projection = Some(b),
None => return Err("experimental_speed_projection: true or false".into()),
},
other => return Err(format!("unknown setting {}", py_str_repr(other))),
}
}
Ok(out)
}
/// The run config's `sampling` block (`sampling_defaults_from_config`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ConfigSampling {
pub sampling: RequestSampling,
pub experimental_speed_projection: Option<bool>,
/// Keys the Original names at startup and ignores.
pub ignored: Vec<String>,
}
fn config_error(key: &str, value: &Value, expected: &str) -> String {
format!(
"[strata] config sampling.{key}={}: {expected}",
py_repr(value)
)
}
/// Parse the config's `sampling` object. A bad value is an error (the Original stops the start).
pub fn sampling_defaults_from_config(block: &Value) -> Result<ConfigSampling, String> {
let map = match block {
Value::Null => return Ok(ConfigSampling::default()),
Value::Object(map) => map,
_ => return Err("[strata] config sampling: expected an object".into()),
};
let mut out = ConfigSampling::default();
for (key, value) in map {
if value.is_null() {
continue;
}
let number = is_number(value);
let f = as_f64(value).filter(|_| number);
match key.as_str() {
"temperature" => match f {
Some(v) if v >= 0.0 => out.sampling.temperature = Some(v),
_ => {
return Err(config_error(
key,
value,
"expected a number >= 0 (0 = greedy)",
));
}
},
"top_p" => match f {
Some(v) if v > 0.0 && v <= 1.0 => out.sampling.top_p = Some(v),
_ => return Err(config_error(key, value, "expected 0 < top_p <= 1")),
},
"min_p" => match f {
Some(v) if (0.0..=1.0).contains(&v) => out.sampling.min_p = Some(v),
_ => return Err(config_error(key, value, "expected 0 <= min_p <= 1")),
},
"top_k" => match integral(value) {
Some(k) if number && (1..=64).contains(&k) => out.sampling.top_k = Some(k as i64),
_ => {
return Err(config_error(
key,
value,
"the sampled path takes an integer 1..64",
));
}
},
"presence_penalty" => match f {
Some(v) if v >= 0.0 => out.sampling.presence_penalty = Some(v),
_ => return Err(config_error(key, value, "expected a number >= 0")),
},
"frequency_penalty" => match f {
Some(v) if v >= 0.0 => out.sampling.frequency_penalty = Some(v),
_ => return Err(config_error(key, value, "expected a number >= 0")),
},
"repetition_penalty" => match f {
Some(v) if v > 0.0 => out.sampling.repetition_penalty = Some(v),
_ => return Err(config_error(key, value, "expected a number > 0 (1 = off)")),
},
"penalty_last_n" => match integral(value) {
Some(n) if number && (0..=i128::from(i32::MAX)).contains(&n) => {
out.sampling.penalty_last_n = Some(n as i64);
}
_ => {
return Err(config_error(key, value, "expected a non-negative integer"));
}
},
"seed" => match integral(value) {
Some(s) if number && s > 0 && s <= i128::from(u64::MAX) => {
out.sampling.seed = Some(s as u64);
}
_ => return Err(config_error(key, value, "expected a positive integer")),
},
"experimental_speed_projection" => match value.as_bool() {
Some(b) => out.experimental_speed_projection = Some(b),
None => {
return Err(config_error(
key,
value,
"expected true or false (the default for requests that leave it out, when the engine has the vector)",
));
}
},
other => out.ignored.push(other.to_owned()),
}
}
// The request boundary of this port refuses temperatures above 2; a default must be usable.
out.sampling
.validate_config_defaults()
.map_err(|e| format!("[strata] config sampling.{}: {}", e.field, e.expected))?;
Ok(out)
}
/// The defaults a request starts from: the config block, then the shared settings on top
/// (`{**sampling_defaults, **shared}`). The speed-projection default comes the same way.
pub fn merged_defaults(config: &ConfigSampling, shared: &SharedDefaults) -> MergedDefaults {
MergedDefaults {
sampling: RequestSampling::overlay(&config.sampling, &shared.sampling()),
experimental_speed_projection: shared
.experimental_speed_projection
.or(config.experimental_speed_projection),
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct MergedDefaults {
pub sampling: RequestSampling,
pub experimental_speed_projection: Option<bool>,
}
impl MergedDefaults {
/// `default_generation_settings.params` of `GET /props` (llama-server names).
pub fn props_params(&self, shared: &SharedDefaults) -> Value {
let mut params = Map::new();
let s = &self.sampling;
let mut put = |name: &str, value: Option<Value>| {
if let Some(v) = value {
params.insert(name.to_owned(), v);
}
};
put("temperature", s.temperature.map(float_value));
put("top_p", s.top_p.map(float_value));
put("top_k", s.top_k.map(Value::from));
put("min_p", s.min_p.map(float_value));
put("seed", s.seed.map(Value::from));
put("repeat_penalty", s.repetition_penalty.map(float_value));
put("presence_penalty", s.presence_penalty.map(float_value));
put("frequency_penalty", s.frequency_penalty.map(float_value));
put("repeat_last_n", s.penalty_last_n.map(Value::from));
params.insert(
"n_predict".into(),
shared.max_tokens.map_or(Value::from(-1), Value::from),
);
Value::Object(params)
}
}
/// `with_shared`, `max_tokens` half: the shared limit when the request has none of its own.
pub fn shared_max_tokens(request_max: Option<u64>, shared: &SharedDefaults) -> Option<u64> {
match request_max {
Some(n) if n > 0 => Some(n),
_ => shared.max_tokens.or(request_max),
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn unknown_keys_are_refused_unless_their_value_is_empty() {
let d = clean_shared_defaults(&json!({"top_p": null, "x": null, "min_p": ""})).unwrap();
assert!(d.is_empty());
assert_eq!(
clean_shared_defaults(&json!({"min_p": 0.1})),
Err("unknown setting 'min_p'".to_owned())
);
}
#[test]
fn empty_and_null_values_are_dropped() {
let d = clean_shared_defaults(&json!({"temperature": "", "top_p": null})).unwrap();
assert!(d.is_empty());
assert!(clean_shared_defaults(&Value::Null).unwrap().is_empty());
assert!(clean_shared_defaults(&json!([1])).is_err());
}
#[test]
fn valid_values_are_normalised_like_the_original() {
let d = clean_shared_defaults(&json!({"temperature": 1, "top_k": 40.0, "seed": 7,
"reasoning_effort": "high", "max_tokens": 100, "top_p": 1}))
.unwrap();
assert_eq!(d.temperature, Some(1.0));
assert_eq!(d.top_k, Some(40));
assert_eq!(d.seed, Some(7));
assert_eq!(d.max_tokens, Some(100));
assert_eq!(d.top_p, Some(1.0));
assert_eq!(
d.to_json(),
json!({"reasoning_effort": "high", "temperature": 1.0, "top_p": 1.0, "top_k": 40,
"seed": 7, "max_tokens": 100})
);
}
#[test]
fn config_block_checks_the_originals_ranges() {
let c = sampling_defaults_from_config(&json!({"temperature": 0.7, "top_p": 0.9,
"top_k": 40, "min_p": 0.05, "presence_penalty": 0.5, "repetition_penalty": 1.1,
"frequency_penalty": 0.0, "penalty_last_n": 128, "seed": 5,
"experimental_speed_projection": true, "nonsense": 1}))
.unwrap();
assert_eq!(c.sampling.top_k, Some(40));
assert_eq!(c.ignored, vec!["nonsense".to_owned()]);
assert_eq!(c.experimental_speed_projection, Some(true));
for (key, bad) in [
("temperature", json!(-1)),
("top_p", json!(0)),
("min_p", json!(1.5)),
("top_k", json!(0)),
("top_k", json!(65)),
("top_k", json!(1.5)),
("presence_penalty", json!(-0.1)),
("repetition_penalty", json!(0)),
("penalty_last_n", json!(-1)),
("seed", json!(0)),
("seed", json!(true)),
("experimental_speed_projection", json!(1)),
] {
assert!(
sampling_defaults_from_config(&json!({ key: bad.clone() })).is_err(),
"{key}={bad}"
);
}
}
#[test]
fn shared_wins_over_config_and_the_request_wins_over_both() {
let config =
sampling_defaults_from_config(&json!({"temperature": 0.3, "min_p": 0.1})).unwrap();
let shared = clean_shared_defaults(&json!({"temperature": 0.9, "seed": 4})).unwrap();
let merged = merged_defaults(&config, &shared);
assert_eq!(merged.sampling.temperature, Some(0.9));
assert_eq!(merged.sampling.min_p, Some(0.1));
assert_eq!(merged.sampling.seed, Some(4));
let request = RequestSampling {
temperature: Some(0.0),
..Default::default()
};
let effective = RequestSampling::overlay(&merged.sampling, &request);
assert_eq!(effective.temperature, Some(0.0), "explicit 0 stays greedy");
assert_eq!(effective.min_p, Some(0.1));
}
#[test]
fn props_params_use_llama_server_names() {
let config = sampling_defaults_from_config(
&json!({"repetition_penalty": 1.1, "penalty_last_n": 64}),
)
.unwrap();
let shared = clean_shared_defaults(&json!({"max_tokens": 512})).unwrap();
let params = merged_defaults(&config, &shared).props_params(&shared);
assert_eq!(
params,
json!({"repeat_penalty": 1.1, "repeat_last_n": 64, "n_predict": 512})
);
}
#[test]
fn python_repr_of_values() {
assert_eq!(py_repr(&json!(true)), "True");
assert_eq!(py_repr(&json!(null)), "None");
assert_eq!(py_repr(&json!("it's")), "\"it's\"");
assert_eq!(py_repr(&json!(1.5)), "1.5");
assert_eq!(py_repr(&json!([1, "a"])), "[1, 'a']");
assert_eq!(py_repr(&json!({"a": 1})), "{'a': 1}");
}
#[test]
fn shared_max_tokens_only_fills_a_missing_limit() {
let shared = clean_shared_defaults(&json!({"max_tokens": 77})).unwrap();
assert_eq!(shared_max_tokens(None, &shared), Some(77));
assert_eq!(shared_max_tokens(Some(0), &shared), Some(77));
assert_eq!(shared_max_tokens(Some(5), &shared), Some(5));
assert_eq!(shared_max_tokens(None, &SharedDefaults::default()), None);
}
}
File diff suppressed because it is too large Load Diff
+631
View File
@@ -0,0 +1,631 @@
{
"source": "serve/server.py clean_shared_defaults / sampling_defaults_from_config (real code)",
"clean": [
{
"input": null,
"ok": {}
},
{
"input": {},
"ok": {}
},
{
"input": [],
"error": "defaults must be an object"
},
{
"input": "x",
"error": "defaults must be an object"
},
{
"input": 5,
"error": "defaults must be an object"
},
{
"input": {
"temperature": 0.7
},
"ok": {
"temperature": 0.7
}
},
{
"input": {
"temperature": 1
},
"ok": {
"temperature": 1.0
}
},
{
"input": {
"temperature": 0
},
"ok": {
"temperature": 0.0
}
},
{
"input": {
"temperature": 2
},
"ok": {
"temperature": 2.0
}
},
{
"input": {
"temperature": 2.5
},
"error": "temperature: 0..2"
},
{
"input": {
"temperature": -0.1
},
"error": "temperature: 0..2"
},
{
"input": {
"temperature": true
},
"error": "temperature: 0..2"
},
{
"input": {
"temperature": "0.5"
},
"error": "temperature: 0..2"
},
{
"input": {
"top_p": 0.9
},
"ok": {
"top_p": 0.9
}
},
{
"input": {
"top_p": 1
},
"ok": {
"top_p": 1.0
}
},
{
"input": {
"top_p": 0
},
"error": "top_p: 0 < top_p <= 1"
},
{
"input": {
"top_p": 1.5
},
"error": "top_p: 0 < top_p <= 1"
},
{
"input": {
"top_p": false
},
"error": "top_p: 0 < top_p <= 1"
},
{
"input": {
"top_k": 40
},
"ok": {
"top_k": 40
}
},
{
"input": {
"top_k": 40.0
},
"ok": {
"top_k": 40
}
},
{
"input": {
"top_k": 40.5
},
"error": "top_k: an integer 1..64"
},
{
"input": {
"top_k": 0
},
"error": "top_k: an integer 1..64"
},
{
"input": {
"top_k": 64
},
"ok": {
"top_k": 64
}
},
{
"input": {
"top_k": 65
},
"error": "top_k: an integer 1..64"
},
{
"input": {
"top_k": "40"
},
"error": "top_k: an integer 1..64"
},
{
"input": {
"seed": 7
},
"ok": {
"seed": 7
}
},
{
"input": {
"seed": 7.0
},
"ok": {
"seed": 7
}
},
{
"input": {
"seed": 0
},
"error": "seed: a positive integer"
},
{
"input": {
"seed": -3
},
"error": "seed: a positive integer"
},
{
"input": {
"seed": 1.5
},
"error": "seed: a positive integer"
},
{
"input": {
"seed": 18446744073709551615
},
"ok": {
"seed": 18446744073709551615
}
},
{
"input": {
"max_tokens": 512
},
"ok": {
"max_tokens": 512
}
},
{
"input": {
"max_tokens": 0
},
"error": "max_tokens: a positive integer"
},
{
"input": {
"max_tokens": "10"
},
"error": "max_tokens: a positive integer"
},
{
"input": {
"reasoning_effort": "none"
},
"ok": {
"reasoning_effort": "none"
}
},
{
"input": {
"reasoning_effort": "low"
},
"ok": {
"reasoning_effort": "low"
}
},
{
"input": {
"reasoning_effort": "medium"
},
"ok": {
"reasoning_effort": "medium"
}
},
{
"input": {
"reasoning_effort": "high"
},
"ok": {
"reasoning_effort": "high"
}
},
{
"input": {
"reasoning_effort": "xhigh"
},
"error": "reasoning_effort: none, low, medium or high"
},
{
"input": {
"reasoning_effort": 3
},
"error": "reasoning_effort: none, low, medium or high"
},
{
"input": {
"experimental_speed_projection": true
},
"ok": {
"experimental_speed_projection": true
}
},
{
"input": {
"experimental_speed_projection": false
},
"ok": {
"experimental_speed_projection": false
}
},
{
"input": {
"experimental_speed_projection": 1
},
"error": "experimental_speed_projection: true or false"
},
{
"input": {
"temperature": null,
"top_p": "",
"top_k": null
},
"ok": {}
},
{
"input": {
"unknown": 1
},
"error": "unknown setting 'unknown'"
},
{
"input": {
"unknown": null
},
"ok": {}
},
{
"input": {
"min_p": 0.1
},
"error": "unknown setting 'min_p'"
},
{
"input": {
"temperature": 0.7,
"top_p": 0.9,
"top_k": 20,
"seed": 11,
"max_tokens": 100,
"reasoning_effort": "medium",
"experimental_speed_projection": false
},
"ok": {
"temperature": 0.7,
"top_p": 0.9,
"top_k": 20,
"seed": 11,
"max_tokens": 100,
"reasoning_effort": "medium",
"experimental_speed_projection": false
}
}
],
"config": [
{
"input": null,
"ok": {},
"ignored": []
},
{
"input": {},
"ok": {},
"ignored": []
},
{
"input": {
"temperature": 0.7
},
"ok": {
"temperature": 0.7
},
"ignored": []
},
{
"input": {
"temperature": 0
},
"ok": {
"temperature": 0.0
},
"ignored": []
},
{
"input": {
"temperature": -1
},
"error": "[strata] config sampling.temperature=-1: expected a number >= 0 (0 = greedy)"
},
{
"input": {
"temperature": true
},
"error": "[strata] config sampling.temperature=True: expected a number >= 0 (0 = greedy)"
},
{
"input": {
"top_p": 0.95
},
"ok": {
"top_p": 0.95
},
"ignored": []
},
{
"input": {
"top_p": 0
},
"error": "[strata] config sampling.top_p=0: expected 0 < top_p <= 1"
},
{
"input": {
"top_p": 1.01
},
"error": "[strata] config sampling.top_p=1.01: expected 0 < top_p <= 1"
},
{
"input": {
"min_p": 0.05
},
"ok": {
"min_p": 0.05
},
"ignored": []
},
{
"input": {
"min_p": 0
},
"ok": {
"min_p": 0.0
},
"ignored": []
},
{
"input": {
"min_p": 2
},
"error": "[strata] config sampling.min_p=2: expected 0 <= min_p <= 1"
},
{
"input": {
"top_k": 40
},
"ok": {
"top_k": 40
},
"ignored": []
},
{
"input": {
"top_k": 0
},
"error": "[strata] config sampling.top_k=0: the sampled path takes an integer 1..64"
},
{
"input": {
"top_k": 65
},
"error": "[strata] config sampling.top_k=65: the sampled path takes an integer 1..64"
},
{
"input": {
"top_k": 20.0
},
"ok": {
"top_k": 20
},
"ignored": []
},
{
"input": {
"top_k": 1.5
},
"error": "[strata] config sampling.top_k=1.5: the sampled path takes an integer 1..64"
},
{
"input": {
"presence_penalty": 0.5
},
"ok": {
"presence_penalty": 0.5
},
"ignored": []
},
{
"input": {
"presence_penalty": -0.5
},
"error": "[strata] config sampling.presence_penalty=-0.5: expected a number >= 0"
},
{
"input": {
"frequency_penalty": 0.25
},
"ok": {
"frequency_penalty": 0.25
},
"ignored": []
},
{
"input": {
"frequency_penalty": -1
},
"error": "[strata] config sampling.frequency_penalty=-1: expected a number >= 0"
},
{
"input": {
"repetition_penalty": 1.1
},
"ok": {
"repetition_penalty": 1.1
},
"ignored": []
},
{
"input": {
"repetition_penalty": 0
},
"error": "[strata] config sampling.repetition_penalty=0: expected a number > 0 (1 = off)"
},
{
"input": {
"penalty_last_n": 128
},
"ok": {
"penalty_last_n": 128
},
"ignored": []
},
{
"input": {
"penalty_last_n": 0
},
"ok": {
"penalty_last_n": 0
},
"ignored": []
},
{
"input": {
"penalty_last_n": -2
},
"error": "[strata] config sampling.penalty_last_n=-2: expected a non-negative integer"
},
{
"input": {
"penalty_last_n": 1.5
},
"error": "[strata] config sampling.penalty_last_n=1.5: expected a non-negative integer"
},
{
"input": {
"seed": 5
},
"ok": {
"seed": 5
},
"ignored": []
},
{
"input": {
"seed": 0
},
"error": "[strata] config sampling.seed=0: expected a positive integer"
},
{
"input": {
"seed": 5.5
},
"error": "[strata] config sampling.seed=5.5: expected a positive integer"
},
{
"input": {
"seed": "5"
},
"error": "[strata] config sampling.seed='5': expected a positive integer"
},
{
"input": {
"experimental_speed_projection": true
},
"ok": {
"experimental_speed_projection": true
},
"ignored": []
},
{
"input": {
"experimental_speed_projection": "yes"
},
"error": "[strata] config sampling.experimental_speed_projection='yes': expected true or false (the default for requests that leave it out, when the engine has the vector)"
},
{
"input": {
"temperature": null,
"top_p": null
},
"ok": {},
"ignored": []
},
{
"input": {
"nonsense": 3
},
"ok": {},
"ignored": [
"[strata] config sampling.nonsense=3: unknown key, ignored"
]
},
{
"input": {
"temperature": 0.6,
"nonsense": 3
},
"ok": {
"temperature": 0.6
},
"ignored": [
"[strata] config sampling.nonsense=3: unknown key, ignored"
]
},
{
"input": {
"temperature": 0.6,
"top_p": 0.9,
"top_k": 30,
"min_p": 0.02,
"presence_penalty": 0.1,
"frequency_penalty": 0.1,
"repetition_penalty": 1.05,
"penalty_last_n": 64,
"seed": 9
},
"ok": {
"temperature": 0.6,
"top_p": 0.9,
"top_k": 30,
"min_p": 0.02,
"presence_penalty": 0.1,
"frequency_penalty": 0.1,
"repetition_penalty": 1.05,
"penalty_last_n": 64,
"seed": 9
},
"ignored": []
}
]
}
@@ -0,0 +1,75 @@
//! `BudgetTracker` and `parse_budget` against the Original's real `Detokenizer` + `OutputParser` loop and
//! `Service.reasoning_budget` (fixture from `control-plane/tests/golden/gen_goldens.py reasoning`).
use leleka_serving_policy::reasoning::{BudgetTracker, Verdict, WRAP_UP, parse_budget};
use serde_json::Value;
fn fixture() -> Value {
serde_json::from_str(include_str!("fixtures/reasoning.json")).unwrap()
}
fn unhex(text: &str) -> Vec<u8> {
(0..text.len() / 2)
.map(|i| u8::from_str_radix(&text[2 * i..2 * i + 2], 16).unwrap())
.collect()
}
#[test]
fn wrap_up_text_is_the_originals() {
assert_eq!(fixture()["wrap_up"].as_str().unwrap(), WRAP_UP);
}
#[test]
fn wrap_up_points_equal_python_for_every_sequence_and_budget() {
let fixture = fixture();
let mut wrapped = 0;
let mut unwrapped = 0;
for case in fixture["cases"].as_array().unwrap() {
let pieces: Vec<Vec<u8>> = case["pieces_hex"]
.as_array()
.unwrap()
.iter()
.map(|v| unhex(v.as_str().unwrap()))
.collect();
for (budget, want) in case["wrap_at"].as_object().unwrap() {
let mut tracker = BudgetTracker::new(budget.parse().unwrap());
let mut got = None;
for (index, piece) in pieces.iter().enumerate() {
if tracker.push(piece) == Verdict::WrapUp {
got = Some(index as u64);
break;
}
}
assert_eq!(
got,
want.as_u64(),
"budget {budget} pieces {:?}",
case["pieces_hex"]
);
if got.is_some() {
wrapped += 1;
} else {
unwrapped += 1;
}
}
}
assert!(wrapped > 100 && unwrapped > 50, "{wrapped} {unwrapped}");
}
#[test]
fn budget_parsing_equals_python() {
for case in fixture()["parse"].as_array().unwrap() {
let request = case["request"].get("reasoning_budget_tokens");
let default = case["default"].clone();
let got = parse_budget(request, Some(&default));
match (case.get("ok"), case.get("error")) {
(Some(ok), None) => assert_eq!(
got.unwrap().map(Value::from).unwrap_or(Value::Null),
*ok,
"{case}"
),
(None, Some(error)) => assert_eq!(got.unwrap_err(), error.as_str().unwrap(), "{case}"),
_ => unreachable!(),
}
}
}
@@ -0,0 +1,79 @@
//! `clean_shared_defaults` / `sampling_defaults_from_config` against the Original's real Python output
//! (fixture from `control-plane/tests/golden/gen_goldens.py shared`).
use leleka_serving_policy::shared::{clean_shared_defaults, sampling_defaults_from_config};
use serde_json::{Value, json};
fn fixture() -> Value {
serde_json::from_str(include_str!("fixtures/shared.json")).unwrap()
}
#[test]
fn settings_cleaning_equals_python() {
let fixture = fixture();
let mut agreed_errors = 0;
for case in fixture["clean"].as_array().unwrap() {
let input = &case["input"];
let got = clean_shared_defaults(input);
match (case.get("ok"), case.get("error")) {
(Some(ok), None) => {
let got = got.unwrap_or_else(|e| panic!("{input}: unexpected error {e}"));
assert_eq!(&got.to_json(), ok, "{input}");
}
(None, Some(error)) => {
assert_eq!(got.unwrap_err(), error.as_str().unwrap(), "{input}");
agreed_errors += 1;
}
_ => unreachable!(),
}
}
assert!(agreed_errors >= 20);
}
#[test]
fn config_sampling_block_equals_python() {
let fixture = fixture();
let mut agreed_errors = 0;
for case in fixture["config"].as_array().unwrap() {
let input = case["input"].clone();
let got = sampling_defaults_from_config(&input);
match (case.get("ok"), case.get("error")) {
(Some(ok), None) => {
let got = got.unwrap_or_else(|e| panic!("{input}: unexpected error {e}"));
// Python returns the dict of accepted keys: compare through the same names.
let s = &got.sampling;
let mut mine = serde_json::Map::new();
let mut put = |k: &str, v: Option<Value>| {
if let Some(v) = v {
mine.insert(k.into(), v);
}
};
put("temperature", s.temperature.map(|v| json!(v)));
put("top_p", s.top_p.map(|v| json!(v)));
put("min_p", s.min_p.map(|v| json!(v)));
put("top_k", s.top_k.map(|v| json!(v)));
put("presence_penalty", s.presence_penalty.map(|v| json!(v)));
put("frequency_penalty", s.frequency_penalty.map(|v| json!(v)));
put("repetition_penalty", s.repetition_penalty.map(|v| json!(v)));
put("penalty_last_n", s.penalty_last_n.map(|v| json!(v)));
put("seed", s.seed.map(|v| json!(v)));
put(
"experimental_speed_projection",
got.experimental_speed_projection.map(|v| json!(v)),
);
assert_eq!(&Value::Object(mine), ok, "{input}");
assert_eq!(
got.ignored.len(),
case["ignored"].as_array().unwrap().len(),
"{input}"
);
}
(None, Some(error)) => {
assert_eq!(got.unwrap_err(), error.as_str().unwrap(), "{input}");
agreed_errors += 1;
}
_ => unreachable!(),
}
}
assert!(agreed_errors >= 14);
}
+2
View File
@@ -11,6 +11,8 @@ path = "src/main.rs"
[dependencies]
leleka-backend-api = { path = "../crates/backend-api" }
leleka-runtime = { path = "../crates/leleka-runtime" }
leleka-sampler-ref = { path = "../crates/sampler-ref" }
leleka-serving-policy = { path = "../crates/serving-policy" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sysinfo = { version = "0.39.6", default-features = false, features = ["system"] }
+11
View File
@@ -67,6 +67,17 @@ message OperationResult {
message GenerateRequest {
string request_id = 1; string expected_epoch = 2; string handle = 3;
string prompt = 4; uint32 max_output_tokens = 5; uint32 temperature_milli = 6;
// Remaining Original sampling controls (fixed point; an absent field keeps the Original's default).
// top_p/min_p/repetition_penalty are millionths, frequency/presence penalties signed millionths;
// top_k 0 or above 64 selects the widest list; seed absent or 0 draws a fresh seed per request.
optional uint32 top_p_micro = 7;
optional uint32 top_k = 8;
optional uint32 min_p_micro = 9;
optional uint32 repetition_penalty_micro = 10;
optional sint32 frequency_penalty_micro = 11;
optional sint32 presence_penalty_micro = 12;
optional uint32 penalty_last_n = 13;
optional uint64 seed = 14;
}
message CancelRequest { string request_id = 1; string expected_epoch = 2; }
message CancelAck { string request_id = 1; string epoch = 2; bool acknowledged = 3; }
+1
View File
@@ -11,6 +11,7 @@ pub mod remote;
pub mod runtime_client;
pub mod runtime_gateway;
pub mod runtime_rpc;
mod runtime_sampling;
pub mod runtime_tool_response;
pub mod runtime_tools;
// Reuse the verified pure Rust template; no control-plane crate/C bridge link.
+1
View File
@@ -522,6 +522,7 @@ mod tests {
prompt: String::new(),
max_output_tokens: 1,
temperature_milli: 0,
..Default::default()
})
.await
.unwrap();
+54 -22
View File
@@ -13,6 +13,7 @@ use axum::{
response::{IntoResponse, Response},
routing::{get, post},
};
use leleka_sampler_ref::params::FixedPoint;
use serde::Deserialize;
use serde_json::{Value, json};
use std::{collections::HashSet, net::SocketAddr, sync::Arc, time::Duration};
@@ -418,12 +419,12 @@ async fn status(State(r): State<Registry>, h: HeaderMap) -> Response {
}
Json(json!({"schema_version":1,"runtimes":states})).into_response()
}
fn render(v: &Value) -> Result<(String, u32), &'static str> {
fn render(v: &Value) -> Result<(String, u32, FixedPoint), &'static str> {
let o = v.as_object().ok_or("invalid_json")?;
for (key, value) in o {
match key.as_str() {
"model" | "input" | "instructions" | "stream" | "max_output_tokens" => {}
"temperature" if value.as_f64() == Some(0.0) => {}
key if leleka_serving_policy::fixed::SAMPLING_KEYS.contains(&key) => {}
"store" if value == &Value::Bool(false) => {}
"tools" if value.as_array().is_some_and(Vec::is_empty) => {}
"text" if value == &json!({"format":{"type":"text"}}) => {}
@@ -433,6 +434,7 @@ fn render(v: &Value) -> Result<(String, u32), &'static str> {
if o.get("stream").is_some_and(|v| !v.is_boolean()) {
return Err("invalid_stream");
}
let sampling = crate::runtime_sampling::from_json(o)?;
let cap = o
.get("max_output_tokens")
.map(|v| v.as_u64().ok_or("invalid_output_limit"))
@@ -507,7 +509,7 @@ fn render(v: &Value) -> Result<(String, u32), &'static str> {
if prompt.len() > 1024 * 1024 {
return Err("prompt_limit");
}
Ok((prompt, cap as u32))
Ok((prompt, cap as u32, sampling))
}
fn response_value(id: &str, model: &str, text: &str, status: &str, usage: &proto::Usage) -> Value {
json!({"id":id,"object":"response","created_at":std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0,|v|v.as_secs()),"model":model,"status":status,"output":[{"id":format!("msg_{id}"),"type":"message","role":"assistant","status":status,"content":[{"type":"output_text","text":text,"annotations":[]}]}],"usage":{"input_tokens":usage.input_tokens,"output_tokens":usage.output_tokens,"total_tokens":usage.input_tokens.saturating_add(usage.output_tokens),"input_tokens_details":{"cached_tokens":usage.reused_input_tokens}},"error":null,"incomplete_details":if status=="incomplete"{json!({"reason":"max_output_tokens"})}else{Value::Null}})
@@ -638,7 +640,7 @@ async fn responses(State(r): State<Registry>, h: HeaderMap, body: Bytes) -> Resp
if r.0.experimental_native_tools && needs_tool_adapter(&v) {
return tool_responses(r, index, v).await;
}
let (prompt, cap) = match render(&v) {
let (prompt, cap, sampling) = match render(&v) {
Ok(v) => v,
Err(e) => return error(StatusCode::BAD_REQUEST, e),
};
@@ -649,19 +651,16 @@ async fn responses(State(r): State<Registry>, h: HeaderMap, body: Bytes) -> Resp
return error(StatusCode::SERVICE_UNAVAILABLE, "model_not_ready");
};
let request_id = uuid::Uuid::new_v4().to_string();
let stream = match accepted(
&mut client,
proto::GenerateRequest {
request_id: request_id.clone(),
expected_epoch: snapshot.epoch,
handle: loaded.handle,
prompt,
max_output_tokens: cap,
temperature_milli: 0,
},
)
.await
{
let mut generate = proto::GenerateRequest {
request_id: request_id.clone(),
expected_epoch: snapshot.epoch,
handle: loaded.handle,
prompt,
max_output_tokens: cap,
..Default::default()
};
crate::runtime_sampling::apply(&mut generate, &sampling);
let stream = match accepted(&mut client, generate).await {
Ok(s) => s,
Err(_) => return error(StatusCode::BAD_GATEWAY, "runtime_dispatch_failed"),
};
@@ -869,14 +868,15 @@ async fn tool_responses(registry: Registry, index: usize, value: Value) -> Respo
return error(StatusCode::SERVICE_UNAVAILABLE, "model_not_ready");
};
let request_id = uuid::Uuid::new_v4().to_string();
let request = proto::GenerateRequest {
let mut request = proto::GenerateRequest {
request_id: request_id.clone(),
expected_epoch: snapshot.epoch,
handle: loaded.handle,
prompt: plan.prompt.clone(),
max_output_tokens: plan.max_output_tokens,
temperature_milli: 0,
..Default::default()
};
crate::runtime_sampling::apply(&mut request, &plan.sampling);
let stream = match accepted(&mut client, request.clone()).await {
Ok(stream) => stream,
Err(_) => return error(StatusCode::BAD_GATEWAY, "runtime_dispatch_failed"),
@@ -943,9 +943,15 @@ async fn tool_responses(registry: Registry, index: usize, value: Value) -> Respo
mod tests {
use super::*;
#[test]
fn runtime_gateway_refuses_silent_sampling_tools_and_state() {
fn runtime_gateway_refuses_tools_state_and_out_of_contract_sampling() {
for extra in [
json!({"temperature":0.5}),
json!({"temperature":2.5}),
json!({"temperature":0.1234}),
json!({"top_p":1.5}),
json!({"top_k":1.5}),
json!({"seed":-1}),
json!({"repetition_penalty":0}),
json!({"stop":["x"]}),
json!({"tools":[{"type":"function","name":"run"}]}),
json!({"previous_response_id":"resp_x"}),
json!({"store":true}),
@@ -958,12 +964,38 @@ mod tests {
.extend(extra.as_object().unwrap().clone());
assert!(render(&value).is_err());
}
let (prompt, limit) =
let (prompt, limit, greedy) =
render(&json!({"model":"native","input":"hello","max_output_tokens":2,"store":false}))
.unwrap();
assert_eq!(limit, 2);
assert_eq!(greedy, FixedPoint::default());
assert!(prompt.ends_with("<|im_start|>assistant\n<think>\n\n</think>\n\n"));
}
#[test]
fn runtime_gateway_forwards_the_full_sampling_contract_to_the_runtime_request() {
let (_, _, fixed) = render(&json!({
"model":"native","input":"hello","temperature":0.7,"top_p":0.9,"top_k":40,"min_p":0.05,
"repetition_penalty":1.1,"frequency_penalty":0.25,"presence_penalty":-0.5,
"penalty_last_n":128,"seed":42
}))
.unwrap();
let mut request = proto::GenerateRequest::default();
crate::runtime_sampling::apply(&mut request, &fixed);
assert_eq!(request.temperature_milli, 700);
assert_eq!(request.top_p_micro, Some(900_000));
assert_eq!(request.top_k, Some(40));
assert_eq!(request.min_p_micro, Some(50_000));
assert_eq!(request.repetition_penalty_micro, Some(1_100_000));
assert_eq!(request.frequency_penalty_micro, Some(250_000));
assert_eq!(request.presence_penalty_micro, Some(-500_000));
assert_eq!(request.penalty_last_n, Some(128));
assert_eq!(request.seed, Some(42));
let backend = crate::runtime_sampling::to_backend(&request).unwrap();
assert_eq!(backend.top_p_micro, Some(900_000));
assert_eq!(backend.seed, Some(42));
request.top_p_micro = Some(1_000_001);
assert!(crate::runtime_sampling::to_backend(&request).is_err());
}
fn trace() -> Trace {
Trace {
id: "resp_test".into(),
+10 -4
View File
@@ -545,15 +545,20 @@ impl proto::runtime_server::Runtime for RuntimeServer {
if command.prompt.len() > 1024 * 1024
|| command.max_output_tokens == 0
|| command.max_output_tokens > 4096
// Sampling is validated and served by the backend (Original sampler chain);
// only the documented range is enforced at this boundary.
|| command.temperature_milli > 2000
{
return Err(refusal(
tonic::Code::InvalidArgument,
"unsupported_generation_request",
));
}
// Sampling is served by the backend (Original sampler chain); the Original's documented
// ranges are enforced here too, so an out-of-contract request never reaches a worker.
let sampling = crate::runtime_sampling::to_backend(&command).map_err(|()| {
refusal(
tonic::Code::InvalidArgument,
"unsupported_generation_request",
)
})?;
let loaded = {
let mut state = lock(&self.inner.state)?;
fence(&state, &command.expected_epoch)?;
@@ -594,7 +599,7 @@ impl proto::runtime_server::Runtime for RuntimeServer {
prompt: command.prompt,
max_output_tokens: command.max_output_tokens,
temperature_milli: command.temperature_milli,
sampling: Default::default(),
sampling,
};
let mut acceptance_guard = AcceptanceGuard {
inner: self.inner.clone(),
@@ -1308,6 +1313,7 @@ mod tests {
prompt: prompt.into(),
max_output_tokens: 2,
temperature_milli: 0,
..Default::default()
}
}
#[tokio::test(flavor = "current_thread")]
+60
View File
@@ -0,0 +1,60 @@
//! Sampling controls on the runtime gRPC contract: JSON request fields <-> fixed point <->
//! `runtime.proto` `GenerateRequest` <-> `backend-api` `SamplingOptions`. The arithmetic and the
//! Original's ranges live in `leleka-serving-policy` (tested on every host); this file is the thin
//! field-by-field mapping.
use leleka_backend_api::SamplingOptions;
use leleka_sampler_ref::params::FixedPoint;
use leleka_serving_policy::fixed::{error_code, sampling_from_object, to_fixed_point};
use serde_json::{Map, Value};
use crate::runtime_rpc::proto;
/// Read and validate the sampling fields of a Responses request object.
pub(crate) fn from_json(object: &Map<String, Value>) -> Result<FixedPoint, &'static str> {
let sampling = sampling_from_object(object).map_err(|e| error_code(&e))?;
to_fixed_point(&sampling).map_err(|e| error_code(&e))
}
/// Put the sampling controls on a runtime request.
pub(crate) fn apply(request: &mut proto::GenerateRequest, fixed: &FixedPoint) {
request.temperature_milli = fixed.temperature_milli;
request.top_p_micro = fixed.top_p_micro;
request.top_k = fixed.top_k;
request.min_p_micro = fixed.min_p_micro;
request.repetition_penalty_micro = fixed.repetition_penalty_micro;
request.frequency_penalty_micro = fixed.frequency_penalty_micro;
request.presence_penalty_micro = fixed.presence_penalty_micro;
request.penalty_last_n = fixed.penalty_last_n;
request.seed = fixed.seed;
}
/// Validate a received request's controls at the RPC boundary (the backend validates again) and
/// convert them for the backend.
pub(crate) fn to_backend(command: &proto::GenerateRequest) -> Result<SamplingOptions, ()> {
let fixed = FixedPoint {
temperature_milli: command.temperature_milli,
top_p_micro: command.top_p_micro,
top_k: command.top_k,
min_p_micro: command.min_p_micro,
repetition_penalty_micro: command.repetition_penalty_micro,
frequency_penalty_micro: command.frequency_penalty_micro,
presence_penalty_micro: command.presence_penalty_micro,
penalty_last_n: command.penalty_last_n,
seed: command.seed,
};
// The same contract as the HTTP boundary: the ranges of `RequestSampling::validate`.
leleka_sampler_ref::RequestSampling::from_fixed_point(&fixed)
.validate()
.map_err(|_| ())?;
Ok(SamplingOptions {
top_p_micro: fixed.top_p_micro,
top_k: fixed.top_k,
min_p_micro: fixed.min_p_micro,
repetition_penalty_micro: fixed.repetition_penalty_micro,
frequency_penalty_micro: fixed.frequency_penalty_micro,
presence_penalty_micro: fixed.presence_penalty_micro,
penalty_last_n: fixed.penalty_last_n,
seed: fixed.seed,
})
}
+13 -5
View File
@@ -18,6 +18,7 @@ pub struct ToolPlan {
pub prompt: String,
pub max_output_tokens: u32,
pub policy: ToolPolicy,
pub sampling: leleka_sampler_ref::params::FixedPoint,
}
pub enum ValidatedSegment {
@@ -400,6 +401,14 @@ pub fn prepare(request: &Value) -> Result<ToolPlan, &'static str> {
"stream",
"max_output_tokens",
"temperature",
"top_p",
"top_k",
"min_p",
"repetition_penalty",
"frequency_penalty",
"presence_penalty",
"penalty_last_n",
"seed",
"store",
"tools",
"tool_choice",
@@ -414,14 +423,12 @@ pub fn prepare(request: &Value) -> Result<ToolPlan, &'static str> {
return Err("invalid_stream");
}
if object
.get("temperature")
.is_some_and(|v| v.as_f64() != Some(0.0))
|| object
.get("store")
.is_some_and(|v| v != &Value::Bool(false))
.get("store")
.is_some_and(|v| v != &Value::Bool(false))
{
return Err("unsupported_sampling_or_store");
}
let sampling = crate::runtime_sampling::from_json(object)?;
if object
.get("text")
.is_some_and(|v| v != &json!({"format":{"type":"text"}}))
@@ -493,6 +500,7 @@ pub fn prepare(request: &Value) -> Result<ToolPlan, &'static str> {
prompt,
max_output_tokens: cap as u32,
policy,
sampling,
})
}