From cce433339d97da4d641929e352941acbbcca6132 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 14 Oct 2026 15:17:04 +0200 Subject: [PATCH] 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 --- Cargo.lock | 12 + Cargo.toml | 4 +- control-plane/Cargo.toml | 2 + control-plane/src/app.rs | 5 +- control-plane/src/chat.rs | 17 +- control-plane/src/lib.rs | 4 + control-plane/src/messages.rs | 7 +- control-plane/src/queue.rs | 3 +- control-plane/src/responses.rs | 290 +- control-plane/src/sampling.rs | 216 ++ control-plane/src/settings.rs | 179 ++ control-plane/src/wire.rs | 207 +- control-plane/src/worker.rs | 44 +- .../tests/fixtures/golden/gen_lines.json | 1085 ++++++++ control-plane/tests/fixtures/mock_engine.sh | 0 control-plane/tests/golden/gen_goldens.py | 223 ++ crates/serving-policy/Cargo.toml | 14 + crates/serving-policy/src/fixed.rs | 258 ++ crates/serving-policy/src/lib.rs | 9 + crates/serving-policy/src/reasoning.rs | 251 ++ crates/serving-policy/src/shared.rs | 501 ++++ .../tests/fixtures/reasoning.json | 2476 +++++++++++++++++ .../serving-policy/tests/fixtures/shared.json | 631 +++++ .../serving-policy/tests/golden_reasoning.rs | 75 + crates/serving-policy/tests/golden_shared.rs | 79 + desktop-core/Cargo.toml | 2 + desktop-core/proto/runtime.proto | 11 + desktop-core/src/lib.rs | 1 + desktop-core/src/runtime_client.rs | 1 + desktop-core/src/runtime_gateway.rs | 76 +- desktop-core/src/runtime_rpc.rs | 14 +- desktop-core/src/runtime_sampling.rs | 60 + desktop-core/src/runtime_tools.rs | 18 +- 33 files changed, 6667 insertions(+), 108 deletions(-) create mode 100644 control-plane/src/sampling.rs create mode 100644 control-plane/src/settings.rs create mode 100644 control-plane/tests/fixtures/golden/gen_lines.json mode change 100644 => 100755 control-plane/tests/fixtures/mock_engine.sh create mode 100644 control-plane/tests/golden/gen_goldens.py create mode 100644 crates/serving-policy/Cargo.toml create mode 100644 crates/serving-policy/src/fixed.rs create mode 100644 crates/serving-policy/src/lib.rs create mode 100644 crates/serving-policy/src/reasoning.rs create mode 100644 crates/serving-policy/src/shared.rs create mode 100644 crates/serving-policy/tests/fixtures/reasoning.json create mode 100644 crates/serving-policy/tests/fixtures/shared.json create mode 100644 crates/serving-policy/tests/golden_reasoning.rs create mode 100644 crates/serving-policy/tests/golden_shared.rs create mode 100644 desktop-core/src/runtime_sampling.rs diff --git a/Cargo.lock b/Cargo.lock index 45e2c11c..3a33f873 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", diff --git a/Cargo.toml b/Cargo.toml index d60f6b80..b5fb1d04 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/control-plane/Cargo.toml b/control-plane/Cargo.toml index e4454078..4b73f910 100644 --- a/control-plane/Cargo.toml +++ b/control-plane/Cargo.toml @@ -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" diff --git a/control-plane/src/app.rs b/control-plane/src/app.rs index 92e9ccb0..197f7503 100644 --- a/control-plane/src/app.rs +++ b/control-plane/src/app.rs @@ -27,6 +27,7 @@ pub struct AppState { pub tokenizer: Option>, pub generation: Option>, pub response_history: Arc>, + pub settings: Arc, } 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), }) diff --git a/control-plane/src/chat.rs b/control-plane/src/chat.rs index a912e6fc..0f0122b6 100644 --- a/control-plane/src/chat.rs +++ b/control-plane/src/chat.rs @@ -41,8 +41,6 @@ struct Request { store: Option, stop: Option, logprobs: Option, - frequency_penalty: Option, - presence_penalty: Option, } #[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); diff --git a/control-plane/src/lib.rs b/control-plane/src/lib.rs index ef8c6e48..3a270bb2 100644 --- a/control-plane/src/lib.rs +++ b/control-plane/src/lib.rs @@ -60,3 +60,7 @@ pub mod cuda_memory; pub mod service_switch; pub mod queue; + +pub mod sampling; + +pub mod settings; diff --git a/control-plane/src/messages.rs b/control-plane/src/messages.rs index 8036d2e6..937e76f9 100644 --- a/control-plane/src/messages.rs +++ b/control-plane/src/messages.rs @@ -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; diff --git a/control-plane/src/queue.rs b/control-plane/src/queue.rs index f00c0776..06705ff1 100644 --- a/control-plane/src/queue.rs +++ b/control-plane/src/queue.rs @@ -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), }, diff --git a/control-plane/src/responses.rs b/control-plane/src/responses.rs index 4f488a07..788e7206 100644 --- a/control-plane/src/responses.rs +++ b/control-plane/src/responses.rs @@ -500,6 +500,17 @@ pub struct CreateRequest { pub tool_choice: Option, pub temperature: Option, pub top_p: Option, + /// Original-server sampling extensions (top level, like `serve/server.py`): see `sampling`. + pub top_k: Option, + pub min_p: Option, + pub repetition_penalty: Option, + pub frequency_penalty: Option, + pub presence_penalty: Option, + pub penalty_last_n: Option, + pub seed: Option, + pub strata_tune: Option, + pub experimental_speed_projection: Option, + pub reasoning_budget_tokens: Option, pub truncation: Option, pub metadata: Option>, pub store: Option, @@ -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( + settings: crate::settings::Settings, + body: Value, + route: F, + ) -> (StatusCode, Option) + where + F: FnOnce( + State, + Result, axum::extract::rejection::JsonRejection>, + ) -> Fut, + Fut: std::future::Future, + { + 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::>(), + ["GEN", "5"] + ); + } + #[tokio::test] async fn nonstreaming_tool_call_keeps_typed_arguments() { let (tokenizer, root) = test_tokenizer(); diff --git a/control-plane/src/sampling.rs b/control-plane/src/sampling.rs new file mode 100644 index 00000000..546f692e --- /dev/null +++ b/control-plane/src/sampling.rs @@ -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) { + 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, + pub spec_min_p: Option, +} + +impl From 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::(json!({"pcie_frac": 0.5, "x": 1})).is_err()); + } +} diff --git a/control-plane/src/settings.rs b/control-plane/src/settings.rs new file mode 100644 index 00000000..89f37700 --- /dev/null +++ b/control-plane/src/settings.rs @@ -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, + shared_path: Option, + /// The config's `reasoning_budget_tokens` (raw, validated at startup). + reasoning_budget_default: Option, +} + +impl Settings { + pub fn new(config: ConfigSampling) -> Self { + Self { + config, + ..Default::default() + } + } + + pub fn with_reasoning_budget(mut self, default: Option) -> 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::(&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 { + 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: `.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") + ); + } +} diff --git a/control-plane/src/wire.rs b/control-plane/src/wire.rs index c49b696b..bba0f8ba 100644 --- a/control-plane/src/wire.rs +++ b/control-plane/src/wire.rs @@ -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, + pub spec_min_p: Option, +} + +/// 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, pub max_new: u32, - pub temperature: Option, - pub top_p: Option, + pub sampling: RequestSampling, + pub tune: Option, + /// `experimental_speed_projection`: `Some(b)` emits `cvec=0|1`, `None` leaves the + /// engine default (on when a vector is loaded). + pub cvec: Option, + /// `GENI`: path of the SVE1 image-embeddings file for this request. + pub embeddings: Option, } impl Generate { + /// The tuning and projection keys after the sampling keys, in the Python order. + fn engine_keys(&self) -> Result { + 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 { 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") diff --git a/control-plane/src/worker.rs b/control-plane/src/worker.rs index 216a7a00..2a86b657 100644 --- a/control-plane/src/worker.rs +++ b/control-plane/src/worker.rs @@ -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), }) diff --git a/control-plane/tests/fixtures/golden/gen_lines.json b/control-plane/tests/fixtures/golden/gen_lines.json new file mode 100644 index 00000000..fdb8a117 --- /dev/null +++ b/control-plane/tests/fixtures/golden/gen_lines.json @@ -0,0 +1,1085 @@ +{ + "source": "serve/server.py StrataEngine.generate (real code, fake pipe)", + "cases": [ + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": {}, + "line": "GEN 16 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.0 + }, + "line": "GEN 16 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.7 + }, + "line": "GEN 16 temperature=0.7 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.7, + "top_p": 0.9 + }, + "line": "GEN 16 temperature=0.7 top_p=0.9 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 1, + "top_p": 1.0 + }, + "line": "GEN 16 temperature=1.0 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.8, + "top_k": 40, + "min_p": 0.05 + }, + "line": "GEN 16 temperature=0.8 top_k=40 min_p=0.05 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.8, + "top_k": 0 + }, + "line": "GEN 16 temperature=0.8 top_k=64 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.8, + "top_k": 1000 + }, + "line": "GEN 16 temperature=0.8 top_k=64 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.6, + "top_p": 0.95, + "top_k": 20, + "min_p": 0.0 + }, + "line": "GEN 16 temperature=0.6 top_p=0.95 top_k=20 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "repetition_penalty": 1.1 + }, + "line": "GEN 16 penalty_repeat=1.1 penalty_last_n=64 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "repetition_penalty": 1.1, + "penalty_last_n": 256 + }, + "line": "GEN 16 penalty_repeat=1.1 penalty_last_n=256 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "presence_penalty": 0.5, + "frequency_penalty": 0.25 + }, + "line": "GEN 16 penalty_freq=0.25 penalty_present=0.5 penalty_last_n=64 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "presence_penalty": -0.5 + }, + "line": "GEN 16 penalty_present=-0.5 penalty_last_n=64 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "frequency_penalty": 1.5, + "penalty_last_n": 0 + }, + "line": "GEN 16 penalty_freq=1.5 penalty_last_n=64 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.7, + "seed": 42 + }, + "line": "GEN 16 temperature=0.7 seed=42 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.7, + "seed": 0 + }, + "line": "GEN 16 temperature=0.7 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.7, + "seed": 18446744073709551615 + }, + "line": "GEN 16 temperature=0.7 seed=18446744073709551615 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "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 + }, + "line": "GEN 16 temperature=0.9 top_p=0.8 top_k=33 min_p=0.02 penalty_repeat=1.05 penalty_freq=0.2 penalty_present=0.1 penalty_last_n=128 seed=7 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "strata_tune": { + "pcie_frac": 0.0 + } + }, + "line": "GEN 16 pcie_frac=0.0 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "strata_tune": { + "pcie_frac": 0.35, + "spec_min_p": 0.2 + } + }, + "line": "GEN 16 pcie_frac=0.35 spec_min_p=0.2 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "strata_tune": { + "spec_min_p": 1.0 + } + }, + "line": "GEN 16 spec_min_p=1.0 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "experimental_speed_projection": true + }, + "line": "GEN 16 cvec=1 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "experimental_speed_projection": false + }, + "line": "GEN 16 cvec=0 1,2,3\n" + }, + { + "token_ids": [ + 1, + 2, + 3 + ], + "max_new": 16, + "embeddings": null, + "sampling": { + "temperature": 0.5, + "strata_tune": { + "pcie_frac": 0.5 + }, + "experimental_speed_projection": false + }, + "line": "GEN 16 temperature=0.5 pcie_frac=0.5 cvec=0 1,2,3\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": {}, + "line": "GEN 4096 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.0 + }, + "line": "GEN 4096 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.7 + }, + "line": "GEN 4096 temperature=0.7 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.7, + "top_p": 0.9 + }, + "line": "GEN 4096 temperature=0.7 top_p=0.9 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 1, + "top_p": 1.0 + }, + "line": "GEN 4096 temperature=1.0 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.8, + "top_k": 40, + "min_p": 0.05 + }, + "line": "GEN 4096 temperature=0.8 top_k=40 min_p=0.05 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.8, + "top_k": 0 + }, + "line": "GEN 4096 temperature=0.8 top_k=64 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.8, + "top_k": 1000 + }, + "line": "GEN 4096 temperature=0.8 top_k=64 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.6, + "top_p": 0.95, + "top_k": 20, + "min_p": 0.0 + }, + "line": "GEN 4096 temperature=0.6 top_p=0.95 top_k=20 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "repetition_penalty": 1.1 + }, + "line": "GEN 4096 penalty_repeat=1.1 penalty_last_n=64 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "repetition_penalty": 1.1, + "penalty_last_n": 256 + }, + "line": "GEN 4096 penalty_repeat=1.1 penalty_last_n=256 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "presence_penalty": 0.5, + "frequency_penalty": 0.25 + }, + "line": "GEN 4096 penalty_freq=0.25 penalty_present=0.5 penalty_last_n=64 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "presence_penalty": -0.5 + }, + "line": "GEN 4096 penalty_present=-0.5 penalty_last_n=64 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "frequency_penalty": 1.5, + "penalty_last_n": 0 + }, + "line": "GEN 4096 penalty_freq=1.5 penalty_last_n=64 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.7, + "seed": 42 + }, + "line": "GEN 4096 temperature=0.7 seed=42 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.7, + "seed": 0 + }, + "line": "GEN 4096 temperature=0.7 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.7, + "seed": 18446744073709551615 + }, + "line": "GEN 4096 temperature=0.7 seed=18446744073709551615 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "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 + }, + "line": "GEN 4096 temperature=0.9 top_p=0.8 top_k=33 min_p=0.02 penalty_repeat=1.05 penalty_freq=0.2 penalty_present=0.1 penalty_last_n=128 seed=7 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "strata_tune": { + "pcie_frac": 0.0 + } + }, + "line": "GEN 4096 pcie_frac=0.0 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "strata_tune": { + "pcie_frac": 0.35, + "spec_min_p": 0.2 + } + }, + "line": "GEN 4096 pcie_frac=0.35 spec_min_p=0.2 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "strata_tune": { + "spec_min_p": 1.0 + } + }, + "line": "GEN 4096 spec_min_p=1.0 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "experimental_speed_projection": true + }, + "line": "GEN 4096 cvec=1 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "experimental_speed_projection": false + }, + "line": "GEN 4096 cvec=0 248045,872,198,9707\n" + }, + { + "token_ids": [ + 248045, + 872, + 198, + 9707 + ], + "max_new": 4096, + "embeddings": null, + "sampling": { + "temperature": 0.5, + "strata_tune": { + "pcie_frac": 0.5 + }, + "experimental_speed_projection": false + }, + "line": "GEN 4096 temperature=0.5 pcie_frac=0.5 cvec=0 248045,872,198,9707\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": {}, + "line": "GENI 32 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.0 + }, + "line": "GENI 32 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.7 + }, + "line": "GENI 32 temperature=0.7 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.7, + "top_p": 0.9 + }, + "line": "GENI 32 temperature=0.7 top_p=0.9 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 1, + "top_p": 1.0 + }, + "line": "GENI 32 temperature=1.0 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.8, + "top_k": 40, + "min_p": 0.05 + }, + "line": "GENI 32 temperature=0.8 top_k=40 min_p=0.05 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.8, + "top_k": 0 + }, + "line": "GENI 32 temperature=0.8 top_k=64 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.8, + "top_k": 1000 + }, + "line": "GENI 32 temperature=0.8 top_k=64 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.6, + "top_p": 0.95, + "top_k": 20, + "min_p": 0.0 + }, + "line": "GENI 32 temperature=0.6 top_p=0.95 top_k=20 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "repetition_penalty": 1.1 + }, + "line": "GENI 32 penalty_repeat=1.1 penalty_last_n=64 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "repetition_penalty": 1.1, + "penalty_last_n": 256 + }, + "line": "GENI 32 penalty_repeat=1.1 penalty_last_n=256 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "presence_penalty": 0.5, + "frequency_penalty": 0.25 + }, + "line": "GENI 32 penalty_freq=0.25 penalty_present=0.5 penalty_last_n=64 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "presence_penalty": -0.5 + }, + "line": "GENI 32 penalty_present=-0.5 penalty_last_n=64 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "frequency_penalty": 1.5, + "penalty_last_n": 0 + }, + "line": "GENI 32 penalty_freq=1.5 penalty_last_n=64 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.7, + "seed": 42 + }, + "line": "GENI 32 temperature=0.7 seed=42 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.7, + "seed": 0 + }, + "line": "GENI 32 temperature=0.7 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.7, + "seed": 18446744073709551615 + }, + "line": "GENI 32 temperature=0.7 seed=18446744073709551615 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "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 + }, + "line": "GENI 32 temperature=0.9 top_p=0.8 top_k=33 min_p=0.02 penalty_repeat=1.05 penalty_freq=0.2 penalty_present=0.1 penalty_last_n=128 seed=7 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "strata_tune": { + "pcie_frac": 0.0 + } + }, + "line": "GENI 32 pcie_frac=0.0 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "strata_tune": { + "pcie_frac": 0.35, + "spec_min_p": 0.2 + } + }, + "line": "GENI 32 pcie_frac=0.35 spec_min_p=0.2 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "strata_tune": { + "spec_min_p": 1.0 + } + }, + "line": "GENI 32 spec_min_p=1.0 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "experimental_speed_projection": true + }, + "line": "GENI 32 cvec=1 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "experimental_speed_projection": false + }, + "line": "GENI 32 cvec=0 /tmp/req-abc123.sve 5,248056,248056,6\n" + }, + { + "token_ids": [ + 5, + 248056, + 248056, + 6 + ], + "max_new": 32, + "embeddings": "/tmp/req-abc123.sve", + "sampling": { + "temperature": 0.5, + "strata_tune": { + "pcie_frac": 0.5 + }, + "experimental_speed_projection": false + }, + "line": "GENI 32 temperature=0.5 pcie_frac=0.5 cvec=0 /tmp/req-abc123.sve 5,248056,248056,6\n" + } + ] +} diff --git a/control-plane/tests/fixtures/mock_engine.sh b/control-plane/tests/fixtures/mock_engine.sh old mode 100644 new mode 100755 diff --git a/control-plane/tests/golden/gen_goldens.py b/control-plane/tests/golden/gen_goldens.py new file mode 100644 index 00000000..46942ab1 --- /dev/null +++ b/control-plane/tests/golden/gen_goldens.py @@ -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"", b"", b"<", b"/", b"\n", + b"\xc3", b"\xa9", "\u65e5".encode()[:1], "\u65e5".encode()[1:], b"\xff", b"\xe2\x82", b"\xac", b"", 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:]) diff --git a/crates/serving-policy/Cargo.toml b/crates/serving-policy/Cargo.toml new file mode 100644 index 00000000..07963d95 --- /dev/null +++ b/crates/serving-policy/Cargo.toml @@ -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 diff --git a/crates/serving-policy/src/fixed.rs b/crates/serving-policy/src/fixed.rs new file mode 100644 index 00000000..260dced1 --- /dev/null +++ b/crates/serving-policy/src/fixed.rs @@ -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 { + 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 { + sampling.validate()?; + let micro_u32 = + |field: &'static str, value: Option| -> Result, 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| -> Result, 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, key: &'static str) -> Result, 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, key: &'static str) -> Result, 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) -> Result { + 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 { + 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() + ); + } +} diff --git a/crates/serving-policy/src/lib.rs b/crates/serving-policy/src/lib.rs new file mode 100644 index 00000000..124e06d8 --- /dev/null +++ b/crates/serving-policy/src/lib.rs @@ -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; diff --git a/crates/serving-policy/src/reasoning.rs b/crates/serving-policy/src/reasoning.rs new file mode 100644 index 00000000..b8041bd0 --- /dev/null +++ b/crates/serving-policy/src/reasoning.rs @@ -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 +//! `` 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 ``). + +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\n\n"; + +const THINK_END: &str = ""; + +/// `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, 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 ``. + held: String, + /// Bytes of a UTF-8 character not yet complete (`Detokenizer.pending`). + partial: Vec, +} + +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 ``). + 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 ""), 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""] { + 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); + } +} diff --git a/crates/serving-policy/src/shared.rs b/crates/serving-policy/src/shared.rs new file mode 100644 index 00000000..41fbc41e --- /dev/null +++ b/crates/serving-policy/src/shared.rs @@ -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, + pub temperature: Option, + pub top_p: Option, + pub top_k: Option, + pub seed: Option, + pub max_tokens: Option, + pub experimental_speed_projection: Option, +} + +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::>().join(", ") + ), + Value::Object(map) => format!( + "{{{}}}", + map.iter() + .map(|(k, v)| format!("{}: {}", py_str_repr(k), py_repr(v))) + .collect::>() + .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 { + v.as_f64() +} + +/// An integral number as `i128`, or `None`. +fn integral(v: &Value) -> Option { + 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 { + 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, + /// Keys the Original names at startup and ignores. + pub ignored: Vec, +} + +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 { + 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, +} + +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| { + 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, shared: &SharedDefaults) -> Option { + 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); + } +} diff --git a/crates/serving-policy/tests/fixtures/reasoning.json b/crates/serving-policy/tests/fixtures/reasoning.json new file mode 100644 index 00000000..7e8152d7 --- /dev/null +++ b/crates/serving-policy/tests/fixtures/reasoning.json @@ -0,0 +1,2476 @@ +{ + "source": "serve/server.py Service.reasoning_budget + Service.run budget branch (real Detokenizer/OutputParser)", + "wrap_up": "\n\nI have thought about this long enough; time to give my answer.\n\n\n", + "cases": [ + { + "pieces_hex": [ + "61", + "62", + "20736f20", + "7468696e6b" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "3c2f", + "2f7468696e6b3e" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "3c2f7468696e6b3e", + "61", + "62" + ], + "wrap_at": { + "1": null, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "61", + "3c2f", + "61", + "62" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "0a", + "c3", + "61", + "61", + "61" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "a9", + "e6", + "61", + "61" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "ff", + "61", + "61" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "e282", + "ac", + "61" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "7468696e6b", + "3c2f", + "2f7468696e6b3e", + "7468696e6b", + "7468696e6b" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "61", + "61", + "61", + "61", + "61", + "61", + "61", + "61", + "61", + "61" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "e6", + "7468696e6b", + "61", + "20736f20", + "ac", + "62", + "78", + "20736f20", + "7468696e6b", + "0a", + "3c2f746869", + "61", + "61" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "61", + "0a", + "68696e6b3e", + "3c74", + "97a5", + "3c74", + "e6", + "3c2f", + "20736f20", + "2f7468696e6b3e", + "7468696e6b", + "61", + "ff" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 8 + } + }, + { + "pieces_hex": [ + "3c2f746869", + "20736f20", + "78", + "e282", + "e6", + "20736f20", + "3c74", + "78" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": 5, + "8": 7 + } + }, + { + "pieces_hex": [ + "ff", + "ac" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "6e6b3e" + ], + "wrap_at": { + "1": 0, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "20736f20", + "68696e6b3e", + "3c", + "97a5", + "0a", + "6e6b3e", + "3c2f746869", + "68696e6b3e", + "3c2f7468696e6b3e" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "ff", + "78", + "61", + "ff", + "20736f20", + "61", + "2f", + "3c2f" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "97a5", + "78", + "c3", + "2f7468696e6b3e", + "62", + "20736f20", + "ac", + "97a5", + "2f7468696e6b3e", + "20736f20", + "e282", + "3c2f7468696e6b3e" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "61", + "0a", + "7468696e6b" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "3c2f", + "78", + "3c", + "e6", + "62", + "a9", + "6e6b3e", + "78", + "62" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 4, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "6e6b3e", + "3c2f", + "3c" + ], + "wrap_at": { + "1": 0, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "e6", + "62", + "ac" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "0a", + "97a5", + "2f", + "ac", + "e6", + "97a5", + "62" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 5, + "8": null + } + }, + { + "pieces_hex": [ + "97a5", + "3c74", + "2f7468696e6b3e", + "e6", + "ff", + "e6", + "3c", + "6e6b3e", + "7468696e6b", + "2f7468696e6b3e", + "a9", + "a9", + "7468696e6b" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "7468696e6b", + "97a5", + "c3", + "78", + "6e6b3e", + "68696e6b3e", + "3c2f7468696e6b3e", + "0a", + "7468696e6b" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "2f7468696e6b3e", + "ac", + "6e6b3e", + "3c2f", + "2f", + "e6", + "20736f20", + "20736f20", + "c3", + "3c2f7468696e6b3e", + "62", + "3c" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "62", + "3c2f746869", + "ff", + "20736f20", + "2f", + "3c", + "e6", + "20736f20", + "ac", + "6e6b3e", + "20736f20", + "a9", + "3c2f7468696e6b3e" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "c3", + "3c2f7468696e6b3e" + ], + "wrap_at": { + "1": null, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "e6", + "ff", + "3c2f746869", + "0a", + "3c2f7468696e6b3e", + "ff", + "a9", + "2f7468696e6b3e", + "ac", + "3c2f7468696e6b3e", + "3c", + "62" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 3, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "e282", + "3c2f", + "97a5", + "e282", + "97a5", + "2f" + ], + "wrap_at": { + "1": 2, + "2": 2, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "3c2f", + "62", + "3c74" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "3c2f", + "e282", + "20736f20" + ], + "wrap_at": { + "1": 2, + "2": 2, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "2f", + "2f7468696e6b3e", + "61", + "78", + "78", + "62", + "68696e6b3e", + "20736f20", + "3c2f", + "3c2f7468696e6b3e", + "62", + "a9" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "2f", + "3c2f7468696e6b3e", + "78", + "c3", + "6e6b3e", + "e282", + "68696e6b3e" + ], + "wrap_at": { + "1": 0, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "a9", + "2f", + "78", + "ac", + "3c2f" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "20736f20", + "6e6b3e", + "6e6b3e", + "a9", + "c3", + "ac", + "6e6b3e", + "ff", + "7468696e6b" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 5, + "8": 7 + } + }, + { + "pieces_hex": [ + "c3", + "6e6b3e", + "3c2f7468696e6b3e", + "3c", + "ac", + "c3", + "62", + "0a", + "e6", + "3c2f746869", + "97a5", + "2f7468696e6b3e" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "3c", + "61", + "20736f20", + "97a5", + "c3", + "3c", + "a9" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": 6, + "8": null + } + }, + { + "pieces_hex": [ + "97a5", + "2f7468696e6b3e", + "c3", + "68696e6b3e", + "97a5", + "2f7468696e6b3e", + "3c", + "ac", + "0a", + "68696e6b3e", + "3c74" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "3c2f7468696e6b3e", + "2f7468696e6b3e", + "ff", + "ac", + "e6", + "78" + ], + "wrap_at": { + "1": null, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "78", + "61", + "e6", + "78", + "7468696e6b", + "61", + "0a", + "97a5" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "3c2f", + "ac" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "0a", + "3c", + "3c", + "78", + "78", + "ac" + ], + "wrap_at": { + "1": 0, + "2": 3, + "3": 3, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "ac", + "3c", + "ac", + "3c2f7468696e6b3e", + "ff", + "6e6b3e" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "e282", + "3c74" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "2f", + "ff", + "2f", + "2f" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "6e6b3e", + "20736f20", + "ff", + "ac", + "ac", + "e282", + "7468696e6b", + "3c2f746869" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "0a", + "3c2f", + "61", + "c3", + "62" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "62", + "3c2f7468696e6b3e", + "78", + "3c2f", + "2f", + "ff", + "0a", + "a9", + "ff", + "20736f20", + "3c" + ], + "wrap_at": { + "1": 0, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "97a5", + "ac", + "3c2f746869", + "0a", + "ff" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "68696e6b3e", + "61" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "ac", + "2f", + "ac", + "3c2f746869", + "2f7468696e6b3e", + "97a5", + "97a5", + "78", + "78", + "3c2f", + "e282" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "3c74", + "20736f20", + "3c2f", + "e282", + "3c2f746869", + "2f7468696e6b3e", + "ff", + "ff", + "c3", + "2f" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 5, + "5": 5, + "8": 7 + } + }, + { + "pieces_hex": [ + "e282", + "ac", + "e282" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "3c74", + "e6", + "62", + "0a", + "20736f20", + "0a", + "78", + "a9", + "62", + "3c74" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "20736f20", + "2f", + "3c2f746869", + "3c74", + "3c2f7468696e6b3e", + "0a", + "ff", + "c3", + "ac", + "97a5" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "61" + ], + "wrap_at": { + "1": 0, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "20736f20", + "3c", + "a9", + "2f", + "3c2f", + "97a5", + "78", + "68696e6b3e" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": 5, + "8": 7 + } + }, + { + "pieces_hex": [ + "61", + "0a", + "ac", + "0a" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "2f7468696e6b3e", + "20736f20", + "68696e6b3e", + "61", + "3c2f7468696e6b3e", + "3c2f7468696e6b3e", + "3c74" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "e282", + "3c2f", + "ff", + "3c2f", + "78", + "6e6b3e", + "68696e6b3e", + "62", + "3c74", + "e6" + ], + "wrap_at": { + "1": 2, + "2": 2, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "3c74", + "0a", + "3c", + "c3", + "a9", + "0a" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 4, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "3c", + "61", + "2f", + "ac" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "7468696e6b", + "e282", + "3c74", + "62", + "3c2f7468696e6b3e" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "ac", + "ac", + "0a", + "e282", + "2f7468696e6b3e", + "2f", + "3c", + "0a", + "6e6b3e" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "68696e6b3e", + "2f7468696e6b3e", + "e6", + "2f7468696e6b3e", + "61", + "e282", + "a9", + "3c2f746869", + "3c2f7468696e6b3e", + "e6", + "6e6b3e", + "2f7468696e6b3e" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "ac", + "a9", + "ff", + "97a5", + "3c74", + "ac" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "97a5", + "ff", + "e6", + "0a", + "3c74", + "7468696e6b", + "78", + "ff" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "ac", + "3c2f", + "7468696e6b", + "97a5", + "97a5", + "7468696e6b", + "e282" + ], + "wrap_at": { + "1": 0, + "2": 3, + "3": 3, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "3c2f", + "6e6b3e", + "3c2f746869", + "20736f20", + "2f", + "c3", + "3c", + "ff", + "0a" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 3, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "e282", + "3c2f7468696e6b3e", + "3c74", + "97a5", + "78", + "78", + "e6" + ], + "wrap_at": { + "1": null, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "e6", + "ff", + "7468696e6b", + "e282", + "e6", + "20736f20" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": 5, + "8": null + } + }, + { + "pieces_hex": [ + "3c2f7468696e6b3e", + "2f7468696e6b3e" + ], + "wrap_at": { + "1": null, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "2f", + "2f7468696e6b3e", + "c3", + "6e6b3e", + "3c2f7468696e6b3e", + "6e6b3e", + "61", + "2f7468696e6b3e", + "78", + "2f" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "7468696e6b", + "62", + "62", + "78", + "6e6b3e", + "a9", + "2f", + "2f", + "3c", + "ac" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "ac", + "78", + "2f7468696e6b3e", + "c3", + "c3", + "61", + "3c" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 5, + "8": null + } + }, + { + "pieces_hex": [ + "3c74", + "3c", + "2f", + "3c74", + "3c2f746869", + "3c2f", + "3c2f7468696e6b3e", + "3c74", + "e6", + "3c74" + ], + "wrap_at": { + "1": 0, + "2": 3, + "3": 3, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "a9", + "ff", + "2f", + "ff", + "6e6b3e", + "a9", + "c3", + "6e6b3e" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "ac", + "97a5", + "2f", + "3c2f746869", + "3c", + "2f7468696e6b3e", + "2f7468696e6b3e", + "a9", + "2f7468696e6b3e", + "62", + "3c2f746869" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "e282", + "0a", + "68696e6b3e", + "e282", + "3c2f7468696e6b3e", + "a9", + "e6", + "61", + "e282", + "c3" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "20736f20", + "20736f20", + "20736f20", + "3c2f746869", + "68696e6b3e", + "c3", + "97a5", + "c3", + "3c2f746869", + "3c", + "ff", + "2f", + "ff" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 10 + } + }, + { + "pieces_hex": [ + "e6", + "78", + "78", + "20736f20", + "3c", + "61", + "ff", + "2f7468696e6b3e", + "3c2f" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": 5, + "8": 7 + } + }, + { + "pieces_hex": [ + "c3", + "a9", + "2f7468696e6b3e" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "3c2f", + "3c", + "7468696e6b", + "97a5", + "e282", + "2f", + "3c74", + "3c2f", + "6e6b3e" + ], + "wrap_at": { + "1": 2, + "2": 2, + "3": 2, + "5": 5, + "8": 8 + } + }, + { + "pieces_hex": [ + "a9", + "97a5", + "6e6b3e", + "2f", + "2f7468696e6b3e", + "20736f20", + "e6", + "3c2f746869", + "e6", + "3c2f746869", + "20736f20", + "6e6b3e", + "3c2f" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 10 + } + }, + { + "pieces_hex": [ + "e282", + "6e6b3e", + "3c2f", + "c3", + "3c2f7468696e6b3e", + "3c2f7468696e6b3e", + "e282", + "ff", + "3c2f", + "3c2f7468696e6b3e", + "2f" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "78", + "3c74", + "a9", + "78", + "61", + "ff", + "0a", + "3c2f7468696e6b3e", + "68696e6b3e", + "3c2f746869", + "e282", + "61" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "0a" + ], + "wrap_at": { + "1": 0, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "3c2f746869", + "78", + "61", + "a9", + "a9", + "97a5", + "a9", + "2f" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "ac", + "ff", + "3c2f746869", + "ac", + "ac", + "ac", + "97a5", + "3c", + "97a5", + "ac", + "61" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": 4, + "8": 8 + } + }, + { + "pieces_hex": [ + "3c" + ], + "wrap_at": { + "1": null, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "ac", + "7468696e6b", + "e6", + "ac", + "3c2f746869", + "c3", + "a9", + "3c2f7468696e6b3e", + "62", + "a9", + "c3", + "7468696e6b" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 6, + "5": 6, + "8": null + } + }, + { + "pieces_hex": [ + "2f7468696e6b3e", + "2f7468696e6b3e", + "3c74", + "20736f20", + "0a", + "2f7468696e6b3e", + "3c2f746869" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "20736f20", + "ff", + "c3", + "62", + "3c2f", + "6e6b3e", + "78", + "ff", + "61", + "0a", + "ff", + "62", + "6e6b3e" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 3, + "5": 5, + "8": 7 + } + }, + { + "pieces_hex": [ + "ff", + "61", + "62", + "a9", + "97a5", + "61", + "3c", + "2f7468696e6b3e", + "3c2f746869", + "3c74", + "97a5", + "ac" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "3c" + ], + "wrap_at": { + "1": null, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "e6", + "e6", + "2f7468696e6b3e", + "6e6b3e" + ], + "wrap_at": { + "1": 2, + "2": 2, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "a9", + "68696e6b3e", + "3c" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "61", + "3c", + "68696e6b3e", + "2f", + "68696e6b3e", + "3c74", + "3c2f7468696e6b3e", + "2f7468696e6b3e", + "62" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "3c", + "68696e6b3e", + "3c74", + "97a5", + "61", + "a9", + "2f7468696e6b3e", + "a9", + "68696e6b3e", + "2f", + "3c74" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "7468696e6b", + "20736f20", + "ac", + "a9", + "ac" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "ff", + "3c74", + "62", + "78", + "a9", + "e6" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "2f7468696e6b3e", + "c3", + "7468696e6b", + "e282", + "ff", + "2f", + "68696e6b3e", + "ac", + "ff" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "3c2f7468696e6b3e", + "68696e6b3e", + "ff", + "7468696e6b", + "c3", + "20736f20", + "2f", + "ff", + "3c2f" + ], + "wrap_at": { + "1": null, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "20736f20", + "68696e6b3e", + "68696e6b3e", + "2f", + "3c74", + "97a5", + "6e6b3e", + "20736f20", + "20736f20", + "3c74", + "e6" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "3c74", + "61", + "0a", + "62", + "ac", + "3c74", + "3c2f7468696e6b3e", + "7468696e6b", + "78", + "e6", + "e282", + "2f7468696e6b3e", + "ac" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "6e6b3e" + ], + "wrap_at": { + "1": 0, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "78", + "ac", + "c3", + "3c", + "ac", + "3c74", + "62", + "78", + "ac" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 4, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "2f", + "e282", + "2f", + "3c2f7468696e6b3e", + "20736f20", + "ff", + "3c2f746869", + "7468696e6b", + "3c", + "61", + "20736f20" + ], + "wrap_at": { + "1": 0, + "2": 2, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "61", + "3c" + ], + "wrap_at": { + "1": 0, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "3c74", + "0a", + "3c74", + "78", + "68696e6b3e", + "a9", + "3c74", + "61", + "c3" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "20736f20", + "3c2f7468696e6b3e", + "20736f20", + "0a", + "68696e6b3e", + "2f", + "0a", + "c3" + ], + "wrap_at": { + "1": 0, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "7468696e6b", + "61", + "3c2f", + "3c2f", + "e6", + "0a" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 5, + "5": 5, + "8": null + } + }, + { + "pieces_hex": [ + "3c2f", + "7468696e6b", + "62", + "6e6b3e", + "ac", + "2f7468696e6b3e", + "62", + "3c74", + "2f", + "e282", + "3c74", + "97a5" + ], + "wrap_at": { + "1": 2, + "2": 2, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "20736f20", + "ff", + "a9", + "78", + "0a", + "61", + "a9", + "2f", + "3c2f7468696e6b3e", + "e282" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 7 + } + }, + { + "pieces_hex": [ + "3c74", + "ac", + "3c2f746869" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "a9", + "2f7468696e6b3e", + "68696e6b3e", + "a9", + "97a5", + "68696e6b3e", + "3c2f", + "c3", + "ff", + "78", + "97a5", + "ac" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 8 + } + }, + { + "pieces_hex": [ + "3c", + "ac", + "6e6b3e", + "6e6b3e", + "3c2f", + "0a", + "3c2f" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": 5, + "8": null + } + }, + { + "pieces_hex": [ + "78", + "6e6b3e", + "3c74", + "3c", + "3c2f746869", + "3c", + "2f7468696e6b3e", + "3c2f", + "3c74", + "68696e6b3e", + "ac", + "e6" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "6e6b3e" + ], + "wrap_at": { + "1": 0, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "0a", + "62", + "0a", + "68696e6b3e", + "61", + "ff", + "62" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "3c74", + "3c", + "3c2f7468696e6b3e", + "97a5" + ], + "wrap_at": { + "1": 0, + "2": null, + "3": null, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "c3", + "68696e6b3e", + "78", + "78", + "3c", + "2f", + "e282", + "c3", + "a9", + "6e6b3e", + "e6" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 2, + "5": 8, + "8": 8 + } + }, + { + "pieces_hex": [ + "ff", + "62", + "3c74", + "68696e6b3e", + "3c74", + "2f", + "6e6b3e", + "3c2f7468696e6b3e", + "2f", + "7468696e6b", + "c3" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "0a", + "0a", + "a9", + "3c", + "c3", + "a9", + "78", + "3c", + "6e6b3e", + "3c74" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 5, + "8": 8 + } + }, + { + "pieces_hex": [ + "e6", + "ac", + "0a" + ], + "wrap_at": { + "1": 2, + "2": 2, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "ff", + "2f7468696e6b3e", + "62", + "c3" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": null, + "8": null + } + }, + { + "pieces_hex": [ + "e6", + "ac", + "68696e6b3e", + "3c2f", + "3c2f746869", + "c3", + "3c", + "0a", + "a9", + "3c74" + ], + "wrap_at": { + "1": 2, + "2": 2, + "3": 2, + "5": 7, + "8": 7 + } + }, + { + "pieces_hex": [ + "3c2f746869", + "2f", + "e282", + "e6", + "2f" + ], + "wrap_at": { + "1": 1, + "2": 1, + "3": 4, + "5": 4, + "8": null + } + }, + { + "pieces_hex": [ + "7468696e6b", + "68696e6b3e", + "2f7468696e6b3e", + "e282", + "6e6b3e", + "2f7468696e6b3e", + "c3", + "e6", + "6e6b3e", + "6e6b3e", + "e6" + ], + "wrap_at": { + "1": 0, + "2": 1, + "3": 2, + "5": 4, + "8": 8 + } + } + ], + "parse": [ + { + "request": null, + "default": 0, + "ok": null + }, + { + "request": {}, + "default": 0, + "ok": null + }, + { + "request": { + "reasoning_budget_tokens": 20 + }, + "default": 0, + "ok": 20 + }, + { + "request": { + "reasoning_budget_tokens": 20.0 + }, + "default": 0, + "ok": 20 + }, + { + "request": { + "reasoning_budget_tokens": 0 + }, + "default": 50, + "ok": null + }, + { + "request": { + "reasoning_budget_tokens": -1 + }, + "default": 50, + "ok": null + }, + { + "request": {}, + "default": 50, + "ok": 50 + }, + { + "request": { + "reasoning_budget_tokens": null + }, + "default": 50, + "ok": 50 + }, + { + "request": { + "reasoning_budget_tokens": true + }, + "default": 0, + "error": "reasoning_budget_tokens=True: expected a whole number of tokens (0: no budget)" + }, + { + "request": { + "reasoning_budget_tokens": "5" + }, + "default": 0, + "error": "reasoning_budget_tokens='5': expected a whole number of tokens (0: no budget)" + }, + { + "request": { + "reasoning_budget_tokens": 2.5 + }, + "default": 0, + "error": "reasoning_budget_tokens=2.5: expected a whole number of tokens (0: no budget)" + }, + { + "request": { + "reasoning_budget_tokens": [ + 1 + ] + }, + "default": 0, + "error": "reasoning_budget_tokens=[1]: expected a whole number of tokens (0: no budget)" + }, + { + "request": { + "reasoning_budget_tokens": 10000 + }, + "default": 0, + "ok": 10000 + } + ] +} diff --git a/crates/serving-policy/tests/fixtures/shared.json b/crates/serving-policy/tests/fixtures/shared.json new file mode 100644 index 00000000..a271e79b --- /dev/null +++ b/crates/serving-policy/tests/fixtures/shared.json @@ -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": [] + } + ] +} diff --git a/crates/serving-policy/tests/golden_reasoning.rs b/crates/serving-policy/tests/golden_reasoning.rs new file mode 100644 index 00000000..5a611b0d --- /dev/null +++ b/crates/serving-policy/tests/golden_reasoning.rs @@ -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 { + (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> = 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!(), + } + } +} diff --git a/crates/serving-policy/tests/golden_shared.rs b/crates/serving-policy/tests/golden_shared.rs new file mode 100644 index 00000000..929c7c8c --- /dev/null +++ b/crates/serving-policy/tests/golden_shared.rs @@ -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| { + 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); +} diff --git a/desktop-core/Cargo.toml b/desktop-core/Cargo.toml index ef31825b..08f93c36 100644 --- a/desktop-core/Cargo.toml +++ b/desktop-core/Cargo.toml @@ -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"] } diff --git a/desktop-core/proto/runtime.proto b/desktop-core/proto/runtime.proto index 9dfe58cc..71bd1209 100644 --- a/desktop-core/proto/runtime.proto +++ b/desktop-core/proto/runtime.proto @@ -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; } diff --git a/desktop-core/src/lib.rs b/desktop-core/src/lib.rs index 5fbc3ca1..ab6c5a30 100644 --- a/desktop-core/src/lib.rs +++ b/desktop-core/src/lib.rs @@ -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. diff --git a/desktop-core/src/runtime_client.rs b/desktop-core/src/runtime_client.rs index 102587e9..bf122477 100644 --- a/desktop-core/src/runtime_client.rs +++ b/desktop-core/src/runtime_client.rs @@ -522,6 +522,7 @@ mod tests { prompt: String::new(), max_output_tokens: 1, temperature_milli: 0, + ..Default::default() }) .await .unwrap(); diff --git a/desktop-core/src/runtime_gateway.rs b/desktop-core/src/runtime_gateway.rs index da9823e1..3dd11610 100644 --- a/desktop-core/src/runtime_gateway.rs +++ b/desktop-core/src/runtime_gateway.rs @@ -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, 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, 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, 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\n\n\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(), diff --git a/desktop-core/src/runtime_rpc.rs b/desktop-core/src/runtime_rpc.rs index 8868a534..b01712be 100644 --- a/desktop-core/src/runtime_rpc.rs +++ b/desktop-core/src/runtime_rpc.rs @@ -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")] diff --git a/desktop-core/src/runtime_sampling.rs b/desktop-core/src/runtime_sampling.rs new file mode 100644 index 00000000..5fba8bea --- /dev/null +++ b/desktop-core/src/runtime_sampling.rs @@ -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) -> Result { + 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 { + 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, + }) +} diff --git a/desktop-core/src/runtime_tools.rs b/desktop-core/src/runtime_tools.rs index f9b1c3a7..0a46168c 100644 --- a/desktop-core/src/runtime_tools.rs +++ b/desktop-core/src/runtime_tools.rs @@ -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 { "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 { 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 { prompt, max_output_tokens: cap as u32, policy, + sampling, }) }