Merge branch 'claude/port-api' into claude/port-main
# Conflicts: # Cargo.toml
This commit is contained in:
Generated
+12
@@ -1079,6 +1079,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"
|
||||
@@ -2079,6 +2087,8 @@ dependencies = [
|
||||
"jsonschema",
|
||||
"leleka-model-format",
|
||||
"leleka-quant-core",
|
||||
"leleka-sampler-ref",
|
||||
"leleka-serving-policy",
|
||||
"leleka-tokenizer",
|
||||
"libc",
|
||||
"regex",
|
||||
@@ -2103,6 +2113,8 @@ dependencies = [
|
||||
"jsonschema",
|
||||
"leleka-backend-api",
|
||||
"leleka-runtime",
|
||||
"leleka-sampler-ref",
|
||||
"leleka-serving-policy",
|
||||
"prost",
|
||||
"protoc-bin-vendored",
|
||||
"regex",
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/native-cpu-expert", "crates/sampler-ref", "crates/experimental-ref", "control-plane", "desktop-core"]
|
||||
default-members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/context", "crates/sampler-ref", "crates/experimental-ref", "control-plane", "desktop-core"]
|
||||
members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/native-cpu-expert", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "control-plane", "desktop-core"]
|
||||
default-members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/context", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "control-plane", "desktop-core"]
|
||||
|
||||
[workspace.package]
|
||||
edition = "2024"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -27,6 +27,20 @@ pub struct AppState {
|
||||
pub tokenizer: Option<Arc<Tokenizer>>,
|
||||
pub generation: Option<mpsc::Sender<GenerationCommand>>,
|
||||
pub response_history: Arc<RwLock<responses::ResponseHistory>>,
|
||||
pub settings: Arc<crate::settings::Settings>,
|
||||
/// Other names of the model (`aliases` in the config), answered like the model's own.
|
||||
pub aliases: Arc<Vec<String>>,
|
||||
/// Browser pages of these origins may call `/v1/*`.
|
||||
pub cors: Arc<leleka_serving_policy::cors::Cors>,
|
||||
/// Origins that count as this server's own page for `/settings` and `/v1/load|unload`.
|
||||
pub trusted_origins: Arc<Vec<String>>,
|
||||
/// Administrative channel to the worker supervisor (load/unload); `None` without a worker.
|
||||
pub control: Option<mpsc::Sender<crate::worker::Control>>,
|
||||
pub started_at: std::time::SystemTime,
|
||||
/// Source of the model's chat template, served by `/props`.
|
||||
pub chat_template: Option<Arc<str>>,
|
||||
/// The MCP servers configured for the operator (`GET /mcp`).
|
||||
pub mcp: Option<Arc<crate::mcp::Hub>>,
|
||||
}
|
||||
|
||||
impl Default for AppState {
|
||||
@@ -40,6 +54,14 @@ impl Default for AppState {
|
||||
tokenizer: None,
|
||||
generation: None,
|
||||
response_history: Arc::new(RwLock::new(responses::ResponseHistory::default())),
|
||||
settings: Arc::new(crate::settings::Settings::default()),
|
||||
aliases: Arc::new(Vec::new()),
|
||||
cors: Arc::new(Default::default()),
|
||||
trusted_origins: Arc::new(Vec::new()),
|
||||
control: None,
|
||||
started_at: std::time::SystemTime::now(),
|
||||
chat_template: None,
|
||||
mcp: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -66,6 +88,20 @@ pub fn router(state: AppState) -> Router {
|
||||
.route("/ready", get(ready))
|
||||
.route("/status", get(status))
|
||||
.route("/metrics", get(metrics))
|
||||
.route("/api/health", get(crate::server_api::api_health))
|
||||
.route("/props", get(crate::server_api::props))
|
||||
.route("/slots", get(crate::server_api::slots))
|
||||
.route("/v1/status", get(crate::server_api::v1_status))
|
||||
.route("/mcp", get(crate::server_api::mcp_status))
|
||||
.route(
|
||||
"/settings",
|
||||
get(crate::server_api::settings_get).post(crate::server_api::settings_post),
|
||||
)
|
||||
.route("/load", post(crate::server_api::load_post))
|
||||
.route("/unload", post(crate::server_api::unload_post))
|
||||
.route("/v1/load", post(crate::server_api::v1_load))
|
||||
.route("/v1/unload", post(crate::server_api::v1_unload))
|
||||
.route("/models", get(crate::models_api::list))
|
||||
.route("/v1/models", get(crate::models_api::list))
|
||||
.route("/v1/models/{id}", get(crate::models_api::retrieve))
|
||||
.route(
|
||||
@@ -118,11 +154,17 @@ pub fn router(state: AppState) -> Router {
|
||||
)
|
||||
.route("/admin/drain", post(drain))
|
||||
.route("/admin/resume", post(resume))
|
||||
.fallback(crate::server_api::not_found)
|
||||
.layer(DefaultBodyLimit::max(16 * 1024 * 1024))
|
||||
.layer(middleware::from_fn_with_state(
|
||||
state.api_key.clone(),
|
||||
crate::auth::authorize,
|
||||
))
|
||||
// Outermost: a browser's credential-less preflight is answered before authentication.
|
||||
.layer(middleware::from_fn_with_state(
|
||||
state.cors.clone(),
|
||||
crate::server_api::cors_layer,
|
||||
))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
@@ -137,7 +179,10 @@ async fn lifecycle_status(State(state): State<AppState>) -> Json<serde_json::Val
|
||||
&& lifecycle.requests_in_flight == 0
|
||||
&& lifecycle.generation_jobs == 0
|
||||
&& worker.metrics.active_since.is_none()
|
||||
&& matches!(worker.state, WorkerState::Ready | WorkerState::Unconfigured);
|
||||
&& matches!(
|
||||
worker.state,
|
||||
WorkerState::Ready | WorkerState::Unconfigured | WorkerState::Unloaded
|
||||
);
|
||||
Json(
|
||||
serde_json::json!({"service":"strata-control", "server_pid":std::process::id(), "model":state.model,
|
||||
"draining":lifecycle.draining,
|
||||
@@ -380,8 +425,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),
|
||||
})
|
||||
|
||||
@@ -115,7 +115,7 @@ pub async fn authorize(
|
||||
request.uri().path(),
|
||||
"/v1/messages" | "/v1/messages/count_tokens"
|
||||
);
|
||||
if request.uri().path() != "/health"
|
||||
if !matches!(request.uri().path(), "/health" | "/api/health")
|
||||
&& key.as_ref().is_some_and(|key| {
|
||||
if messages {
|
||||
!key.accepts_messages(request.headers())
|
||||
|
||||
@@ -41,8 +41,6 @@ struct Request {
|
||||
store: Option<bool>,
|
||||
stop: Option<Value>,
|
||||
logprobs: Option<bool>,
|
||||
frequency_penalty: Option<f64>,
|
||||
presence_penalty: Option<f64>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -151,14 +149,6 @@ impl Request {
|
||||
if self.logprobs == Some(true) {
|
||||
return Err(invalid("logprobs", "log probabilities are not supported"));
|
||||
}
|
||||
if self.frequency_penalty.is_some_and(|x| x != 0.0)
|
||||
|| self.presence_penalty.is_some_and(|x| x != 0.0)
|
||||
{
|
||||
return Err(invalid(
|
||||
"frequency_penalty",
|
||||
"nonzero frequency/presence penalties are not supported",
|
||||
));
|
||||
}
|
||||
if !self.stream && self.stream_options.is_some() {
|
||||
return Err(invalid(
|
||||
"stream_options",
|
||||
@@ -389,6 +379,8 @@ pub async fn create(
|
||||
Ok(body) => body,
|
||||
Err(e) => return error(e.status(), "invalid_json", None, &e.to_string()),
|
||||
};
|
||||
// Sampling extensions (top_k, min_p, penalties, seed, ...) are validated once, by the native request.
|
||||
let (body, extensions) = crate::sampling::split_extensions(body);
|
||||
let request: Request = match serde_json::from_value(body) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
@@ -400,7 +392,7 @@ pub async fn create(
|
||||
);
|
||||
}
|
||||
};
|
||||
let (request, stream, include_usage) = match request.into_responses() {
|
||||
let (mut request, stream, include_usage) = match request.into_responses() {
|
||||
Ok(r) => r,
|
||||
Err((p, m)) => {
|
||||
return error(
|
||||
@@ -411,6 +403,9 @@ pub async fn create(
|
||||
);
|
||||
}
|
||||
};
|
||||
for (key, value) in extensions {
|
||||
request[key] = value;
|
||||
}
|
||||
let response = responses::create(State(state), Ok(Json(request))).await;
|
||||
if stream && response.status().is_success() {
|
||||
return stream_response(response.into_body(), include_usage);
|
||||
|
||||
+463
-6
@@ -28,6 +28,24 @@ pub struct Config {
|
||||
pub model: Option<String>,
|
||||
pub worker: Option<WorkerConfig>,
|
||||
pub tokenizer_dir: Option<PathBuf>,
|
||||
/// Other names the model answers to (`aliases`).
|
||||
pub aliases: Vec<String>,
|
||||
/// Browser pages of these origins may call `/v1/*` (`cors_origins`; `"*"` allowed).
|
||||
pub cors_origins: Vec<String>,
|
||||
/// Origins that count as this server's own page (`trusted_origins`; no wildcard).
|
||||
pub trusted_origins: Vec<String>,
|
||||
/// The `sampling` block: defaults for what a request leaves out.
|
||||
pub sampling: leleka_serving_policy::shared::ConfigSampling,
|
||||
/// `reasoning_budget_tokens`: the default thinking budget (0: none).
|
||||
pub reasoning_budget_tokens: Option<serde_json::Value>,
|
||||
/// Where the Chat settings shared with every client are kept between starts.
|
||||
pub shared_settings_file: Option<PathBuf>,
|
||||
/// Unload the engine after this long without requests (`engine.idle_unload_s`).
|
||||
pub idle_unload: Option<Duration>,
|
||||
/// MCP servers (`mcp_servers`, `mcpServers`, `mcp_config_file`); empty when there are none.
|
||||
pub mcp_servers: std::collections::BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
|
||||
/// The `mcp` block: timeouts and caps.
|
||||
pub mcp_settings: crate::mcp::Settings,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
@@ -49,6 +67,17 @@ struct FileConfig {
|
||||
bind: Option<String>,
|
||||
model: Option<String>,
|
||||
engine: Option<FileEngine>,
|
||||
aliases: Option<serde_json::Value>,
|
||||
cors_origins: Option<serde_json::Value>,
|
||||
trusted_origins: Option<serde_json::Value>,
|
||||
sampling: Option<serde_json::Value>,
|
||||
reasoning_budget_tokens: Option<serde_json::Value>,
|
||||
shared_settings_file: Option<PathBuf>,
|
||||
mcp_servers: Option<serde_json::Value>,
|
||||
#[serde(rename = "mcpServers")]
|
||||
mcp_servers_desktop: Option<serde_json::Value>,
|
||||
mcp_config_file: Option<PathBuf>,
|
||||
mcp: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -61,6 +90,140 @@ struct FileEngine {
|
||||
generation_timeout_s: Option<u64>,
|
||||
max_restarts: Option<u32>,
|
||||
tokenizer_dir: Option<PathBuf>,
|
||||
/// Start unloaded; the first request loads the engine.
|
||||
#[serde(default)]
|
||||
lazy_load: bool,
|
||||
/// Unload after this many idle seconds so other programs can use the GPU.
|
||||
idle_unload_s: Option<f64>,
|
||||
/// Reload only when this much VRAM is free (MiB).
|
||||
min_free_vram_mib: Option<u64>,
|
||||
/// Command run before every reload and restart (a shell line or an argv list).
|
||||
before_load: Option<crate::worker::BeforeLoad>,
|
||||
/// No engine line for this long during a request ends it (the stall watchdog).
|
||||
stall_timeout_s: Option<u64>,
|
||||
/// A control vector on the residual stream (steering); requests switch it per request.
|
||||
control_vector: Option<ControlVector>,
|
||||
}
|
||||
|
||||
/// `--control-vector-scaled`, `--cvec-mode`, `--cvec-dir`, `--control-vector-layer-range`.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ControlVector {
|
||||
files: Vec<ControlVectorFile>,
|
||||
/// `add` (default) or `project`.
|
||||
mode: Option<String>,
|
||||
/// `per-layer` (default) or `single:L` (project mode).
|
||||
dir: Option<String>,
|
||||
/// First and last steered layer, inclusive.
|
||||
layer_range: Option<[i32; 2]>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ControlVectorFile {
|
||||
path: PathBuf,
|
||||
scale: f32,
|
||||
}
|
||||
|
||||
impl ControlVector {
|
||||
/// The engine arguments for this vector after checking the files (GGUF control vectors with
|
||||
/// F32 `direction.<layer>` tensors of one width), so a typo stops the start, not the load.
|
||||
fn engine_args(&self) -> Result<Vec<String>, String> {
|
||||
if self.files.is_empty() || self.files.len() > 16 {
|
||||
return Err("control_vector.files needs 1 to 16 files".into());
|
||||
}
|
||||
let mode = match self.mode.as_deref() {
|
||||
None => leleka_serving_policy::cvec::Mode::Add,
|
||||
Some(text) => leleka_serving_policy::cvec::parse_mode(text)?,
|
||||
};
|
||||
let single = match self.dir.as_deref() {
|
||||
None => -1,
|
||||
Some(text) => leleka_serving_policy::cvec::parse_dir(text)?,
|
||||
};
|
||||
if single >= 0 && mode != leleka_serving_policy::cvec::Mode::Project {
|
||||
return Err("control_vector.dir single:L needs mode project".into());
|
||||
}
|
||||
let mut width: Option<u64> = None;
|
||||
let mut list = Vec::new();
|
||||
for file in &self.files {
|
||||
if !file.path.is_absolute()
|
||||
|| file.path.to_str().is_none_or(|p| p.contains([',', '\n']))
|
||||
{
|
||||
return Err("control_vector file paths must be absolute, without commas".into());
|
||||
}
|
||||
if !file.scale.is_finite() {
|
||||
return Err("control_vector scale must be finite".into());
|
||||
}
|
||||
let metadata = fs::metadata(&file.path)
|
||||
.map_err(|error| format!("control_vector {}: {error}", file.path.display()))?;
|
||||
if !metadata.is_file() || metadata.len() > 256 * 1024 * 1024 {
|
||||
return Err(format!(
|
||||
"control_vector {} must be a regular file of at most 256 MiB",
|
||||
file.path.display()
|
||||
));
|
||||
}
|
||||
let parsed = leleka_serving_policy::cvec::parse_gguf(
|
||||
&fs::read(&file.path)
|
||||
.map_err(|error| format!("control_vector {}: {error}", file.path.display()))?,
|
||||
)
|
||||
.map_err(|error| format!("control_vector {}: {error}", file.path.display()))?;
|
||||
if parsed.architecture.as_deref() != Some("controlvector") {
|
||||
return Err(format!(
|
||||
"control_vector {}: not a control vector GGUF (general.architecture is not 'controlvector')",
|
||||
file.path.display()
|
||||
));
|
||||
}
|
||||
let mut found = false;
|
||||
for tensor in parsed
|
||||
.tensors
|
||||
.iter()
|
||||
.filter(|t| t.name.starts_with("direction."))
|
||||
{
|
||||
if tensor.kind != 0 {
|
||||
return Err(format!(
|
||||
"control_vector {}: {} must be f32",
|
||||
file.path.display(),
|
||||
tensor.name
|
||||
));
|
||||
}
|
||||
if *width.get_or_insert(tensor.elements) != tensor.elements {
|
||||
return Err(format!(
|
||||
"control_vector {}: direction tensors differ in width",
|
||||
file.path.display()
|
||||
));
|
||||
}
|
||||
found = true;
|
||||
}
|
||||
if !found {
|
||||
return Err(format!(
|
||||
"control_vector {}: no direction.<layer> tensors",
|
||||
file.path.display()
|
||||
));
|
||||
}
|
||||
list.push(format!("{}:{}", file.path.display(), file.scale));
|
||||
}
|
||||
let mut args = vec!["--control-vector-scaled".to_owned(), list.join(",")];
|
||||
args.extend([
|
||||
"--cvec-mode".to_owned(),
|
||||
if mode == leleka_serving_policy::cvec::Mode::Project {
|
||||
"project"
|
||||
} else {
|
||||
"add"
|
||||
}
|
||||
.to_owned(),
|
||||
]);
|
||||
if let Some(dir) = &self.dir {
|
||||
args.extend(["--cvec-dir".to_owned(), dir.clone()]);
|
||||
}
|
||||
if let Some([first, last]) = self.layer_range {
|
||||
args.extend([
|
||||
"--control-vector-layer-range".to_owned(),
|
||||
first.to_string(),
|
||||
last.to_string(),
|
||||
]);
|
||||
}
|
||||
Ok(args)
|
||||
}
|
||||
}
|
||||
|
||||
impl Config {
|
||||
@@ -70,14 +233,12 @@ impl Config {
|
||||
|
||||
/// An explicit CLI config path takes precedence over STRATA_CONFIG.
|
||||
pub fn load_with_path(path: Option<&Path>) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
let file = match path
|
||||
let config_path = path
|
||||
.map(|p| p.as_os_str().to_owned())
|
||||
.or_else(|| env::var_os("STRATA_CONFIG"))
|
||||
{
|
||||
Some(path) => {
|
||||
let path = PathBuf::from(path);
|
||||
serde_json::from_str::<FileConfig>(&fs::read_to_string(path)?)?
|
||||
}
|
||||
.map(PathBuf::from);
|
||||
let file = match &config_path {
|
||||
Some(path) => serde_json::from_str::<FileConfig>(&fs::read_to_string(path)?)?,
|
||||
None => FileConfig::default(),
|
||||
};
|
||||
|
||||
@@ -157,6 +318,25 @@ impl Config {
|
||||
if generation_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) {
|
||||
return Err("generation_timeout_s must be between 1 and 86400".into());
|
||||
}
|
||||
let engine_file = file.engine.as_ref();
|
||||
let mut args = args;
|
||||
if let Some(vector) = engine_file.and_then(|engine| engine.control_vector.as_ref()) {
|
||||
if args
|
||||
.iter()
|
||||
.any(|arg| arg.starts_with("--control-vector") || arg.starts_with("--cvec-"))
|
||||
{
|
||||
return Err("control_vector owns the --control-vector*/--cvec-* arguments; remove them from engine args".into());
|
||||
}
|
||||
args.extend(vector.engine_args()?);
|
||||
}
|
||||
let stall_timeout_s = engine_file.and_then(|engine| engine.stall_timeout_s);
|
||||
if stall_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) {
|
||||
return Err("stall_timeout_s must be between 1 and 86400".into());
|
||||
}
|
||||
let idle_unload_s = engine_file.and_then(|engine| engine.idle_unload_s);
|
||||
if idle_unload_s.is_some_and(|seconds| !seconds.is_finite() || seconds < 0.0) {
|
||||
return Err("idle_unload_s must be a non-negative number".into());
|
||||
}
|
||||
let worker = match executable {
|
||||
Some(executable) if !executable.is_empty() => Some(WorkerConfig {
|
||||
executable,
|
||||
@@ -165,6 +345,12 @@ impl Config {
|
||||
startup_timeout: Duration::from_secs(startup_timeout_s),
|
||||
generation_timeout: generation_timeout_s.map(Duration::from_secs),
|
||||
max_restarts,
|
||||
lazy: engine_file.is_some_and(|engine| engine.lazy_load),
|
||||
stall_timeout: stall_timeout_s.map(Duration::from_secs),
|
||||
before_load: engine_file.and_then(|engine| engine.before_load.clone()),
|
||||
min_free_vram_mib: engine_file
|
||||
.and_then(|engine| engine.min_free_vram_mib)
|
||||
.unwrap_or(0),
|
||||
}),
|
||||
Some(_) => return Err("engine executable cannot be empty".into()),
|
||||
None if !args.is_empty() => return Err("engine args require an executable".into()),
|
||||
@@ -257,7 +443,91 @@ impl Config {
|
||||
"response_history_dir must be an absolute non-root path without '..'".into(),
|
||||
);
|
||||
}
|
||||
let aliases = match &file.aliases {
|
||||
None => Vec::new(),
|
||||
Some(value) => leleka_serving_policy::shared::normalize_aliases(
|
||||
value,
|
||||
model.as_deref().unwrap_or(""),
|
||||
)
|
||||
.map_err(|message| format!("config {message}"))?,
|
||||
};
|
||||
if aliases.iter().any(|alias| {
|
||||
alias.len() > 180
|
||||
|| !alias
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
|
||||
}) {
|
||||
return Err(
|
||||
"aliases require 1..180 ASCII letters, digits, dots, hyphens or underscores".into(),
|
||||
);
|
||||
}
|
||||
let cors_origins = leleka_serving_policy::cors::origins_of(
|
||||
file.cors_origins
|
||||
.as_ref()
|
||||
.unwrap_or(&serde_json::Value::Null),
|
||||
"cors_origins",
|
||||
true,
|
||||
)?;
|
||||
let trusted_origins = leleka_serving_policy::cors::origins_of(
|
||||
file.trusted_origins
|
||||
.as_ref()
|
||||
.unwrap_or(&serde_json::Value::Null),
|
||||
"trusted_origins",
|
||||
false,
|
||||
)?;
|
||||
let sampling = leleka_serving_policy::shared::sampling_defaults_from_config(
|
||||
file.sampling.as_ref().unwrap_or(&serde_json::Value::Null),
|
||||
)?;
|
||||
for ignored in &sampling.ignored {
|
||||
eprintln!("config sampling.{ignored}: unknown key, ignored");
|
||||
}
|
||||
if let Some(value) = &file.reasoning_budget_tokens {
|
||||
leleka_serving_policy::reasoning::parse_budget(None, Some(value))
|
||||
.map_err(|message| format!("config {message}"))?;
|
||||
}
|
||||
let shared_settings_file = file.shared_settings_file.clone().or_else(|| {
|
||||
config_path
|
||||
.as_deref()
|
||||
.map(crate::settings::default_shared_path)
|
||||
});
|
||||
let mut mcp_servers = std::collections::BTreeMap::new();
|
||||
let null = serde_json::Value::Null;
|
||||
mcp_servers.extend(crate::mcp::servers_from(
|
||||
file.mcp_servers.as_ref().unwrap_or(&null),
|
||||
"config mcp_servers",
|
||||
)?);
|
||||
mcp_servers.extend(crate::mcp::servers_from(
|
||||
file.mcp_servers_desktop.as_ref().unwrap_or(&null),
|
||||
"config mcpServers",
|
||||
)?);
|
||||
if let Some(path) = &file.mcp_config_file {
|
||||
// Claude Desktop's format; a name in both takes this file's entry.
|
||||
let location = format!("mcp_config_file {}", path.display());
|
||||
let text = std::fs::read_to_string(path)
|
||||
.map_err(|error| format!("[strata] {location}: {error}"))?;
|
||||
let data: serde_json::Value = serde_json::from_str(text.trim_start_matches('\u{feff}'))
|
||||
.map_err(|error| format!("[strata] {location}: {error}"))?;
|
||||
let block = data
|
||||
.get("mcpServers")
|
||||
.or_else(|| data.get("mcp_servers"))
|
||||
.ok_or_else(|| {
|
||||
format!("[strata] {location}: expected {{\"mcpServers\": {{...}}}}")
|
||||
})?;
|
||||
mcp_servers.extend(crate::mcp::servers_from(block, &location)?);
|
||||
}
|
||||
let mcp_settings = crate::mcp::settings_from(file.mcp.as_ref().unwrap_or(&null))?;
|
||||
Ok(Self {
|
||||
mcp_servers,
|
||||
mcp_settings,
|
||||
aliases,
|
||||
cors_origins,
|
||||
trusted_origins,
|
||||
sampling,
|
||||
reasoning_budget_tokens: file.reasoning_budget_tokens,
|
||||
shared_settings_file,
|
||||
idle_unload: idle_unload_s
|
||||
.filter(|seconds| *seconds > 0.0)
|
||||
.map(Duration::from_secs_f64),
|
||||
mtp_pack: file.mtp_pack,
|
||||
response_history_dir,
|
||||
assets: file.assets,
|
||||
@@ -365,3 +635,190 @@ fn optional_env(name: &str) -> Result<Option<String>, env::VarError> {
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn temp(name: &str) -> PathBuf {
|
||||
let dir = env::temp_dir().join(format!("strata-config-{}-{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn load(dir: &Path, value: serde_json::Value) -> Result<Config, String> {
|
||||
let path = dir.join("config.json");
|
||||
fs::write(&path, value.to_string()).unwrap();
|
||||
Config::load_with_path(Some(&path)).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn control_vector_file(
|
||||
dir: &Path,
|
||||
name: &str,
|
||||
architecture: &str,
|
||||
kind: u32,
|
||||
elements: u64,
|
||||
) -> PathBuf {
|
||||
let mut bytes = b"GGUF".to_vec();
|
||||
bytes.extend_from_slice(&3u32.to_le_bytes());
|
||||
bytes.extend_from_slice(&1u64.to_le_bytes());
|
||||
bytes.extend_from_slice(&1u64.to_le_bytes());
|
||||
let key = b"general.architecture";
|
||||
bytes.extend_from_slice(&(key.len() as u64).to_le_bytes());
|
||||
bytes.extend_from_slice(key);
|
||||
bytes.extend_from_slice(&8u32.to_le_bytes());
|
||||
bytes.extend_from_slice(&(architecture.len() as u64).to_le_bytes());
|
||||
bytes.extend_from_slice(architecture.as_bytes());
|
||||
let tensor = b"direction.1";
|
||||
bytes.extend_from_slice(&(tensor.len() as u64).to_le_bytes());
|
||||
bytes.extend_from_slice(tensor);
|
||||
bytes.extend_from_slice(&1u32.to_le_bytes());
|
||||
bytes.extend_from_slice(&elements.to_le_bytes());
|
||||
bytes.extend_from_slice(&kind.to_le_bytes());
|
||||
bytes.extend_from_slice(&0u64.to_le_bytes());
|
||||
while !bytes.len().is_multiple_of(32) {
|
||||
bytes.push(0);
|
||||
}
|
||||
bytes.extend(std::iter::repeat_n(0u8, elements as usize * 4));
|
||||
let path = dir.join(name);
|
||||
fs::write(&path, bytes).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serving_settings_are_read_and_checked_at_start() {
|
||||
let dir = temp("serving");
|
||||
let config = load(
|
||||
&dir,
|
||||
json!({
|
||||
"model": "strata-test",
|
||||
"aliases": ["gpt-local", " strata-test ", "gpt-local"],
|
||||
"cors_origins": ["https://chat.example.com/", "*"],
|
||||
"trusted_origins": "https://strata.example.com",
|
||||
"sampling": {"temperature": 0.6, "top_k": 30, "nonsense": 1},
|
||||
"reasoning_budget_tokens": 128,
|
||||
"engine": {"executable": "/bin/engine", "lazy_load": true, "idle_unload_s": 90,
|
||||
"min_free_vram_mib": 20000, "before_load": "echo hook",
|
||||
"stall_timeout_s": 120}
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(config.aliases, vec!["gpt-local"]);
|
||||
assert_eq!(config.cors_origins, vec!["https://chat.example.com", "*"]);
|
||||
assert_eq!(config.trusted_origins, vec!["https://strata.example.com"]);
|
||||
assert_eq!(config.sampling.sampling.top_k, Some(30));
|
||||
assert_eq!(config.sampling.ignored, vec!["nonsense"]);
|
||||
assert_eq!(config.idle_unload, Some(Duration::from_secs(90)));
|
||||
assert_eq!(
|
||||
config.shared_settings_file,
|
||||
Some(dir.join("config.shared-settings.json"))
|
||||
);
|
||||
let worker = config.worker.unwrap();
|
||||
assert!(worker.lazy);
|
||||
assert_eq!(worker.min_free_vram_mib, 20000);
|
||||
assert_eq!(worker.stall_timeout, Some(Duration::from_secs(120)));
|
||||
assert_eq!(
|
||||
worker.before_load,
|
||||
Some(crate::worker::BeforeLoad::Shell("echo hook".into()))
|
||||
);
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_serving_settings_stop_the_start() {
|
||||
let dir = temp("serving-bad");
|
||||
for (name, value) in [
|
||||
("sampling", json!({"sampling": {"top_k": 100}})),
|
||||
("cors", json!({"cors_origins": ["https://a.example/path"]})),
|
||||
("trusted", json!({"trusted_origins": ["*"]})),
|
||||
("aliases", json!({"aliases": [1]})),
|
||||
("alias charset", json!({"aliases": ["has space"]})),
|
||||
("budget", json!({"reasoning_budget_tokens": "many"})),
|
||||
(
|
||||
"stall",
|
||||
json!({"engine": {"executable": "/bin/e", "stall_timeout_s": 0}}),
|
||||
),
|
||||
(
|
||||
"idle",
|
||||
json!({"engine": {"executable": "/bin/e", "idle_unload_s": -1}}),
|
||||
),
|
||||
] {
|
||||
assert!(load(&dir, value).is_err(), "{name}");
|
||||
}
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_control_vector_becomes_engine_arguments_after_a_preflight() {
|
||||
let dir = temp("cvec");
|
||||
let good = control_vector_file(&dir, "good.gguf", "controlvector", 0, 8);
|
||||
let config = load(
|
||||
&dir,
|
||||
json!({"engine": {"executable": "/bin/engine", "args": ["--max-context", "4096"],
|
||||
"control_vector": {"files": [{"path": good, "scale": 0.5}], "mode": "project",
|
||||
"dir": "single:3", "layer_range": [2, 40]}}}),
|
||||
)
|
||||
.unwrap();
|
||||
let args = config.worker.unwrap().args;
|
||||
assert_eq!(args[..2], ["--max-context", "4096"]);
|
||||
assert_eq!(args[2], "--control-vector-scaled");
|
||||
assert_eq!(args[3], format!("{}:0.5", good.display()));
|
||||
assert_eq!(
|
||||
args[4..],
|
||||
[
|
||||
"--cvec-mode",
|
||||
"project",
|
||||
"--cvec-dir",
|
||||
"single:3",
|
||||
"--control-vector-layer-range",
|
||||
"2",
|
||||
"40"
|
||||
]
|
||||
);
|
||||
for (name, value) in [
|
||||
(
|
||||
"wrong arch",
|
||||
control_vector_file(&dir, "arch.gguf", "llama", 0, 8),
|
||||
),
|
||||
(
|
||||
"f16",
|
||||
control_vector_file(&dir, "f16.gguf", "controlvector", 1, 8),
|
||||
),
|
||||
] {
|
||||
let result = load(
|
||||
&dir,
|
||||
json!({"engine": {"executable": "/bin/e", "control_vector": {"files": [{"path": value, "scale": 1.0}]}}}),
|
||||
);
|
||||
assert!(result.is_err(), "{name}");
|
||||
}
|
||||
for bad in [
|
||||
json!({"files": []}),
|
||||
json!({"files": [{"path": "relative.gguf", "scale": 1.0}]}),
|
||||
json!({"files": [{"path": dir.join("missing.gguf"), "scale": 1.0}]}),
|
||||
json!({"files": [{"path": good, "scale": 1.0}], "dir": "single:2"}),
|
||||
json!({"files": [{"path": good, "scale": 1.0}], "mode": "mix"}),
|
||||
json!({"files": [{"path": good, "scale": 1.0}], "dir": "everywhere"}),
|
||||
] {
|
||||
assert!(
|
||||
load(
|
||||
&dir,
|
||||
json!({"engine": {"executable": "/bin/e", "control_vector": bad}})
|
||||
)
|
||||
.is_err(),
|
||||
"{bad}"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
load(
|
||||
&dir,
|
||||
json!({"engine": {"executable": "/bin/e", "args": ["--cvec-mode", "add"],
|
||||
"control_vector": {"files": [{"path": good, "scale": 1.0}]}}})
|
||||
)
|
||||
.is_err(),
|
||||
"owned arguments"
|
||||
);
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,6 +42,18 @@ impl Selection {
|
||||
choose(self.policy, devices, Some(std::slice::from_ref(&self.uuid))).map(|_| ())
|
||||
}
|
||||
}
|
||||
/// Free VRAM in MiB of the selected GPU, or of the freest visible one; `None` when it cannot be read
|
||||
/// (then nothing is refused, as in the Original's `free_vram_mib`).
|
||||
pub async fn free_mib(selection: Option<&Selection>) -> Option<u64> {
|
||||
let devices = inventory().await.ok()?;
|
||||
match selection {
|
||||
Some(selection) => devices
|
||||
.iter()
|
||||
.find(|d| d.uuid == selection.uuid)
|
||||
.map(|d| d.free),
|
||||
None => devices.iter().map(|d| d.free).max(),
|
||||
}
|
||||
}
|
||||
struct Device {
|
||||
uuid: String,
|
||||
free: u64,
|
||||
|
||||
@@ -60,3 +60,11 @@ pub mod cuda_memory;
|
||||
pub mod service_switch;
|
||||
|
||||
pub mod queue;
|
||||
|
||||
pub mod sampling;
|
||||
|
||||
pub mod server_api;
|
||||
|
||||
pub mod settings;
|
||||
|
||||
pub mod mcp;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::{env, io::Read, path::Path, sync::Arc};
|
||||
use std::{env, io::Read, path::Path, sync::Arc, time::Duration};
|
||||
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
@@ -822,30 +822,74 @@ async fn serve(config_path: Option<&Path>) -> Result<(), Box<dyn std::error::Err
|
||||
};
|
||||
config.provision().await?;
|
||||
let listener = tokio::net::TcpListener::bind(config.bind).await?;
|
||||
let mut settings = strata_control::settings::Settings::new(config.sampling.clone())
|
||||
.with_reasoning_budget(config.reasoning_budget_tokens.clone());
|
||||
if let Some(path) = config.shared_settings_file.clone() {
|
||||
settings = settings.with_shared_file(path);
|
||||
}
|
||||
let mut state = app::AppState {
|
||||
queue_timeout: config.queue_timeout,
|
||||
lifecycle: strata_control::lifecycle::Lifecycle::new(config.max_in_flight_requests)?,
|
||||
response_history: Arc::new(tokio::sync::RwLock::new(response_history)),
|
||||
api_key: config.api_key.clone(),
|
||||
model: config.model.clone(),
|
||||
settings: Arc::new(settings),
|
||||
aliases: Arc::new(config.aliases.clone()),
|
||||
cors: Arc::new(leleka_serving_policy::cors::Cors::new(
|
||||
config.cors_origins.clone(),
|
||||
)),
|
||||
trusted_origins: Arc::new(config.trusted_origins.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
if !config.mcp_servers.is_empty() {
|
||||
let hub = Arc::new(strata_control::mcp::Hub::new(
|
||||
std::mem::take(&mut config.mcp_servers),
|
||||
config.mcp_settings.clone(),
|
||||
));
|
||||
state.mcp = Some(hub.clone());
|
||||
// Servers start in the background (npx may download a package first); GET /mcp shows progress.
|
||||
tokio::spawn(async move { hub.start().await });
|
||||
}
|
||||
if config.cors_origins.iter().any(|o| o == "*") && config.api_key.is_none() {
|
||||
eprintln!("CORS on /v1/*: WARNING: any web page may use the model (no API key)");
|
||||
}
|
||||
if let Some(path) = config.tokenizer_dir.as_deref() {
|
||||
state.tokenizer = Some(Arc::new(tokenizer::Tokenizer::from_assets(path)?));
|
||||
state.chat_template = std::fs::read_to_string(path.join("chat_template.jinja"))
|
||||
.ok()
|
||||
.map(Arc::from);
|
||||
}
|
||||
let (shutdown_tx, shutdown_rx) = watch::channel(false);
|
||||
let worker_task = config.worker.map(|config| {
|
||||
let (sender, receiver) = mpsc::channel(16);
|
||||
let (control_sender, control_receiver) = mpsc::channel(16);
|
||||
state.generation = Some(sender);
|
||||
tokio::spawn(worker::run_with_requests(
|
||||
state.control = Some(control_sender);
|
||||
tokio::spawn(worker::run_supervised(
|
||||
config,
|
||||
state.worker.clone(),
|
||||
shutdown_rx,
|
||||
receiver,
|
||||
control_receiver,
|
||||
))
|
||||
});
|
||||
if let (Some(idle), true) = (config.idle_unload, state.control.is_some()) {
|
||||
eprintln!(
|
||||
"the model unloads after {} s without requests",
|
||||
idle.as_secs_f64()
|
||||
);
|
||||
let poll = Duration::from_secs_f64(leleka_serving_policy::idle::poll_interval_s(
|
||||
idle.as_secs_f64(),
|
||||
));
|
||||
tokio::spawn(strata_control::server_api::idle_unload_loop(
|
||||
state.clone(),
|
||||
idle,
|
||||
poll,
|
||||
));
|
||||
}
|
||||
eprintln!("strata-control listening on {}", listener.local_addr()?);
|
||||
let server_shutdown = shutdown_tx.clone();
|
||||
let state_mcp = state.mcp.clone();
|
||||
let lifecycle = state.lifecycle.clone();
|
||||
let shutdown_grace = config.shutdown_grace;
|
||||
let result = axum::serve(listener, app::router(state))
|
||||
@@ -859,6 +903,9 @@ async fn serve(config_path: Option<&Path>) -> Result<(), Box<dyn std::error::Err
|
||||
})
|
||||
.await;
|
||||
let _ = shutdown_tx.send(true);
|
||||
if let Some(hub) = &state_mcp {
|
||||
hub.close().await;
|
||||
}
|
||||
if let Some(task) = worker_task {
|
||||
task.await?;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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;
|
||||
|
||||
@@ -15,6 +15,31 @@ fn record(id: &str) -> Value {
|
||||
json!({"id":id,"object":"model","created":0,"owned_by":"local"})
|
||||
}
|
||||
|
||||
/// The model and each configured alias (`alias_of` names the model), like the Original; an engine
|
||||
/// that is unloaded on purpose says so (`status`) and still lists: it loads on use.
|
||||
async fn records(state: &AppState) -> Vec<Value> {
|
||||
let unloaded = state.worker.read().await.state == crate::worker::WorkerState::Unloaded;
|
||||
let mark = |mut value: Value| {
|
||||
if unloaded {
|
||||
value["status"] = json!({"value": "unloaded"});
|
||||
}
|
||||
value
|
||||
};
|
||||
let Some(model) = state.model.as_deref() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out = vec![mark(record(model))];
|
||||
if !state.aliases.is_empty() {
|
||||
out[0]["aliases"] = json!(*state.aliases);
|
||||
}
|
||||
for alias in state.aliases.iter() {
|
||||
let mut value = mark(record(alias));
|
||||
value["alias_of"] = json!(model);
|
||||
out.push(value);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn query_error(query: Option<String>) -> Option<Response> {
|
||||
query.filter(|q| !q.is_empty()).map(|_| {
|
||||
(
|
||||
@@ -32,7 +57,7 @@ pub async fn list(State(state): State<AppState>, RawQuery(query): RawQuery) -> R
|
||||
if let Some(error) = query_error(query) {
|
||||
return error;
|
||||
}
|
||||
let data: Vec<_> = state.model.as_deref().map(record).into_iter().collect();
|
||||
let data = records(&state).await;
|
||||
Json(json!({"object":"list","data":data})).into_response()
|
||||
}
|
||||
|
||||
@@ -44,8 +69,12 @@ pub async fn retrieve(
|
||||
if let Some(error) = query_error(query) {
|
||||
return error;
|
||||
}
|
||||
if state.model.as_deref() == Some(id.as_str()) {
|
||||
return Json(record(&id)).into_response();
|
||||
if let Some(found) = records(&state)
|
||||
.await
|
||||
.into_iter()
|
||||
.find(|value| value["id"] == id.as_str())
|
||||
{
|
||||
return Json(found).into_response();
|
||||
}
|
||||
(
|
||||
StatusCode::NOT_FOUND,
|
||||
|
||||
@@ -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),
|
||||
},
|
||||
|
||||
+369
-12
@@ -500,6 +500,17 @@ pub struct CreateRequest {
|
||||
pub tool_choice: Option<Value>,
|
||||
pub temperature: Option<f64>,
|
||||
pub top_p: Option<f64>,
|
||||
/// Original-server sampling extensions (top level, like `serve/server.py`): see `sampling`.
|
||||
pub top_k: Option<i64>,
|
||||
pub min_p: Option<f64>,
|
||||
pub repetition_penalty: Option<f64>,
|
||||
pub frequency_penalty: Option<f64>,
|
||||
pub presence_penalty: Option<f64>,
|
||||
pub penalty_last_n: Option<i64>,
|
||||
pub seed: Option<u64>,
|
||||
pub strata_tune: Option<crate::sampling::Tune>,
|
||||
pub experimental_speed_projection: Option<bool>,
|
||||
pub reasoning_budget_tokens: Option<Value>,
|
||||
pub truncation: Option<String>,
|
||||
pub metadata: Option<Map<String, Value>>,
|
||||
pub store: Option<bool>,
|
||||
@@ -528,6 +539,53 @@ pub enum TextFormat {
|
||||
}
|
||||
|
||||
impl CreateRequest {
|
||||
/// The request's sampling fields as the Original's serving layer reads them.
|
||||
pub fn sampling(&self) -> leleka_sampler_ref::RequestSampling {
|
||||
leleka_sampler_ref::RequestSampling {
|
||||
temperature: self.temperature,
|
||||
top_p: self.top_p,
|
||||
top_k: self.top_k,
|
||||
min_p: self.min_p,
|
||||
repetition_penalty: self.repetition_penalty,
|
||||
frequency_penalty: self.frequency_penalty,
|
||||
presence_penalty: self.presence_penalty,
|
||||
penalty_last_n: self.penalty_last_n,
|
||||
seed: self.seed,
|
||||
}
|
||||
}
|
||||
|
||||
/// Fill what the request left out from the server defaults: the config's `sampling` block,
|
||||
/// then the shared Chat settings (`{**config, **shared}`, request fields win, an explicit
|
||||
/// `temperature: 0` stays greedy), the shared `max_tokens`, and the shared reasoning effort.
|
||||
pub fn apply_defaults(&mut self, settings: &crate::settings::Settings) {
|
||||
let merged = settings.merged();
|
||||
let shared = settings.shared();
|
||||
let effective =
|
||||
leleka_sampler_ref::RequestSampling::overlay(&merged.sampling, &self.sampling());
|
||||
self.temperature = effective.temperature;
|
||||
self.top_p = effective.top_p;
|
||||
self.top_k = effective.top_k;
|
||||
self.min_p = effective.min_p;
|
||||
self.repetition_penalty = effective.repetition_penalty;
|
||||
self.frequency_penalty = effective.frequency_penalty;
|
||||
self.presence_penalty = effective.presence_penalty;
|
||||
self.penalty_last_n = effective.penalty_last_n;
|
||||
self.seed = effective.seed;
|
||||
self.experimental_speed_projection = self
|
||||
.experimental_speed_projection
|
||||
.or(merged.experimental_speed_projection);
|
||||
if self.max_output_tokens.is_none()
|
||||
&& let Some(limit) = shared.max_tokens
|
||||
{
|
||||
self.max_output_tokens = Some(limit.min(u64::from(u32::MAX)) as u32);
|
||||
}
|
||||
if self.reasoning.is_none()
|
||||
&& let Some(effort) = &shared.reasoning_effort
|
||||
{
|
||||
self.reasoning = Some(json!({"effort": effort}));
|
||||
}
|
||||
}
|
||||
|
||||
fn forced_tool(&self) -> Option<&str> {
|
||||
self.tool_choice
|
||||
.as_ref()
|
||||
@@ -608,17 +666,20 @@ impl CreateRequest {
|
||||
if self.max_output_tokens == Some(0) {
|
||||
return Err(("max_output_tokens", "max_output_tokens must be positive"));
|
||||
}
|
||||
if self
|
||||
.temperature
|
||||
.is_some_and(|value| !value.is_finite() || !(0.0..=2.0).contains(&value))
|
||||
{
|
||||
return Err(("temperature", "temperature must be between 0 and 2"));
|
||||
crate::sampling::validate(&self.sampling())?;
|
||||
if let Some(tune) = &self.strata_tune {
|
||||
crate::sampling::validate_tune(tune)?;
|
||||
}
|
||||
if self
|
||||
.top_p
|
||||
.is_some_and(|value| !value.is_finite() || !(0.0..=1.0).contains(&value))
|
||||
if leleka_serving_policy::reasoning::parse_budget(
|
||||
self.reasoning_budget_tokens.as_ref(),
|
||||
None,
|
||||
)
|
||||
.is_err()
|
||||
{
|
||||
return Err(("top_p", "top_p must be between 0 and 1"));
|
||||
return Err((
|
||||
"reasoning_budget_tokens",
|
||||
"reasoning_budget_tokens must be a whole number of tokens (0: no budget)",
|
||||
));
|
||||
}
|
||||
if let Some(TextOptions {
|
||||
format: TextFormat::JsonSchema { name, schema, .. },
|
||||
@@ -773,7 +834,7 @@ fn parse_request(
|
||||
if state
|
||||
.model
|
||||
.as_ref()
|
||||
.is_some_and(|model| model != &request.model)
|
||||
.is_some_and(|model| model != &request.model && !state.aliases.contains(&request.model))
|
||||
{
|
||||
return Err(Box::new(api_error(
|
||||
StatusCode::NOT_FOUND,
|
||||
@@ -910,6 +971,9 @@ pub async fn create(
|
||||
Ok(request) => request,
|
||||
Err(error) => return *error,
|
||||
};
|
||||
if let Err(response) = crate::server_api::ensure_loaded(&state).await {
|
||||
return *response;
|
||||
}
|
||||
if state.worker.read().await.state != WorkerState::Ready {
|
||||
return api_error(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
@@ -937,6 +1001,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 +1022,11 @@ 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,
|
||||
reasoning: reasoning_plan(&request, &state, tokenizer),
|
||||
};
|
||||
if request.stream {
|
||||
let (events, received) = mpsc::channel(16);
|
||||
@@ -1327,6 +1395,37 @@ impl ReasoningStream {
|
||||
}
|
||||
}
|
||||
|
||||
/// The reasoning-budget wrap-up for this request, if thinking is on and a budget is set (the
|
||||
/// request's `reasoning_budget_tokens`, else the config's).
|
||||
fn reasoning_plan(
|
||||
request: &CreateRequest,
|
||||
state: &AppState,
|
||||
tokenizer: &Arc<Tokenizer>,
|
||||
) -> Option<crate::wire::ReasoningPlan> {
|
||||
if !reasoning_enabled(request) {
|
||||
return None;
|
||||
}
|
||||
let budget = leleka_serving_policy::reasoning::parse_budget(
|
||||
request.reasoning_budget_tokens.as_ref(),
|
||||
state.settings.reasoning_budget_default(),
|
||||
)
|
||||
.ok()??;
|
||||
let wrap_up = tokenizer
|
||||
.encode(leleka_serving_policy::reasoning::WRAP_UP, true)
|
||||
.ok()?;
|
||||
let stop_ids = ["<|im_end|>", "<|endoftext|>"]
|
||||
.into_iter()
|
||||
.filter_map(|name| tokenizer.special_id(name))
|
||||
.collect();
|
||||
let bytes_of = tokenizer.clone();
|
||||
Some(crate::wire::ReasoningPlan {
|
||||
budget,
|
||||
wrap_up,
|
||||
stop_ids,
|
||||
token_bytes: Arc::new(move |id| bytes_of.decode_bytes(&[id]).unwrap_or_default()),
|
||||
})
|
||||
}
|
||||
|
||||
fn is_structured(request: &CreateRequest) -> bool {
|
||||
request
|
||||
.text
|
||||
@@ -4115,6 +4214,264 @@ mod tests {
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
/// Run one request through `route` against a fake worker and return the `Generate` it was handed.
|
||||
async fn captured_generate<F, Fut>(
|
||||
settings: crate::settings::Settings,
|
||||
body: Value,
|
||||
route: F,
|
||||
) -> (StatusCode, Option<Generate>)
|
||||
where
|
||||
F: FnOnce(
|
||||
State<AppState>,
|
||||
Result<Json<Value>, axum::extract::rejection::JsonRejection>,
|
||||
) -> Fut,
|
||||
Fut: std::future::Future<Output = Response>,
|
||||
{
|
||||
let (tokenizer, root) = test_tokenizer();
|
||||
let (sender, mut receiver) = mpsc::channel(1);
|
||||
let mut state = AppState::default();
|
||||
state.worker.write().await.state = WorkerState::Ready;
|
||||
state.tokenizer = Some(tokenizer);
|
||||
state.generation = Some(sender);
|
||||
state.settings = Arc::new(settings);
|
||||
let worker = tokio::spawn(async move {
|
||||
let command: GenerationCommand = receiver.recv().await?;
|
||||
let request = command.request.clone();
|
||||
let prompt_tokens = command.request.token_ids.len() as u64;
|
||||
let events = vec![
|
||||
Event::Token(79),
|
||||
Event::Token(75),
|
||||
Event::Done(Done {
|
||||
generated: 2,
|
||||
prompt_tokens,
|
||||
prompt_ms: 1.0,
|
||||
decode_ms: 2.0,
|
||||
finish: Finish::Stop,
|
||||
drafts_accepted: None,
|
||||
drafts_offered: None,
|
||||
reused: Some(0),
|
||||
expert_hits: None,
|
||||
expert_lookups: None,
|
||||
}),
|
||||
];
|
||||
match command.result {
|
||||
GenerationResult::Buffered(result) => {
|
||||
let _ = result.send(Ok(events));
|
||||
}
|
||||
GenerationResult::Streaming(sender) => {
|
||||
for event in events {
|
||||
let _ = sender.send(Ok(event)).await;
|
||||
}
|
||||
}
|
||||
GenerationResult::Finished => {}
|
||||
}
|
||||
Some(request)
|
||||
});
|
||||
let response = route(State(state), Ok(Json(body))).await;
|
||||
let status = response.status();
|
||||
let _ = to_bytes(response.into_body(), usize::MAX).await;
|
||||
// A request refused before the queue never reaches the worker; any other answer (even an
|
||||
// error about the fake worker's output) means the worker was handed the request.
|
||||
let generate = if matches!(
|
||||
status,
|
||||
StatusCode::BAD_REQUEST | StatusCode::NOT_FOUND | StatusCode::NOT_IMPLEMENTED
|
||||
) {
|
||||
worker.abort();
|
||||
None
|
||||
} else {
|
||||
worker.await.unwrap()
|
||||
};
|
||||
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 reasoning_budget_reaches_the_worker_only_when_thinking_is_on() {
|
||||
let thinking = |extra: Value| {
|
||||
merge(
|
||||
json!({"model": "strata-local", "input": "Hello", "reasoning": {"effort": "high"}}),
|
||||
extra,
|
||||
)
|
||||
};
|
||||
let (_, generate) = captured_generate(
|
||||
Default::default(),
|
||||
thinking(json!({"reasoning_budget_tokens": 20})),
|
||||
create,
|
||||
)
|
||||
.await;
|
||||
let plan = generate.unwrap().reasoning.expect("a plan");
|
||||
assert_eq!(plan.budget, 20);
|
||||
assert!(!plan.wrap_up.is_empty());
|
||||
assert_eq!(
|
||||
plan.stop_ids,
|
||||
vec![257],
|
||||
"<|im_end|> of the test vocabulary"
|
||||
);
|
||||
assert_eq!((plan.token_bytes)(79), b"O".to_vec());
|
||||
// Thinking off, a zero budget, or no budget at all: no plan.
|
||||
for body in [
|
||||
merge(
|
||||
json!({"model": "strata-local", "input": "Hello", "reasoning": {"effort": "none"}}),
|
||||
json!({"reasoning_budget_tokens": 20}),
|
||||
),
|
||||
thinking(json!({"reasoning_budget_tokens": 0})),
|
||||
thinking(json!({})),
|
||||
] {
|
||||
let (_, generate) = captured_generate(Default::default(), body, create).await;
|
||||
assert!(generate.unwrap().reasoning.is_none());
|
||||
}
|
||||
// The config's default applies, and a request can switch it off.
|
||||
let settings = crate::settings::Settings::default().with_reasoning_budget(Some(json!(50)));
|
||||
let (_, generate) = captured_generate(settings, thinking(json!({})), create).await;
|
||||
assert_eq!(generate.unwrap().reasoning.unwrap().budget, 50);
|
||||
let settings = crate::settings::Settings::default().with_reasoning_budget(Some(json!(50)));
|
||||
let (_, generate) = captured_generate(
|
||||
settings,
|
||||
thinking(json!({"reasoning_budget_tokens": 0})),
|
||||
create,
|
||||
)
|
||||
.await;
|
||||
assert!(generate.unwrap().reasoning.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn server_defaults_fill_what_the_request_leaves_out() {
|
||||
use leleka_serving_policy::shared::sampling_defaults_from_config;
|
||||
let config =
|
||||
sampling_defaults_from_config(&json!({"temperature": 0.3, "min_p": 0.1, "top_k": 10}))
|
||||
.unwrap();
|
||||
let settings = crate::settings::Settings::new(config);
|
||||
settings
|
||||
.set_shared(&json!({"temperature": 0.9, "seed": 4, "max_tokens": 77}))
|
||||
.unwrap();
|
||||
let body =
|
||||
json!({"model": "strata-local", "input": "Hello", "reasoning": {"effort": "none"}});
|
||||
let (_, generate) = captured_generate(settings, body.clone(), create).await;
|
||||
let generate = generate.unwrap();
|
||||
assert_eq!(generate.max_new, 77);
|
||||
assert!(
|
||||
generate
|
||||
.line()
|
||||
.unwrap()
|
||||
.starts_with("GEN 77 temperature=0.9 top_k=10 min_p=0.1 seed=4 "),
|
||||
"{}",
|
||||
generate.line().unwrap()
|
||||
);
|
||||
// The request wins, and an explicit 0 stays greedy.
|
||||
let settings = crate::settings::Settings::default();
|
||||
settings
|
||||
.set_shared(&json!({"temperature": 0.9, "max_tokens": 77}))
|
||||
.unwrap();
|
||||
let (_, generate) = captured_generate(
|
||||
settings,
|
||||
merge(body, json!({"temperature": 0, "max_output_tokens": 5})),
|
||||
create,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
generate
|
||||
.unwrap()
|
||||
.line()
|
||||
.unwrap()
|
||||
.split(' ')
|
||||
.take(2)
|
||||
.collect::<Vec<_>>(),
|
||||
["GEN", "5"]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn nonstreaming_tool_call_keeps_typed_arguments() {
|
||||
let (tokenizer, root) = test_tokenizer();
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
//! Request sampling plumbing shared by the Responses, Chat Completions and Messages routes.
|
||||
//!
|
||||
//! The Original's Python server takes every sampling field from the top level of the request body
|
||||
//! (`StrataEngine.sampling_keys`): `temperature`, `top_p`, `top_k`, `min_p`, `repetition_penalty`,
|
||||
//! `frequency_penalty`, `presence_penalty`, `penalty_last_n`, `seed`, plus the engine knobs
|
||||
//! `strata_tune` and `experimental_speed_projection`, and `reasoning_budget_tokens`. This module
|
||||
//! validates them against the Original's defaults and ranges (`leleka-sampler-ref`) and turns them
|
||||
//! into the `GEN` request. Chat and Messages forward those keys verbatim into the native Responses
|
||||
//! request, so one type validates everything.
|
||||
|
||||
use leleka_sampler_ref::RequestSampling;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::wire::EngineTune;
|
||||
|
||||
/// Top-level body keys that the Chat and Messages adapters pass through to the native request
|
||||
/// unchanged. Removed before their own `deny_unknown_fields` parse.
|
||||
pub const EXTENSION_KEYS: [&str; 10] = [
|
||||
"top_k",
|
||||
"min_p",
|
||||
"repetition_penalty",
|
||||
"frequency_penalty",
|
||||
"presence_penalty",
|
||||
"penalty_last_n",
|
||||
"seed",
|
||||
"strata_tune",
|
||||
"experimental_speed_projection",
|
||||
"reasoning_budget_tokens",
|
||||
];
|
||||
|
||||
/// Split an adapter request body into `(rest, extensions)`.
|
||||
pub fn split_extensions(mut body: Value) -> (Value, Map<String, Value>) {
|
||||
let mut extensions = Map::new();
|
||||
if let Some(object) = body.as_object_mut() {
|
||||
for key in EXTENSION_KEYS {
|
||||
if let Some(value) = object.remove(key) {
|
||||
extensions.insert(key.to_owned(), value);
|
||||
}
|
||||
}
|
||||
}
|
||||
(body, extensions)
|
||||
}
|
||||
|
||||
/// `strata_tune`: engine settings for this request only (setup's calibration).
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Tune {
|
||||
pub pcie_frac: Option<f64>,
|
||||
pub spec_min_p: Option<f64>,
|
||||
}
|
||||
|
||||
impl From<Tune> for EngineTune {
|
||||
fn from(tune: Tune) -> Self {
|
||||
Self {
|
||||
pcie_frac: tune.pcie_frac,
|
||||
spec_min_p: tune.spec_min_p,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn validate_tune(tune: &Tune) -> Result<(), (&'static str, &'static str)> {
|
||||
for (name, value) in [
|
||||
("pcie_frac", tune.pcie_frac),
|
||||
("spec_min_p", tune.spec_min_p),
|
||||
] {
|
||||
if value.is_some_and(|v| !v.is_finite() || !(0.0..=1.0).contains(&v)) {
|
||||
return Err((
|
||||
"strata_tune",
|
||||
if name == "pcie_frac" {
|
||||
"strata_tune.pcie_frac must be between 0 and 1"
|
||||
} else {
|
||||
"strata_tune.spec_min_p must be between 0 and 1"
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate request sampling against the Original's contract; the message is static so it can
|
||||
/// travel in the Responses `(param, message)` error pair.
|
||||
pub fn validate(sampling: &RequestSampling) -> Result<(), (&'static str, &'static str)> {
|
||||
sampling.validate().map_err(|error| match error.field {
|
||||
"temperature" => ("temperature", "temperature must be between 0 and 2"),
|
||||
"top_p" => ("top_p", "top_p must be between 0 and 1"),
|
||||
"min_p" => ("min_p", "min_p must be between 0 and 1"),
|
||||
"top_k" => (
|
||||
"top_k",
|
||||
"top_k must be an integer >= 0 (0 or above 64 use 64)",
|
||||
),
|
||||
"repetition_penalty" => (
|
||||
"repetition_penalty",
|
||||
"repetition_penalty must be greater than 0 (1 is off)",
|
||||
),
|
||||
"frequency_penalty" => (
|
||||
"frequency_penalty",
|
||||
"frequency_penalty must be between -2 and 2",
|
||||
),
|
||||
"presence_penalty" => (
|
||||
"presence_penalty",
|
||||
"presence_penalty must be between -2 and 2",
|
||||
),
|
||||
"penalty_last_n" => (
|
||||
"penalty_last_n",
|
||||
"penalty_last_n must be an integer between 0 and 2147483647",
|
||||
),
|
||||
_ => ("sampling", "sampling parameters are out of range"),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn extensions_are_split_out_of_adapter_bodies() {
|
||||
let (rest, extensions) = split_extensions(json!({
|
||||
"model": "m", "temperature": 0.5, "top_k": 40, "seed": 3, "min_p": null,
|
||||
"strata_tune": {"pcie_frac": 0.1}
|
||||
}));
|
||||
assert_eq!(rest, json!({"model": "m", "temperature": 0.5}));
|
||||
assert_eq!(extensions.len(), 4);
|
||||
assert_eq!(extensions["top_k"], 40);
|
||||
assert!(extensions["min_p"].is_null());
|
||||
let (same, none) = split_extensions(json!([1, 2]));
|
||||
assert_eq!(same, json!([1, 2]));
|
||||
assert!(none.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_sampling_field_has_its_own_error() {
|
||||
for (bad, field) in [
|
||||
(
|
||||
RequestSampling {
|
||||
temperature: Some(3.0),
|
||||
..Default::default()
|
||||
},
|
||||
"temperature",
|
||||
),
|
||||
(
|
||||
RequestSampling {
|
||||
top_p: Some(-0.1),
|
||||
..Default::default()
|
||||
},
|
||||
"top_p",
|
||||
),
|
||||
(
|
||||
RequestSampling {
|
||||
min_p: Some(1.5),
|
||||
..Default::default()
|
||||
},
|
||||
"min_p",
|
||||
),
|
||||
(
|
||||
RequestSampling {
|
||||
top_k: Some(-1),
|
||||
..Default::default()
|
||||
},
|
||||
"top_k",
|
||||
),
|
||||
(
|
||||
RequestSampling {
|
||||
repetition_penalty: Some(0.0),
|
||||
..Default::default()
|
||||
},
|
||||
"repetition_penalty",
|
||||
),
|
||||
(
|
||||
RequestSampling {
|
||||
frequency_penalty: Some(2.5),
|
||||
..Default::default()
|
||||
},
|
||||
"frequency_penalty",
|
||||
),
|
||||
(
|
||||
RequestSampling {
|
||||
presence_penalty: Some(-2.5),
|
||||
..Default::default()
|
||||
},
|
||||
"presence_penalty",
|
||||
),
|
||||
(
|
||||
RequestSampling {
|
||||
penalty_last_n: Some(-1),
|
||||
..Default::default()
|
||||
},
|
||||
"penalty_last_n",
|
||||
),
|
||||
] {
|
||||
assert_eq!(validate(&bad).unwrap_err().0, field);
|
||||
}
|
||||
assert!(validate(&RequestSampling::default()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tune_is_bounded_and_strict() {
|
||||
assert!(validate_tune(&Tune::default()).is_ok());
|
||||
assert!(
|
||||
validate_tune(&Tune {
|
||||
pcie_frac: Some(1.1),
|
||||
spec_min_p: None
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
validate_tune(&Tune {
|
||||
pcie_frac: None,
|
||||
spec_min_p: Some(-0.1)
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
assert!(serde_json::from_value::<Tune>(json!({"pcie_frac": 0.5, "x": 1})).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,542 @@
|
||||
//! The operational HTTP surface of the Original's Python server (`engine/strata/serve/server.py`)
|
||||
//! that is not an inference API: `GET /props`, `GET /slots`, `GET /v1/status`, `GET /api/health`,
|
||||
//! `GET|POST /settings`, `POST /load`, `POST /unload`, `POST /v1/load`, `POST /v1/unload`, CORS and
|
||||
//! the own-page guard. Behaviour is checked against the real Python handlers in
|
||||
//! `tests/http_surface.rs` (fixtures from `tests/golden/gen_goldens.py http`).
|
||||
//!
|
||||
//! One engine at a time: `total_slots` is 1 and `/slots` lists one slot while the engine is loaded.
|
||||
|
||||
use std::{
|
||||
sync::Arc,
|
||||
time::{Duration, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
use axum::{
|
||||
Json,
|
||||
body::Bytes,
|
||||
extract::{Request, State},
|
||||
http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header},
|
||||
middleware::Next,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use leleka_serving_policy::{
|
||||
cors::{Cors, own_page},
|
||||
idle::Outcome,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
|
||||
use crate::{
|
||||
app::AppState,
|
||||
worker::{Control, LoadError, WorkerState, WorkerStatus},
|
||||
};
|
||||
|
||||
/// The chat template the Original serves in `/props` when the model ships none.
|
||||
pub const DEFAULT_CHAT_TEMPLATE: &str =
|
||||
include_str!("../../engine/strata/serve/chat_template.jinja");
|
||||
|
||||
fn error_body(kind: Option<&str>, message: &str) -> Value {
|
||||
match kind {
|
||||
Some(kind) => json!({"error": {"type": kind, "message": message}}),
|
||||
None => json!({"error": {"message": message}}),
|
||||
}
|
||||
}
|
||||
|
||||
fn reply(status: StatusCode, body: Value) -> Response {
|
||||
(status, Json(body)).into_response()
|
||||
}
|
||||
|
||||
fn now_s() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs())
|
||||
}
|
||||
|
||||
fn header_str<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
|
||||
headers.get(name).and_then(|v| v.to_str().ok())
|
||||
}
|
||||
|
||||
fn is_loaded(worker: &WorkerStatus) -> bool {
|
||||
worker.state == WorkerState::Ready
|
||||
}
|
||||
|
||||
/// Whether a request is running or waiting for the engine.
|
||||
fn is_busy(state: &AppState, worker: &WorkerStatus) -> bool {
|
||||
worker.metrics.active_since.is_some() || state.lifecycle.snapshot().generation_jobs > 0
|
||||
}
|
||||
|
||||
fn context_of(worker: &WorkerStatus) -> usize {
|
||||
worker.max_context.or(worker.known_max_context).unwrap_or(0)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ loading
|
||||
|
||||
/// Start the engine if it is unloaded (the Original's `Service.load`, called at the start of every
|
||||
/// request). Stamps the activity time so the idle timer does not unload between this and the
|
||||
/// request's own start. `Err` is a ready-made error response.
|
||||
pub async fn ensure_loaded(state: &AppState) -> Result<(), Box<Response>> {
|
||||
let unloaded = {
|
||||
let mut worker = state.worker.write().await;
|
||||
worker.last_activity = Some(tokio::time::Instant::now());
|
||||
worker.state == WorkerState::Unloaded
|
||||
};
|
||||
if !unloaded {
|
||||
return Ok(());
|
||||
}
|
||||
match load(state).await {
|
||||
Ok(()) => Ok(()),
|
||||
Err(error) => Err(Box::new(load_error_response(&error))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask the supervisor to load and wait until it is ready.
|
||||
pub async fn load(state: &AppState) -> Result<(), LoadError> {
|
||||
let Some(control) = &state.control else {
|
||||
return Err(LoadError::Failed(
|
||||
"the engine cannot be loaded on demand".into(),
|
||||
));
|
||||
};
|
||||
let (answer, received) = oneshot::channel();
|
||||
control
|
||||
.send(Control::Load { reply: answer })
|
||||
.await
|
||||
.map_err(|_| LoadError::Failed("the server is shutting down".into()))?;
|
||||
received
|
||||
.await
|
||||
.map_err(|_| LoadError::Failed("the server is shutting down".into()))?
|
||||
}
|
||||
|
||||
/// `POST /unload`'s core (also the idle thread): the outcome string of the Original.
|
||||
pub async fn unload(state: &AppState, idle_for: Option<Duration>) -> Outcome {
|
||||
let Some(control) = &state.control else {
|
||||
return Outcome::Unsupported;
|
||||
};
|
||||
{
|
||||
let worker = state.worker.read().await;
|
||||
if is_loaded(&worker) && is_busy(state, &worker) {
|
||||
return Outcome::Busy;
|
||||
}
|
||||
}
|
||||
let (answer, received) = oneshot::channel();
|
||||
if control
|
||||
.send(Control::Unload {
|
||||
idle_for,
|
||||
reply: answer,
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return Outcome::NotLoaded;
|
||||
}
|
||||
received.await.unwrap_or(Outcome::NotLoaded)
|
||||
}
|
||||
|
||||
fn load_error_response(error: &LoadError) -> Response {
|
||||
let message = match error {
|
||||
LoadError::GpuBusy(m) | LoadError::Failed(m) => m,
|
||||
};
|
||||
api_server_error(message)
|
||||
}
|
||||
|
||||
fn api_server_error(message: &str) -> Response {
|
||||
reply(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
error_body(Some("server_error"), message),
|
||||
)
|
||||
}
|
||||
|
||||
/// The idle thread of `--idle-unload`: every `poll` seconds, give the engine back if no request ran
|
||||
/// within `idle`. Returns when the control channel closes.
|
||||
pub async fn idle_unload_loop(state: AppState, idle: Duration, poll: Duration) {
|
||||
loop {
|
||||
tokio::time::sleep(poll).await;
|
||||
if state.control.as_ref().is_none_or(mpsc::Sender::is_closed) {
|
||||
return;
|
||||
}
|
||||
let outcome = unload(&state, Some(idle)).await;
|
||||
if outcome == Outcome::Unloaded {
|
||||
eprintln!(
|
||||
"model unloaded after {:.0} s idle; the next request loads it again",
|
||||
idle.as_secs_f64()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ handlers
|
||||
|
||||
/// `GET /api/health` (the Python server's `/health`): who answers and whether the engine is loaded.
|
||||
pub async fn api_health(State(state): State<AppState>) -> Response {
|
||||
let worker = *state.worker.read().await;
|
||||
reply(
|
||||
StatusCode::OK,
|
||||
json!({"status": "ok", "max_context": context_of(&worker), "model": state.model,
|
||||
"images": false, "api_key": state.api_key.is_some(),
|
||||
"loaded": is_loaded(&worker), "service": "strata"}),
|
||||
)
|
||||
}
|
||||
|
||||
fn model_names(state: &AppState) -> Vec<String> {
|
||||
state
|
||||
.model
|
||||
.iter()
|
||||
.cloned()
|
||||
.chain(state.aliases.iter().cloned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The first non-blank value of `name` (Python's `parse_qs` drops blank values).
|
||||
fn query_param(query: Option<&str>, name: &str) -> Option<String> {
|
||||
query?.split('&').find_map(|pair| {
|
||||
let (key, value) = pair.split_once('=')?;
|
||||
(percent_decode(key) == name && !value.is_empty()).then(|| percent_decode(value))
|
||||
})
|
||||
}
|
||||
|
||||
fn percent_decode(text: &str) -> String {
|
||||
let bytes = text.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'+' => out.push(b' '),
|
||||
b'%' if i + 2 < bytes.len() => {
|
||||
match std::str::from_utf8(&bytes[i + 1..i + 3])
|
||||
.ok()
|
||||
.and_then(|hex| u8::from_str_radix(hex, 16).ok())
|
||||
{
|
||||
Some(byte) => {
|
||||
out.push(byte);
|
||||
i += 2;
|
||||
}
|
||||
None => out.push(b'%'),
|
||||
}
|
||||
}
|
||||
byte => out.push(byte),
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
/// `GET /props` (llama-server compatible): the default generation settings, the chat template and
|
||||
/// what this server can do.
|
||||
pub async fn props(State(state): State<AppState>, request: Request) -> Response {
|
||||
let asked = query_param(request.uri().query(), "model")
|
||||
.or_else(|| state.model.clone())
|
||||
.unwrap_or_default();
|
||||
if !model_names(&state).contains(&asked) {
|
||||
return reply(StatusCode::NOT_FOUND, error_body(None, "model not found"));
|
||||
}
|
||||
let worker = *state.worker.read().await;
|
||||
if !is_loaded(&worker) && worker.state != WorkerState::Unloaded {
|
||||
return reply(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
error_body(None, "the engine is not running"),
|
||||
);
|
||||
}
|
||||
let merged = state.settings.merged();
|
||||
let shared = state.settings.shared();
|
||||
reply(
|
||||
StatusCode::OK,
|
||||
json!({
|
||||
"default_generation_settings": {
|
||||
"n_ctx": context_of(&worker),
|
||||
"params": merged.props_params(&shared),
|
||||
},
|
||||
"total_slots": 1,
|
||||
"model_alias": state.model,
|
||||
"chat_template": state.chat_template.as_deref().unwrap_or(DEFAULT_CHAT_TEMPLATE),
|
||||
"modalities": {"vision": false},
|
||||
"models_autoload": state.control.is_some(),
|
||||
"is_sleeping": !is_loaded(&worker),
|
||||
"build_info": format!("Strata Next {}", env!("CARGO_PKG_VERSION")),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// `GET /slots`: one slot while the engine is loaded, none otherwise.
|
||||
pub async fn slots(State(state): State<AppState>) -> Response {
|
||||
let worker = *state.worker.read().await;
|
||||
if !is_loaded(&worker) {
|
||||
return reply(StatusCode::OK, json!([]));
|
||||
}
|
||||
reply(
|
||||
StatusCode::OK,
|
||||
json!([{"id": 0, "n_ctx": context_of(&worker),
|
||||
"is_processing": is_busy(&state, &worker)}]),
|
||||
)
|
||||
}
|
||||
|
||||
/// `GET /v1/status`: what this server is and does, for a client that would rather ask than guess.
|
||||
pub async fn v1_status(State(state): State<AppState>) -> Response {
|
||||
reply(StatusCode::OK, status_value(&state).await)
|
||||
}
|
||||
|
||||
async fn status_value(state: &AppState) -> Value {
|
||||
let worker = *state.worker.read().await;
|
||||
let lifecycle = state.lifecycle.snapshot();
|
||||
let busy = worker.metrics.active_since.is_some();
|
||||
let queued = lifecycle.generation_jobs.saturating_sub(usize::from(busy));
|
||||
let context = context_of(&worker);
|
||||
let last_at = worker
|
||||
.last_activity
|
||||
.map(|at| now_s().saturating_sub(at.elapsed().as_secs()));
|
||||
let started = state
|
||||
.started_at
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs());
|
||||
let timings = worker.metrics.last_done.map(|done| {
|
||||
let mut value = leleka_serving_policy::timings::request_timings(
|
||||
&leleka_serving_policy::timings::Last {
|
||||
prompt_tokens: done.prompt_tokens,
|
||||
generated: done.generated_tokens,
|
||||
prompt_ms: done.prefill_ms,
|
||||
decode_ms: done.decode_ms,
|
||||
reused: done.reused_tokens,
|
||||
drafts_offered: done.drafts_offered,
|
||||
drafts_accepted: done.drafts_accepted,
|
||||
},
|
||||
done.generated_tokens,
|
||||
);
|
||||
value["at"] = json!(now_s());
|
||||
value
|
||||
});
|
||||
json!({
|
||||
"service": "strata", "model": state.model,
|
||||
"loaded": is_loaded(&worker), "auto_load": state.control.is_some(),
|
||||
"structured_output": {"formats": ["json_object", "json_schema"], "method": "prompt_and_validate",
|
||||
"constrained_decoding": false, "stream_buffered": true},
|
||||
"engine": env!("CARGO_PKG_VERSION"),
|
||||
"started": started,
|
||||
"uptime_s": state.started_at.elapsed().map_or(0, |d| d.as_secs()),
|
||||
"cache_max_tokens": context,
|
||||
"context": {"native": context, "max_positions": context},
|
||||
"concurrency": {"serving": 1, "requested": 1},
|
||||
"dialects": ["/v1/chat/completions", "/v1/messages", "/v1/responses"],
|
||||
"vision": {"enabled": false, "available": false, "error": null},
|
||||
"activity": {"requests": worker.metrics.started, "in_flight": usize::from(busy) + queued,
|
||||
"last_request_at": last_at},
|
||||
"last_timings": timings,
|
||||
"machine": {"at": now_s(), "gpu": null, "ram": null},
|
||||
})
|
||||
}
|
||||
|
||||
/// `GET /settings`.
|
||||
pub async fn settings_get(State(state): State<AppState>) -> Response {
|
||||
let shared = state.settings.shared();
|
||||
reply(
|
||||
StatusCode::OK,
|
||||
json!({"shared": !shared.is_empty(), "defaults": shared.to_json()}),
|
||||
)
|
||||
}
|
||||
|
||||
fn own_page_check(state: &AppState, headers: &HeaderMap, what: &str) -> Result<(), Box<Response>> {
|
||||
own_page(
|
||||
what,
|
||||
header_str(headers, "content-type"),
|
||||
header_str(headers, "origin"),
|
||||
header_str(headers, "host"),
|
||||
&state.trusted_origins,
|
||||
)
|
||||
.map_err(|e| {
|
||||
Box::new(reply(
|
||||
StatusCode::from_u16(e.status()).unwrap_or(StatusCode::FORBIDDEN),
|
||||
error_body(None, &e.message()),
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// `POST /settings`: replace the Chat settings every client gets for what it leaves out. They change
|
||||
/// what every client gets, so only the app's own page may set them.
|
||||
pub async fn settings_post(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
if let Err(response) = own_page_check(&state, &headers, "settings can be changed") {
|
||||
return *response;
|
||||
}
|
||||
let value: Value = if body.is_empty() {
|
||||
json!({})
|
||||
} else {
|
||||
match serde_json::from_slice(&body) {
|
||||
Ok(value) => value,
|
||||
Err(error) => {
|
||||
return reply(
|
||||
StatusCode::BAD_REQUEST,
|
||||
error_body(Some("invalid_request_error"), &error.to_string()),
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
let defaults = value.get("defaults").cloned().unwrap_or(Value::Null);
|
||||
match state.settings.set_shared(&defaults) {
|
||||
Ok(shared) => {
|
||||
if shared.is_empty() {
|
||||
eprintln!("other apps use their own settings again");
|
||||
} else {
|
||||
eprintln!("other apps now use the Chat settings: {}", shared.to_json());
|
||||
}
|
||||
reply(
|
||||
StatusCode::OK,
|
||||
json!({"shared": !shared.is_empty(), "defaults": shared.to_json()}),
|
||||
)
|
||||
}
|
||||
Err(message) => reply(
|
||||
StatusCode::BAD_REQUEST,
|
||||
error_body(Some("invalid_request_error"), &message),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// `POST /unload`: give the GPU back now (between requests).
|
||||
pub async fn unload_post(State(state): State<AppState>) -> Response {
|
||||
let outcome = unload(&state, None).await;
|
||||
reply(
|
||||
if outcome == Outcome::Busy {
|
||||
StatusCode::CONFLICT
|
||||
} else {
|
||||
StatusCode::OK
|
||||
},
|
||||
json!({"status": outcome.as_str()}),
|
||||
)
|
||||
}
|
||||
|
||||
/// `POST /load`: load now, e.g. ahead of a request.
|
||||
pub async fn load_post(State(state): State<AppState>) -> Response {
|
||||
state.worker.write().await.last_activity = Some(tokio::time::Instant::now());
|
||||
if state.worker.read().await.state == WorkerState::Ready {
|
||||
return reply(StatusCode::OK, json!({"status": "loaded"}));
|
||||
}
|
||||
match load(&state).await {
|
||||
Ok(()) => reply(StatusCode::OK, json!({"status": "loaded"})),
|
||||
Err(error) => load_error_response(&error),
|
||||
}
|
||||
}
|
||||
|
||||
/// The shared prelude of `POST /v1/load` and `/v1/unload`: a JSON object body, own page only, and
|
||||
/// the right model.
|
||||
fn model_control_prelude(
|
||||
state: &AppState,
|
||||
headers: &HeaderMap,
|
||||
body: &Bytes,
|
||||
) -> Result<(), Box<Response>> {
|
||||
let value: Value = if body.is_empty() {
|
||||
json!({})
|
||||
} else {
|
||||
serde_json::from_slice(body).map_err(|error| {
|
||||
Box::new(reply(
|
||||
StatusCode::BAD_REQUEST,
|
||||
error_body(Some("invalid_request_error"), &error.to_string()),
|
||||
))
|
||||
})?
|
||||
};
|
||||
let Some(object) = value.as_object() else {
|
||||
return Err(Box::new(reply(
|
||||
StatusCode::BAD_REQUEST,
|
||||
error_body(Some("invalid_request_error"), "send a JSON object"),
|
||||
)));
|
||||
};
|
||||
own_page_check(state, headers, "the model can be loaded or unloaded")?;
|
||||
match object.get("model") {
|
||||
None | Some(Value::Null) => {}
|
||||
Some(Value::String(name)) if state.model.as_deref() == Some(name.as_str()) => {}
|
||||
Some(_) => {
|
||||
return Err(Box::new(reply(
|
||||
StatusCode::NOT_FOUND,
|
||||
error_body(None, "model not found"),
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn model_busy() -> Response {
|
||||
reply(
|
||||
StatusCode::CONFLICT,
|
||||
error_body(Some("model_busy"), "a request is running or queued"),
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn v1_unload(State(state): State<AppState>, headers: HeaderMap, body: Bytes) -> Response {
|
||||
if let Err(response) = model_control_prelude(&state, &headers, &body) {
|
||||
return *response;
|
||||
}
|
||||
let outcome = unload(&state, None).await;
|
||||
if outcome == Outcome::Busy {
|
||||
return model_busy();
|
||||
}
|
||||
let mut value = status_value(&state).await;
|
||||
value["status"] = json!(outcome.as_str());
|
||||
reply(StatusCode::OK, value)
|
||||
}
|
||||
|
||||
pub async fn v1_load(State(state): State<AppState>, headers: HeaderMap, body: Bytes) -> Response {
|
||||
if let Err(response) = model_control_prelude(&state, &headers, &body) {
|
||||
return *response;
|
||||
}
|
||||
{
|
||||
let worker = state.worker.read().await;
|
||||
if is_busy(&state, &worker) {
|
||||
return model_busy();
|
||||
}
|
||||
}
|
||||
state.worker.write().await.last_activity = Some(tokio::time::Instant::now());
|
||||
if state.worker.read().await.state != WorkerState::Ready
|
||||
&& let Err(error) = load(&state).await
|
||||
{
|
||||
return load_error_response(&error);
|
||||
}
|
||||
let mut value = status_value(&state).await;
|
||||
value["status"] = json!("loaded");
|
||||
reply(StatusCode::OK, value)
|
||||
}
|
||||
|
||||
/// Unknown paths: a JSON error, like the Original's `{"error": {"message": "not found"}}`.
|
||||
pub async fn not_found() -> Response {
|
||||
reply(StatusCode::NOT_FOUND, error_body(None, "not found"))
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ CORS
|
||||
|
||||
/// CORS for `/v1/*` (config `cors_origins`) and the preflight: the outermost layer, so a browser's
|
||||
/// credential-less `OPTIONS` is answered before authentication, as the Original does.
|
||||
pub async fn cors_layer(State(cors): State<Arc<Cors>>, request: Request, next: Next) -> Response {
|
||||
let target = request.uri().path_and_query().map_or_else(
|
||||
|| request.uri().path().to_owned(),
|
||||
|p| p.as_str().to_owned(),
|
||||
);
|
||||
let headers = cors.headers(
|
||||
&target,
|
||||
header_str(request.headers(), "origin"),
|
||||
header_str(request.headers(), "access-control-request-headers"),
|
||||
);
|
||||
let mut response = if request.method() == Method::OPTIONS {
|
||||
let mut response = StatusCode::NO_CONTENT.into_response();
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(header::CONTENT_LENGTH, HeaderValue::from_static("0"));
|
||||
response
|
||||
} else {
|
||||
next.run(request).await
|
||||
};
|
||||
for (name, value) in headers {
|
||||
if let (Ok(name), Ok(value)) = (
|
||||
HeaderName::from_bytes(name.as_bytes()),
|
||||
HeaderValue::from_str(&value),
|
||||
) {
|
||||
response.headers_mut().insert(name, value);
|
||||
}
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
/// `GET /mcp`: the configured MCP servers, their state and tools (empty when there are none).
|
||||
pub async fn mcp_status(State(state): State<AppState>) -> Response {
|
||||
let body = match &state.mcp {
|
||||
Some(hub) => hub.status().await,
|
||||
None => json!({"servers": [], "tools": 0}),
|
||||
};
|
||||
reply(StatusCode::OK, body)
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
//! Server-wide sampling defaults: the run config's `sampling` block and the Chat settings every
|
||||
//! client shares (`POST /settings`), kept next to the config between starts. Port of the
|
||||
//! settings half of `serve/server.py` `Service` (`set_shared`, `with_shared`, the default merge in
|
||||
//! `run`). The pure rules live in `leleka-serving-policy`.
|
||||
|
||||
use std::{
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
sync::RwLock,
|
||||
};
|
||||
|
||||
use leleka_serving_policy::shared::{
|
||||
ConfigSampling, MergedDefaults, SharedDefaults, clean_shared_defaults, merged_defaults,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Settings {
|
||||
config: ConfigSampling,
|
||||
shared: RwLock<SharedDefaults>,
|
||||
shared_path: Option<PathBuf>,
|
||||
/// The config's `reasoning_budget_tokens` (raw, validated at startup).
|
||||
reasoning_budget_default: Option<Value>,
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
pub fn new(config: ConfigSampling) -> Self {
|
||||
Self {
|
||||
config,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_reasoning_budget(mut self, default: Option<Value>) -> Self {
|
||||
self.reasoning_budget_default = default;
|
||||
self
|
||||
}
|
||||
|
||||
/// Persist shared settings in `path` and load what a previous run left there. A missing,
|
||||
/// unreadable or invalid file means "clients use their own settings" (as in the Original).
|
||||
pub fn with_shared_file(mut self, path: PathBuf) -> Self {
|
||||
let loaded = fs::read_to_string(&path)
|
||||
.ok()
|
||||
.and_then(|text| serde_json::from_str::<Value>(&text).ok())
|
||||
.and_then(|value| clean_shared_defaults(&value).ok())
|
||||
.unwrap_or_default();
|
||||
*self.shared.write().expect("settings lock") = loaded;
|
||||
self.shared_path = Some(path);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn shared(&self) -> SharedDefaults {
|
||||
self.shared.read().expect("settings lock").clone()
|
||||
}
|
||||
|
||||
pub fn config(&self) -> &ConfigSampling {
|
||||
&self.config
|
||||
}
|
||||
|
||||
pub fn reasoning_budget_default(&self) -> Option<&Value> {
|
||||
self.reasoning_budget_default.as_ref()
|
||||
}
|
||||
|
||||
/// `{**config sampling, **shared}`.
|
||||
pub fn merged(&self) -> MergedDefaults {
|
||||
merged_defaults(&self.config, &self.shared())
|
||||
}
|
||||
|
||||
/// `POST /settings`: validate, replace and persist. `Err` is the 400 message.
|
||||
pub fn set_shared(&self, defaults: &Value) -> Result<SharedDefaults, String> {
|
||||
let cleaned = clean_shared_defaults(defaults)?;
|
||||
*self.shared.write().expect("settings lock") = cleaned.clone();
|
||||
if let Some(path) = &self.shared_path
|
||||
&& let Err(error) = persist(path, &cleaned)
|
||||
{
|
||||
eprintln!("could not save the shared settings: {error}");
|
||||
}
|
||||
Ok(cleaned)
|
||||
}
|
||||
}
|
||||
|
||||
fn persist(path: &Path, shared: &SharedDefaults) -> std::io::Result<()> {
|
||||
if shared.is_empty() {
|
||||
match fs::remove_file(path) {
|
||||
Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error),
|
||||
_ => Ok(()),
|
||||
}
|
||||
} else {
|
||||
// Written next to the destination and renamed, so a crash never leaves half a file.
|
||||
let temporary = path.with_extension("tmp");
|
||||
fs::write(&temporary, serde_json::to_string_pretty(&shared.to_json())?)?;
|
||||
fs::rename(&temporary, path)
|
||||
}
|
||||
}
|
||||
|
||||
/// The shared-settings file the Original keeps next to its config: `<config minus extension>.shared-settings.json`.
|
||||
pub fn default_shared_path(config: &Path) -> PathBuf {
|
||||
let mut name = config.with_extension("").into_os_string();
|
||||
name.push(".shared-settings.json");
|
||||
PathBuf::from(name)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn temp(name: &str) -> PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("strata-settings-{}-{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_settings_persist_across_starts_and_empty_removes_the_file() {
|
||||
let dir = temp("persist");
|
||||
let path = dir.join("strata.shared-settings.json");
|
||||
let first = Settings::default().with_shared_file(path.clone());
|
||||
assert!(first.shared().is_empty());
|
||||
first
|
||||
.set_shared(&json!({"temperature": 0.5, "max_tokens": 128}))
|
||||
.unwrap();
|
||||
assert!(path.exists());
|
||||
let second = Settings::default().with_shared_file(path.clone());
|
||||
assert_eq!(second.shared().temperature, Some(0.5));
|
||||
assert_eq!(second.shared().max_tokens, Some(128));
|
||||
second.set_shared(&json!({})).unwrap();
|
||||
assert!(!path.exists());
|
||||
assert!(
|
||||
Settings::default()
|
||||
.with_shared_file(path)
|
||||
.shared()
|
||||
.is_empty()
|
||||
);
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_corrupt_file_means_no_shared_settings() {
|
||||
let dir = temp("corrupt");
|
||||
let path = dir.join("s.json");
|
||||
fs::write(&path, "{not json").unwrap();
|
||||
assert!(
|
||||
Settings::default()
|
||||
.with_shared_file(path.clone())
|
||||
.shared()
|
||||
.is_empty()
|
||||
);
|
||||
fs::write(&path, r#"{"temperature": 9}"#).unwrap();
|
||||
assert!(
|
||||
Settings::default()
|
||||
.with_shared_file(path)
|
||||
.shared()
|
||||
.is_empty()
|
||||
);
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rejected_update_keeps_the_previous_settings() {
|
||||
let settings = Settings::default();
|
||||
settings.set_shared(&json!({"top_k": 10})).unwrap();
|
||||
assert_eq!(
|
||||
settings.set_shared(&json!({"top_k": 100})).unwrap_err(),
|
||||
"top_k: an integer 1..64"
|
||||
);
|
||||
assert_eq!(settings.shared().top_k, Some(10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_path_sits_next_to_the_config() {
|
||||
assert_eq!(
|
||||
default_shared_path(Path::new("/etc/strata/run.json")),
|
||||
PathBuf::from("/etc/strata/run.shared-settings.json")
|
||||
);
|
||||
}
|
||||
}
|
||||
+219
-22
@@ -1,36 +1,115 @@
|
||||
//! Typed boundary for the resident Strata `--serve` stdin/stdout protocol.
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
use leleka_sampler_ref::RequestSampling;
|
||||
|
||||
/// Per-request engine tuning (`strata_tune` in the Python server): the PCIe share of
|
||||
/// missed experts and the draft-probability floor, both in `0..=1`.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct EngineTune {
|
||||
pub pcie_frac: Option<f64>,
|
||||
pub spec_min_p: Option<f64>,
|
||||
}
|
||||
|
||||
/// Reasoning-budget wrap-up (`reasoning_budget_tokens`, issue #123 of the Original): once the model
|
||||
/// has thought for `budget` tokens, at a clean point the worker stops the pass, appends `wrap_up`
|
||||
/// to the output and continues from `prompt + generated + wrap_up` so the engine keeps its prefix.
|
||||
#[derive(Clone)]
|
||||
pub struct ReasoningPlan {
|
||||
pub budget: u64,
|
||||
/// Token ids of `REASONING_WRAP_UP`.
|
||||
pub wrap_up: Vec<u32>,
|
||||
/// End-of-turn ids: they end the generation and are never counted as thinking.
|
||||
pub stop_ids: Vec<u32>,
|
||||
/// The bytes one token decodes to.
|
||||
pub token_bytes: std::sync::Arc<dyn Fn(u32) -> Vec<u8> + Send + Sync>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ReasoningPlan {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ReasoningPlan")
|
||||
.field("budget", &self.budget)
|
||||
.field("wrap_up", &self.wrap_up)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for ReasoningPlan {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.budget == other.budget
|
||||
&& self.wrap_up == other.wrap_up
|
||||
&& self.stop_ids == other.stop_ids
|
||||
}
|
||||
}
|
||||
|
||||
/// One `GEN` / `GENI` request. Every sampling key the Original's `--serve` loop
|
||||
/// accepts is carried: `temperature`, `top_p`, `top_k`, `min_p`, the three penalties
|
||||
/// with `penalty_last_n`, and `seed` (through [`RequestSampling::gen_keys`], which is
|
||||
/// golden-tested against `StrataEngine.sampling_keys`), plus `strata_tune`
|
||||
/// (`pcie_frac`, `spec_min_p`) and the per-request control-vector switch `cvec`.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct Generate {
|
||||
pub token_ids: Vec<u32>,
|
||||
pub max_new: u32,
|
||||
pub temperature: Option<f64>,
|
||||
pub top_p: Option<f64>,
|
||||
pub sampling: RequestSampling,
|
||||
pub tune: Option<EngineTune>,
|
||||
/// `experimental_speed_projection`: `Some(b)` emits `cvec=0|1`, `None` leaves the
|
||||
/// engine default (on when a vector is loaded).
|
||||
pub cvec: Option<bool>,
|
||||
/// `GENI`: path of the SVE1 image-embeddings file for this request.
|
||||
pub embeddings: Option<String>,
|
||||
/// Reasoning-budget wrap-up, executed by the worker; never sent to the engine.
|
||||
pub reasoning: Option<ReasoningPlan>,
|
||||
}
|
||||
|
||||
impl Generate {
|
||||
/// The tuning and projection keys after the sampling keys, in the Python order.
|
||||
fn engine_keys(&self) -> Result<String, &'static str> {
|
||||
let mut keys = String::new();
|
||||
if let Some(tune) = &self.tune {
|
||||
for (name, value) in [
|
||||
("pcie_frac", tune.pcie_frac),
|
||||
("spec_min_p", tune.spec_min_p),
|
||||
] {
|
||||
if let Some(value) = value {
|
||||
if !value.is_finite() || !(0.0..=1.0).contains(&value) {
|
||||
return Err("strata_tune values must be finite and between 0 and 1");
|
||||
}
|
||||
keys.push_str(&format!(
|
||||
" {name}={}",
|
||||
leleka_sampler_ref::params::py_float_repr(value)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(on) = self.cvec {
|
||||
keys.push_str(&format!(" cvec={}", u8::from(on)));
|
||||
}
|
||||
Ok(keys)
|
||||
}
|
||||
|
||||
pub fn line(&self) -> Result<String, &'static str> {
|
||||
if self.token_ids.is_empty() || self.max_new == 0 {
|
||||
return Err("GEN needs prompt tokens and a positive max_new");
|
||||
}
|
||||
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 +253,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 +274,120 @@ 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),
|
||||
reasoning: None,
|
||||
};
|
||||
assert_eq!(
|
||||
request.line().unwrap(),
|
||||
case["line"].as_str().unwrap(),
|
||||
"case {case}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn out_of_contract_generate_fields_are_refused_before_the_pipe() {
|
||||
let base = Generate {
|
||||
token_ids: vec![1],
|
||||
max_new: 1,
|
||||
..Default::default()
|
||||
};
|
||||
for bad in [
|
||||
RequestSampling {
|
||||
temperature: Some(2.5),
|
||||
..Default::default()
|
||||
},
|
||||
RequestSampling {
|
||||
top_p: Some(1.5),
|
||||
..Default::default()
|
||||
},
|
||||
RequestSampling {
|
||||
top_k: Some(-1),
|
||||
..Default::default()
|
||||
},
|
||||
RequestSampling {
|
||||
repetition_penalty: Some(0.0),
|
||||
..Default::default()
|
||||
},
|
||||
RequestSampling {
|
||||
presence_penalty: Some(f64::NAN),
|
||||
..Default::default()
|
||||
},
|
||||
] {
|
||||
let request = Generate {
|
||||
sampling: bad,
|
||||
..base.clone()
|
||||
};
|
||||
assert!(request.line().is_err(), "{request:?}");
|
||||
}
|
||||
for tune in [
|
||||
EngineTune {
|
||||
pcie_frac: Some(1.5),
|
||||
spec_min_p: None,
|
||||
},
|
||||
EngineTune {
|
||||
pcie_frac: None,
|
||||
spec_min_p: Some(f64::NAN),
|
||||
},
|
||||
] {
|
||||
let request = Generate {
|
||||
tune: Some(tune),
|
||||
..base.clone()
|
||||
};
|
||||
assert!(request.line().is_err());
|
||||
}
|
||||
for path in ["", "a b", "a=b", "a\nb"] {
|
||||
let request = Generate {
|
||||
embeddings: Some(path.into()),
|
||||
..base.clone()
|
||||
};
|
||||
assert!(request.line().is_err(), "{path:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_current_and_older_done_lines() {
|
||||
let current = parse_line("DONE 12 300 45.1 88.2 stop 7 10 240 90 100 2 0 0.0\n")
|
||||
|
||||
+871
-58
File diff suppressed because it is too large
Load Diff
+1085
File diff suppressed because it is too large
Load Diff
+4347
File diff suppressed because one or more lines are too long
+40
@@ -113,6 +113,46 @@ case "$2" in
|
||||
esac
|
||||
done
|
||||
;;
|
||||
lifecycle)
|
||||
printf 'boot\n' >> "$3/boots"
|
||||
printf 'INFO engine=mock\nREADY %s stop\n' "${4:-4096}"
|
||||
while IFS= read -r line; do
|
||||
case "$line" in
|
||||
'GEN 2 1,2') printf 'T 31\nT 32\nDONE 2 2 1.0 2.0 stop 0 0 0 0 0\n' ;;
|
||||
QUIT) printf 'quit\n' >> "$3/quits"; exit 0 ;;
|
||||
*) printf 'ERR unexpected request\n' ;;
|
||||
esac
|
||||
done
|
||||
;;
|
||||
budget)
|
||||
printf 'READY 4096 stop\n'
|
||||
while IFS= read -r line; do
|
||||
case "$line" in
|
||||
'GEN 40 temperature=0.7 10,20')
|
||||
printf '%s\n' "$line" >> "$3/requests"
|
||||
printf 'PP 2 2 1 2.0\nT 31\nT 32\nT 33\nT 34\nT 35\n'
|
||||
IFS= read -r stop || exit 3
|
||||
[ "$stop" = STOP ] || exit 4
|
||||
printf 'DONE 5 2 1.0 2.0 cancel 0 0 0 4 8\n' ;;
|
||||
'GEN 35 temperature=0.7 10,20,31,32,33,90,91')
|
||||
printf '%s\n' "$line" >> "$3/requests"
|
||||
printf 'PP 7 7 1 2.0\nT 40\nT 41\nDONE 2 7 3.0 4.0 stop 0 0 5 1 2\n' ;;
|
||||
'GEN 5 temperature=0.7 10,20')
|
||||
printf '%s\n' "$line" >> "$3/requests"
|
||||
printf 'T 31\nT 32\nT 33\nT 34\n'
|
||||
IFS= read -r stop || exit 3
|
||||
[ "$stop" = STOP ] || exit 4
|
||||
printf 'DONE 4 2 1.0 2.0 cancel\n' ;;
|
||||
QUIT) exit 0 ;;
|
||||
*) printf 'ERR unexpected request\n' ;;
|
||||
esac
|
||||
done
|
||||
;;
|
||||
stall)
|
||||
printf 'READY 4096 stop\n'
|
||||
IFS= read -r line || exit 3
|
||||
sleep 30
|
||||
;;
|
||||
restart-loop)
|
||||
printf 'boot\n' >> "$3/boots"
|
||||
printf 'READY 262144 stop\n'
|
||||
|
||||
@@ -0,0 +1,553 @@
|
||||
"""Offline golden generator for the control-plane serving surface (Python is allowed for fixtures only).
|
||||
|
||||
Runs the REAL Python handlers of the pinned Strata (`engine/strata/serve/*.py`, mock engine, no GPU) over tables
|
||||
of inputs and records what they answer. The Rust tests in `control-plane/tests/golden_*.rs` and the unit tests of
|
||||
`crates/serving-policy` compare against these files.
|
||||
|
||||
python3 -I control-plane/tests/golden/gen_goldens.py [section ...]
|
||||
|
||||
Needs the packages in engine/strata/requirements.txt (jinja2, jsonschema, regex). The scratchpad venv has them.
|
||||
Sections: gen_lines, shared, props_slots, cors, ...
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import queue
|
||||
import sys
|
||||
import threading
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
REPO = os.path.normpath(os.path.join(HERE, "..", "..", ".."))
|
||||
ENGINE = os.path.join(REPO, "engine", "strata")
|
||||
sys.path.insert(0, ENGINE)
|
||||
sys.path.insert(0, os.path.join(ENGINE, "tools"))
|
||||
|
||||
OUT_CONTROL = os.path.join(HERE, "..", "fixtures", "golden")
|
||||
OUT_POLICY = os.path.join(REPO, "crates", "serving-policy", "tests", "fixtures")
|
||||
|
||||
|
||||
def write(name, obj, dest="control"):
|
||||
out = OUT_POLICY if dest == "policy" else OUT_CONTROL
|
||||
os.makedirs(out, exist_ok=True)
|
||||
path = os.path.join(out, name + ".json")
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
json.dump(obj, f, indent=1, ensure_ascii=False, sort_keys=False)
|
||||
f.write("\n")
|
||||
print("wrote", os.path.relpath(path, REPO), file=sys.stderr)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ gen_lines
|
||||
def gen_lines():
|
||||
from serve.server import StrataEngine
|
||||
|
||||
class Pipe:
|
||||
def __init__(self):
|
||||
self.sent = []
|
||||
|
||||
def write(self, text):
|
||||
self.sent.append(text)
|
||||
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
def capture(ids, max_new, sampling, embeddings=None):
|
||||
eng = object.__new__(StrataEngine)
|
||||
eng.proc = type("P", (), {"stdin": Pipe()})()
|
||||
eng.lines = queue.Queue()
|
||||
eng.lines.put("DONE 1 1 1.0 1.0 stop\n")
|
||||
eng.can_stop = False
|
||||
eng.progress = None
|
||||
eng.prefill_tok_s_mean = None
|
||||
eng.last = {}
|
||||
list(eng.generate(ids, max_new, sampling, threading.Event(), embeddings=embeddings))
|
||||
return "".join(eng.proc.stdin.sent)
|
||||
|
||||
cases = []
|
||||
sampling_tables = [
|
||||
{},
|
||||
{"temperature": 0.0},
|
||||
{"temperature": 0.7},
|
||||
{"temperature": 0.7, "top_p": 0.9},
|
||||
{"temperature": 1, "top_p": 1.0},
|
||||
{"temperature": 0.8, "top_k": 40, "min_p": 0.05},
|
||||
{"temperature": 0.8, "top_k": 0},
|
||||
{"temperature": 0.8, "top_k": 1000},
|
||||
{"temperature": 0.6, "top_p": 0.95, "top_k": 20, "min_p": 0.0},
|
||||
{"repetition_penalty": 1.1},
|
||||
{"repetition_penalty": 1.1, "penalty_last_n": 256},
|
||||
{"presence_penalty": 0.5, "frequency_penalty": 0.25},
|
||||
{"presence_penalty": -0.5},
|
||||
{"frequency_penalty": 1.5, "penalty_last_n": 0},
|
||||
{"temperature": 0.7, "seed": 42},
|
||||
{"temperature": 0.7, "seed": 0},
|
||||
{"temperature": 0.7, "seed": 18446744073709551615},
|
||||
{"temperature": 0.9, "top_p": 0.8, "top_k": 33, "min_p": 0.02, "repetition_penalty": 1.05,
|
||||
"presence_penalty": 0.1, "frequency_penalty": 0.2, "penalty_last_n": 128, "seed": 7},
|
||||
{"strata_tune": {"pcie_frac": 0.0}},
|
||||
{"strata_tune": {"pcie_frac": 0.35, "spec_min_p": 0.2}},
|
||||
{"strata_tune": {"spec_min_p": 1.0}},
|
||||
{"experimental_speed_projection": True},
|
||||
{"experimental_speed_projection": False},
|
||||
{"temperature": 0.5, "strata_tune": {"pcie_frac": 0.5}, "experimental_speed_projection": False},
|
||||
]
|
||||
for ids, max_new, emb in (([1, 2, 3], 16, None), ([248045, 872, 198, 9707], 4096, None),
|
||||
([5, 248056, 248056, 6], 32, "/tmp/req-abc123.sve")):
|
||||
for sampling in sampling_tables:
|
||||
cases.append({"token_ids": ids, "max_new": max_new, "embeddings": emb, "sampling": sampling,
|
||||
"line": capture(ids, max_new, sampling, emb)})
|
||||
write("gen_lines", {"source": "serve/server.py StrataEngine.generate (real code, fake pipe)", "cases": cases})
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ shared
|
||||
def shared():
|
||||
from serve.server import clean_shared_defaults, sampling_defaults_from_config
|
||||
|
||||
clean_cases = [
|
||||
None, {}, [], "x", 5,
|
||||
{"temperature": 0.7}, {"temperature": 1}, {"temperature": 0}, {"temperature": 2}, {"temperature": 2.5},
|
||||
{"temperature": -0.1}, {"temperature": True}, {"temperature": "0.5"},
|
||||
{"top_p": 0.9}, {"top_p": 1}, {"top_p": 0}, {"top_p": 1.5}, {"top_p": False},
|
||||
{"top_k": 40}, {"top_k": 40.0}, {"top_k": 40.5}, {"top_k": 0}, {"top_k": 64}, {"top_k": 65}, {"top_k": "40"},
|
||||
{"seed": 7}, {"seed": 7.0}, {"seed": 0}, {"seed": -3}, {"seed": 1.5}, {"seed": 18446744073709551615},
|
||||
{"max_tokens": 512}, {"max_tokens": 0}, {"max_tokens": "10"},
|
||||
{"reasoning_effort": "none"}, {"reasoning_effort": "low"}, {"reasoning_effort": "medium"},
|
||||
{"reasoning_effort": "high"}, {"reasoning_effort": "xhigh"}, {"reasoning_effort": 3},
|
||||
{"experimental_speed_projection": True}, {"experimental_speed_projection": False},
|
||||
{"experimental_speed_projection": 1},
|
||||
{"temperature": None, "top_p": "", "top_k": None}, {"unknown": 1}, {"unknown": None}, {"min_p": 0.1},
|
||||
{"temperature": 0.7, "top_p": 0.9, "top_k": 20, "seed": 11, "max_tokens": 100,
|
||||
"reasoning_effort": "medium", "experimental_speed_projection": False},
|
||||
]
|
||||
clean = []
|
||||
for case in clean_cases:
|
||||
try:
|
||||
clean.append({"input": case, "ok": clean_shared_defaults(case)})
|
||||
except ValueError as e:
|
||||
clean.append({"input": case, "error": str(e)})
|
||||
|
||||
config_cases = [
|
||||
None, {}, {"temperature": 0.7}, {"temperature": 0}, {"temperature": -1}, {"temperature": True},
|
||||
{"top_p": 0.95}, {"top_p": 0}, {"top_p": 1.01}, {"min_p": 0.05}, {"min_p": 0}, {"min_p": 2},
|
||||
{"top_k": 40}, {"top_k": 0}, {"top_k": 65}, {"top_k": 20.0}, {"top_k": 1.5},
|
||||
{"presence_penalty": 0.5}, {"presence_penalty": -0.5}, {"frequency_penalty": 0.25},
|
||||
{"frequency_penalty": -1}, {"repetition_penalty": 1.1}, {"repetition_penalty": 0},
|
||||
{"penalty_last_n": 128}, {"penalty_last_n": 0}, {"penalty_last_n": -2}, {"penalty_last_n": 1.5},
|
||||
{"seed": 5}, {"seed": 0}, {"seed": 5.5}, {"seed": "5"},
|
||||
{"experimental_speed_projection": True}, {"experimental_speed_projection": "yes"},
|
||||
{"temperature": None, "top_p": None}, {"nonsense": 3}, {"temperature": 0.6, "nonsense": 3},
|
||||
{"temperature": 0.6, "top_p": 0.9, "top_k": 30, "min_p": 0.02, "presence_penalty": 0.1,
|
||||
"frequency_penalty": 0.1, "repetition_penalty": 1.05, "penalty_last_n": 64, "seed": 9},
|
||||
]
|
||||
import contextlib
|
||||
import io
|
||||
config = []
|
||||
for case in config_cases:
|
||||
out = io.StringIO()
|
||||
try:
|
||||
with contextlib.redirect_stdout(out):
|
||||
ok = sampling_defaults_from_config({"sampling": case} if case is not None else {})
|
||||
config.append({"input": case, "ok": ok, "ignored": [ln for ln in out.getvalue().splitlines()
|
||||
if "unknown key" in ln]})
|
||||
except SystemExit as e:
|
||||
config.append({"input": case, "error": str(e)})
|
||||
write("shared", {"source": "serve/server.py clean_shared_defaults / sampling_defaults_from_config (real code)",
|
||||
"clean": clean, "config": config}, dest="policy")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ reasoning
|
||||
def reasoning():
|
||||
import random
|
||||
from serve.frontend import OutputParser
|
||||
from serve.server import Detokenizer, Service, ByteTokenizer
|
||||
|
||||
class BytesTok:
|
||||
"""Token i's bytes are the table's entry; what Detokenizer needs from the real tokenizer."""
|
||||
def __init__(self, table):
|
||||
self.table = table
|
||||
|
||||
def token_bytes(self, t):
|
||||
return self.table[t]
|
||||
|
||||
pieces = [b"a", b"b", b" so ", b"think", b"</", b"/think>", b"</think>", b"</thi", b"nk>", b"<", b"/", b"\n",
|
||||
b"\xc3", b"\xa9", "\u65e5".encode()[:1], "\u65e5".encode()[1:], b"\xff", b"\xe2\x82", b"\xac", b"<t",
|
||||
b"hink>", b"x"]
|
||||
rng = random.Random(1234)
|
||||
seqs = [[0, 1, 2, 3], [4, 5], [6, 0, 1], [0, 4, 0, 1], [11, 12, 0, 0, 0], [13, 14, 0, 0], [16, 0, 0], [17, 18, 0],
|
||||
[3, 4, 5, 3, 3], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
|
||||
for _ in range(120):
|
||||
seqs.append([rng.randrange(len(pieces)) for _ in range(rng.randrange(1, 14))])
|
||||
cases = []
|
||||
for seq in seqs:
|
||||
row = {"pieces_hex": [pieces[i].hex() for i in seq], "wrap_at": {}}
|
||||
for budget in (1, 2, 3, 5, 8):
|
||||
parser = OutputParser(thinking=True, tools=None, stream_tools=True)
|
||||
detok = Detokenizer(BytesTok(pieces))
|
||||
thought, wrap_at = 0, None
|
||||
for i, t in enumerate(seq):
|
||||
parser.feed(detok.push(t))
|
||||
if parser.state == "reasoning":
|
||||
thought += 1
|
||||
if thought >= budget and not parser.buf and not detok.pending():
|
||||
wrap_at = i
|
||||
break
|
||||
row["wrap_at"][str(budget)] = wrap_at
|
||||
cases.append(row)
|
||||
|
||||
parse = []
|
||||
svc = Service.__new__(Service)
|
||||
for req, default in [(None, 0), ({}, 0), ({"reasoning_budget_tokens": 20}, 0), ({"reasoning_budget_tokens": 20.0}, 0),
|
||||
({"reasoning_budget_tokens": 0}, 50), ({"reasoning_budget_tokens": -1}, 50),
|
||||
({}, 50), ({"reasoning_budget_tokens": None}, 50), ({"reasoning_budget_tokens": True}, 0),
|
||||
({"reasoning_budget_tokens": "5"}, 0), ({"reasoning_budget_tokens": 2.5}, 0),
|
||||
({"reasoning_budget_tokens": [1]}, 0), ({"reasoning_budget_tokens": 10000}, 0)]:
|
||||
svc.reasoning_budget_tokens = default
|
||||
try:
|
||||
parse.append({"request": req, "default": default, "ok": svc.reasoning_budget(req)})
|
||||
except ValueError as e:
|
||||
parse.append({"request": req, "default": default, "error": str(e)})
|
||||
from serve.server import REASONING_WRAP_UP
|
||||
write("reasoning", {"source": "serve/server.py Service.reasoning_budget + Service.run budget branch (real "
|
||||
"Detokenizer/OutputParser)", "wrap_up": REASONING_WRAP_UP, "cases": cases,
|
||||
"parse": parse}, dest="policy")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ http
|
||||
def http_surface():
|
||||
"""The operational HTTP surface of the real Python server, scenario by scenario (fake resident engine)."""
|
||||
import http.client
|
||||
from pathlib import Path
|
||||
from serve.frontend import ChatTemplate
|
||||
from serve.server import ByteTokenizer, MockEngine, Service, StrataEngine, serve
|
||||
|
||||
class Resident(StrataEngine):
|
||||
def __init__(self, tok, loaded, max_context):
|
||||
self.reply = MockEngine(tok, "Hello.", max_context=max_context)
|
||||
self.max_context, self.info, self.last = max_context, {"version": "9.9.9"}, {}
|
||||
self.loaded, self.unloaded, self.progress = loaded, not loaded, None
|
||||
|
||||
def alive(self):
|
||||
return self.loaded
|
||||
|
||||
def exit_code(self):
|
||||
return None
|
||||
|
||||
def restart(self):
|
||||
self.loaded, self.unloaded = True, False
|
||||
|
||||
def close(self):
|
||||
self.loaded = False
|
||||
|
||||
def unload(self):
|
||||
self.close()
|
||||
self.unloaded = True
|
||||
|
||||
def generate(self, *args, **kwargs):
|
||||
yield from self.reply.generate(*args, **kwargs)
|
||||
|
||||
def run(setup, steps):
|
||||
tok = ByteTokenizer()
|
||||
engine = Resident(tok, setup.get("loaded", True), setup.get("max_context", 4096))
|
||||
svc = Service(engine, tok, ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja"),
|
||||
model_name=setup.get("model", "strata-test"),
|
||||
sampling_defaults=setup.get("config_sampling") or {})
|
||||
svc.set_aliases(setup.get("aliases"))
|
||||
svc.api_key = setup.get("api_key", "")
|
||||
svc.cors_origins = setup.get("cors_origins", [])
|
||||
svc.trusted_origins = setup.get("trusted_origins", [])
|
||||
if setup.get("shared"):
|
||||
svc.shared = dict(setup["shared"])
|
||||
svc.idle_unload_s = setup.get("idle_unload_s", 0)
|
||||
for key, value in (setup.get("status") or {}).items():
|
||||
svc.status[key] = value
|
||||
httpd = serve(svc, port=0)
|
||||
port = httpd.server_address[1]
|
||||
out = []
|
||||
try:
|
||||
for step in steps:
|
||||
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=10)
|
||||
headers = dict(step.get("headers") or {})
|
||||
body = step.get("body")
|
||||
if body is not None and not isinstance(body, str):
|
||||
body = json.dumps(body)
|
||||
headers.setdefault("Content-Type", "application/json")
|
||||
if body is not None:
|
||||
headers.setdefault("Content-Length", str(len(body.encode())))
|
||||
conn.request(step["method"], step["path"], body=body.encode() if body is not None else None,
|
||||
headers=headers)
|
||||
response = conn.getresponse()
|
||||
raw = response.read().decode()
|
||||
selected = {k.lower(): v for k, v in response.getheaders()
|
||||
if k.lower().startswith("access-control-") or k.lower() == "vary"}
|
||||
try:
|
||||
parsed = json.loads(raw) if raw else None
|
||||
except ValueError:
|
||||
parsed = raw
|
||||
out.append({"request": {"method": step["method"], "path": step["path"],
|
||||
"headers": step.get("headers") or {}, "body": step.get("body")},
|
||||
"status": response.status, "headers": selected, "body": parsed,
|
||||
"state": {"loaded": engine.loaded, "shared": svc.shared}})
|
||||
conn.close()
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
return {"setup": setup, "steps": out}
|
||||
|
||||
scenarios = {}
|
||||
# ---- CORS
|
||||
cors_steps = [
|
||||
{"method": "OPTIONS", "path": "/v1/chat/completions",
|
||||
"headers": {"Origin": "https://a.example", "Access-Control-Request-Headers": "authorization,content-type"}},
|
||||
{"method": "OPTIONS", "path": "/v1/models", "headers": {"Origin": "https://evil.example"}},
|
||||
{"method": "OPTIONS", "path": "/v1/models"},
|
||||
{"method": "OPTIONS", "path": "/health", "headers": {"Origin": "https://a.example"}},
|
||||
{"method": "GET", "path": "/v1/models", "headers": {"Origin": "https://a.example/"}},
|
||||
{"method": "GET", "path": "/v1/status?x=1", "headers": {"Origin": "https://b.example"}},
|
||||
{"method": "GET", "path": "/v1/models", "headers": {"Origin": "https://evil.example"}},
|
||||
{"method": "GET", "path": "/v1/models"},
|
||||
{"method": "GET", "path": "/health", "headers": {"Origin": "https://a.example"}},
|
||||
{"method": "GET", "path": "/props", "headers": {"Origin": "https://a.example"}},
|
||||
{"method": "GET", "path": "/v1/nothing", "headers": {"Origin": "https://a.example"}},
|
||||
]
|
||||
for name, origins in (("off", []), ("any", ["*"]), ("listed", ["https://a.example", "https://b.example"])):
|
||||
scenarios[f"cors_{name}"] = run({"cors_origins": origins}, cors_steps)
|
||||
# (an unknown path answers 404 before authentication in the Python server; the Rust server
|
||||
# authenticates every path first, so that one step is left out here)
|
||||
scenarios[f"cors_{name}_with_key"] = run({"cors_origins": origins, "api_key": "k" * 40}, cors_steps[:-1])
|
||||
# ---- own page
|
||||
page = {"defaults": {"temperature": 0.5}}
|
||||
own = [
|
||||
{"method": "POST", "path": "/settings", "body": page},
|
||||
{"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "http://127.0.0.1:1"}},
|
||||
{"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://evil.example"}},
|
||||
{"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://strata.example.com/"}},
|
||||
{"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://strata.example.com",
|
||||
"Host": "proxy.internal"}},
|
||||
{"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://evil.example",
|
||||
"X-Forwarded-Host": "evil.example",
|
||||
"CF-Ray": "1"}},
|
||||
{"method": "POST", "path": "/settings", "body": json.dumps(page), "headers": {"Content-Type": "text/plain"}},
|
||||
{"method": "POST", "path": "/settings", "body": json.dumps(page),
|
||||
"headers": {"Content-Type": "application/x-www-form-urlencoded"}},
|
||||
{"method": "POST", "path": "/settings", "body": json.dumps(page),
|
||||
"headers": {"Content-Type": "application/json; charset=utf-8"}},
|
||||
{"method": "GET", "path": "/settings"},
|
||||
]
|
||||
scenarios["own_page"] = run({"trusted_origins": ["https://strata.example.com"]}, own)
|
||||
# ---- settings
|
||||
settings = [
|
||||
{"method": "GET", "path": "/settings"},
|
||||
{"method": "POST", "path": "/settings", "body": {"defaults": {"temperature": 0.7, "top_k": 40, "seed": 3}}},
|
||||
{"method": "GET", "path": "/settings"},
|
||||
{"method": "POST", "path": "/settings", "body": {"defaults": {"temperature": 9}}},
|
||||
{"method": "POST", "path": "/settings", "body": {"defaults": {"nonsense": 1}}},
|
||||
{"method": "POST", "path": "/settings", "body": {"defaults": {"top_p": 0, "temperature": 1}}},
|
||||
{"method": "GET", "path": "/settings"},
|
||||
{"method": "POST", "path": "/settings", "body": {"defaults": {"max_tokens": 128, "reasoning_effort": "low",
|
||||
"experimental_speed_projection": True}}},
|
||||
{"method": "GET", "path": "/settings"},
|
||||
{"method": "POST", "path": "/settings", "body": [1, 2]},
|
||||
{"method": "GET", "path": "/settings"},
|
||||
{"method": "POST", "path": "/settings", "body": {"defaults": {"temperature": 0.5}}},
|
||||
{"method": "POST", "path": "/settings", "body": {}},
|
||||
{"method": "GET", "path": "/settings"},
|
||||
{"method": "POST", "path": "/settings", "body": {"defaults": 5}},
|
||||
]
|
||||
scenarios["settings"] = run({}, settings)
|
||||
scenarios["settings_with_key"] = run({"api_key": "k" * 40}, [
|
||||
{"method": "GET", "path": "/settings"},
|
||||
{"method": "GET", "path": "/settings", "headers": {"Authorization": "Bearer " + "k" * 40}},
|
||||
{"method": "POST", "path": "/settings", "body": {"defaults": {"top_k": 5}}},
|
||||
{"method": "POST", "path": "/settings", "body": {"defaults": {"top_k": 5}},
|
||||
"headers": {"Authorization": "Bearer " + "k" * 40}},
|
||||
])
|
||||
# ---- props, slots, health, status
|
||||
reads = [
|
||||
{"method": "GET", "path": "/props"},
|
||||
{"method": "GET", "path": "/props?model=strata-test"},
|
||||
{"method": "GET", "path": "/props?model=alias-one"},
|
||||
{"method": "GET", "path": "/props?model=nope"},
|
||||
{"method": "GET", "path": "/props?model="},
|
||||
{"method": "GET", "path": "/slots"},
|
||||
{"method": "GET", "path": "/api/health"},
|
||||
{"method": "GET", "path": "/v1/status"},
|
||||
]
|
||||
scenarios["reads_loaded"] = run({"aliases": ["alias-one", "alias-two"]}, reads)
|
||||
scenarios["reads_loaded_with_defaults"] = run(
|
||||
{"config_sampling": {"temperature": 0.6, "top_p": 0.95, "top_k": 30, "min_p": 0.02, "presence_penalty": 0.2,
|
||||
"repetition_penalty": 1.05, "penalty_last_n": 64, "seed": 8},
|
||||
"shared": {"temperature": 0.9, "max_tokens": 256}, "max_context": 32768}, reads)
|
||||
scenarios["reads_unloaded"] = run({"loaded": False, "aliases": ["alias-one"]}, reads)
|
||||
scenarios["reads_busy"] = run({"status": {"busy": True, "queued": 2}}, [
|
||||
{"method": "GET", "path": "/slots"}, {"method": "GET", "path": "/v1/status"}])
|
||||
scenarios["reads_with_key"] = run({"api_key": "k" * 40}, [
|
||||
{"method": "GET", "path": "/props"}, {"method": "GET", "path": "/slots"},
|
||||
{"method": "GET", "path": "/v1/status"}, {"method": "GET", "path": "/api/health"},
|
||||
{"method": "GET", "path": "/health"}])
|
||||
# ---- load / unload
|
||||
lifecycle = [
|
||||
{"method": "POST", "path": "/unload"},
|
||||
{"method": "POST", "path": "/unload"},
|
||||
{"method": "GET", "path": "/slots"},
|
||||
{"method": "POST", "path": "/load"},
|
||||
{"method": "POST", "path": "/load"},
|
||||
{"method": "POST", "path": "/v1/unload", "body": {}},
|
||||
{"method": "POST", "path": "/v1/unload", "body": {}},
|
||||
{"method": "POST", "path": "/v1/load", "body": {"model": "other-model"}},
|
||||
{"method": "POST", "path": "/v1/load", "body": {"model": "strata-test"}},
|
||||
{"method": "POST", "path": "/v1/load", "body": {}},
|
||||
{"method": "POST", "path": "/v1/load", "body": "{}", "headers": {"Content-Type": "text/plain"}},
|
||||
{"method": "POST", "path": "/v1/unload", "body": {}, "headers": {"Origin": "https://other.example"}},
|
||||
{"method": "POST", "path": "/v1/unload", "body": [1]},
|
||||
{"method": "POST", "path": "/v1/unload", "body": "not json", "headers": {"Content-Type": "application/json"}},
|
||||
{"method": "POST", "path": "/v1/unload", "body": {"model": None}},
|
||||
{"method": "GET", "path": "/props"},
|
||||
]
|
||||
scenarios["lifecycle"] = run({}, lifecycle)
|
||||
scenarios["lifecycle_busy"] = run({"status": {"queued": 1}}, [
|
||||
{"method": "POST", "path": "/v1/unload", "body": {}},
|
||||
{"method": "POST", "path": "/v1/load", "body": {}},
|
||||
{"method": "POST", "path": "/unload"},
|
||||
{"method": "POST", "path": "/load"},
|
||||
])
|
||||
scenarios["lifecycle_unloaded_then_busy"] = run({"loaded": False, "status": {"busy": True}}, [
|
||||
{"method": "POST", "path": "/v1/load", "body": {}},
|
||||
{"method": "POST", "path": "/unload"},
|
||||
{"method": "POST", "path": "/load"},
|
||||
])
|
||||
scenarios["lifecycle_with_key"] = run({"api_key": "k" * 40}, [
|
||||
{"method": "POST", "path": "/unload"},
|
||||
{"method": "POST", "path": "/v1/unload", "body": {}},
|
||||
{"method": "POST", "path": "/v1/unload", "body": {},
|
||||
"headers": {"Authorization": "Bearer " + "k" * 40, "Origin": "https://other.example"}},
|
||||
{"method": "POST", "path": "/v1/unload", "body": {}, "headers": {"Authorization": "Bearer " + "k" * 40}},
|
||||
{"method": "POST", "path": "/load", "headers": {"x-api-key": "k" * 40}},
|
||||
])
|
||||
write("http_surface", {"source": "serve/server.py Handler (real code, resident fake engine)",
|
||||
"scenarios": scenarios})
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ timings
|
||||
def timings():
|
||||
from serve.server import ByteTokenizer, MockEngine, Service, request_timings
|
||||
from serve.frontend import ChatTemplate
|
||||
from pathlib import Path
|
||||
|
||||
cases = []
|
||||
lasts = [
|
||||
{"prompt_ms": 250.0, "decode_ms": 1000.0, "generated": 50, "reused": 60},
|
||||
{"prompt_ms": 0.0, "decode_ms": 0.0, "generated": 0, "reused": 0},
|
||||
{"prompt_ms": 12.34567, "decode_ms": 98.7654, "generated": 7, "reused": None},
|
||||
{"prompt_ms": 0.25, "decode_ms": 0.05, "generated": 3},
|
||||
{"prompt_ms": 2.675, "decode_ms": 1234.55, "generated": 11, "reused": 5, "drafts_offered": 20, "drafts_accepted": 15},
|
||||
{"prompt_ms": 100.0, "decode_ms": 333.3333, "generated": 0, "reused": 200},
|
||||
{"prompt_ms": 1e-9, "decode_ms": 5e-5, "generated": 9, "reused": 0, "drafts_offered": 0, "drafts_accepted": 0},
|
||||
{"prompt_ms": 12345.678, "decode_ms": 87654.321, "generated": 4096, "reused": 1},
|
||||
]
|
||||
for last in lasts:
|
||||
for prompt_tokens, generated in ((300, last.get("generated") or 5), (10, 10), (0, 0), (50, 7)):
|
||||
cases.append({"last": last, "prompt_tokens": prompt_tokens, "generated": generated,
|
||||
"timings": request_timings(prompt_tokens, generated, last)})
|
||||
cases.append({"last": {}, "prompt_tokens": 5, "generated": 5, "timings": request_timings(5, 5, {})})
|
||||
aliases = []
|
||||
tok = ByteTokenizer()
|
||||
for value in (None, [], ["a"], [" a ", "a", "", "m", "b"], "a, b ,a,,m", ["a", 1], 5, {"a": 1}, "", [""]):
|
||||
svc = Service(MockEngine(tok, "x"), tok, ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja"),
|
||||
model_name="m")
|
||||
try:
|
||||
svc.set_aliases(value)
|
||||
aliases.append({"input": value, "ok": svc.aliases})
|
||||
except ValueError as e:
|
||||
aliases.append({"input": value, "error": str(e)})
|
||||
write("timings", {"source": "serve/server.py request_timings + Service.set_aliases (real code)",
|
||||
"timings": cases, "aliases": aliases}, dest="policy")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ vision
|
||||
def vision():
|
||||
import base64
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from serve.frontend import ChatTemplate, _image_source, images_of, openai_to_messages
|
||||
from serve.server import IMAGE_PAD, VISION_START, ByteTokenizer, MockEngine, Service, Vision
|
||||
|
||||
# base64 as Vision.load decodes data: URLs
|
||||
b64 = []
|
||||
for text in ["QQ==", "QUI=", "QUJD", "QU\nJD", "", "QQ", "Q", "QUJDRA==", "QUJDRA=", "QUJDRA", "QU JD", "QQ==QQ==",
|
||||
"Q=Q=", "!!!!", "QUJD\n", "//8=", "-_8=", "QUJD=", "====", "QUJDREVG", "QUJDREVGRw", "QUJDREVGRw=="]:
|
||||
try:
|
||||
b64.append({"text": text, "ok": Vision.load("data:image/png;base64," + text).hex()})
|
||||
except Exception as e: # binascii.Error and friends
|
||||
b64.append({"text": text, "error": type(e).__name__ + ": " + str(e)})
|
||||
|
||||
sources = [
|
||||
{"type": "image_url", "image_url": {"url": "https://x/y.png"}}, {"type": "image_url", "image_url": "data:abc"},
|
||||
{"type": "input_image", "image_url": "file:///a.png"}, {"type": "image_url"}, {"type": "image_url", "image_url": {}},
|
||||
{"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "QQ=="}},
|
||||
{"type": "image", "source": {"type": "base64", "data": "QQ=="}},
|
||||
{"type": "image", "source": {"type": "url", "url": "http://u"}}, {"type": "image", "source": {"path": "/p.png"}},
|
||||
{"type": "image", "source": {"url": "", "path": "/q.png"}}, {"type": "image"}, {"type": "image", "source": None},
|
||||
]
|
||||
src = [{"part": part, "source": _image_source(part)} for part in sources]
|
||||
|
||||
tok = ByteTokenizer()
|
||||
|
||||
class FakeVision:
|
||||
def __init__(self, counts):
|
||||
self.counts, self.dir = counts, Path(tempfile.mkdtemp(prefix="strata-golden-"))
|
||||
|
||||
def encode(self, source):
|
||||
path = self.dir / (str(abs(hash(source)) % 10**8) + ".sve")
|
||||
path.write_bytes(source.encode())
|
||||
return path, self.counts[source]
|
||||
|
||||
template = ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja")
|
||||
prepared = []
|
||||
cases = [
|
||||
([{"role": "user", "content": "hello"}], {}),
|
||||
([{"role": "user", "content": [{"type": "text", "text": "look"}, {"type": "image_url", "image_url": {"url": "A"}}]}],
|
||||
{"A": 3}),
|
||||
([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "A"}},
|
||||
{"type": "image_url", "image_url": {"url": "B"}},
|
||||
{"type": "text", "text": "compare"}]}], {"A": 2, "B": 5}),
|
||||
([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "A"}}]},
|
||||
{"role": "assistant", "content": "ok"},
|
||||
{"role": "user", "content": [{"type": "text", "text": "again"}, {"type": "image_url", "image_url": {"url": "C"}}]}],
|
||||
{"A": 1, "C": 4}),
|
||||
([{"role": "user", "content": [{"type": "text", "text": "literal " + IMAGE_PAD + " in text"},
|
||||
{"type": "image_url", "image_url": {"url": "A"}}]}], {"A": 2}),
|
||||
([{"role": "user", "content": "just text " + IMAGE_PAD + " again"}], {}),
|
||||
([{"role": "user", "content": [{"type": "text", "text": VISION_START + IMAGE_PAD + " fake"},
|
||||
{"type": "image_url", "image_url": {"url": "A"}}]}], {"A": 2}),
|
||||
]
|
||||
for messages, counts in cases:
|
||||
req = {"messages": messages}
|
||||
norm, tools, kw = openai_to_messages(req)
|
||||
prompt = template.render(norm, tools=tools, **kw)
|
||||
ids_before = tok.encode(prompt, parse_special=True)
|
||||
svc = Service(MockEngine(tok, "x", max_context=100000), tok, template, vision=FakeVision(counts) if counts else None)
|
||||
entry = {"messages": messages, "counts": counts, "ids_before": ids_before,
|
||||
"images": images_of(norm), "pad": tok.encode(IMAGE_PAD, parse_special=True)[0],
|
||||
"start": tok.encode(VISION_START, parse_special=True)[0],
|
||||
"literal": tok.encode(IMAGE_PAD, parse_special=False)}
|
||||
try:
|
||||
ids, thinking, max_new = svc.prepare(norm, tools, kw, 10)
|
||||
entry["ids_after"] = ids
|
||||
entry["combined_hex"] = Path(svc.embeddings.path).read_bytes().hex() if getattr(svc.embeddings, "path", None) else None
|
||||
except ValueError as e:
|
||||
entry["error"] = str(e)
|
||||
prepared.append(entry)
|
||||
write("vision", {"source": "serve/server.py Service.prepare, Vision.load, frontend._image_source (real code)",
|
||||
"base64": b64, "sources": src, "prepare": prepared}, dest="policy")
|
||||
|
||||
|
||||
SECTIONS = {"gen_lines": gen_lines, "shared": shared, "reasoning": reasoning, "http": http_surface,
|
||||
"timings": timings, "vision": vision}
|
||||
|
||||
|
||||
def main(argv):
|
||||
names = argv or list(SECTIONS)
|
||||
for name in names:
|
||||
SECTIONS[name]()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1:])
|
||||
@@ -0,0 +1,330 @@
|
||||
//! The operational HTTP surface (`/props`, `/slots`, `/settings`, `/load`, `/unload`, `/v1/load`,
|
||||
//! `/v1/unload`, `/v1/status`, `/api/health`, CORS, own-page guard) against the real Python
|
||||
//! handlers: every scenario in `tests/fixtures/golden/http_surface.json` was recorded from
|
||||
//! `engine/strata/serve/server.py` by `tests/golden/gen_goldens.py http`, and is replayed here
|
||||
//! against the Rust router with a real worker supervisor and the mock engine.
|
||||
//!
|
||||
//! Deliberate differences, skipped in the comparison: the chat template text, the build/version
|
||||
//! strings, wall-clock fields, JSON parser error wording, the extra `/v1/responses` dialect, and
|
||||
//! `x-api-key` (the Rust server accepts it on the Messages routes only).
|
||||
|
||||
use std::{path::PathBuf, sync::Arc, time::Duration};
|
||||
|
||||
use leleka_serving_policy::{cors::Cors, shared::sampling_defaults_from_config};
|
||||
use serde_json::{Value, json};
|
||||
use strata_control::{
|
||||
app::{AppState, router},
|
||||
lifecycle::Guard,
|
||||
settings::Settings,
|
||||
worker::{WorkerConfig, WorkerState, WorkerStatus, run_supervised},
|
||||
};
|
||||
use tokio::sync::{RwLock, mpsc, watch};
|
||||
|
||||
struct Harness {
|
||||
base: String,
|
||||
state: AppState,
|
||||
stop: watch::Sender<bool>,
|
||||
worker: tokio::task::JoinHandle<()>,
|
||||
server: tokio::task::JoinHandle<()>,
|
||||
dir: PathBuf,
|
||||
_guards: Vec<Guard>,
|
||||
}
|
||||
|
||||
impl Harness {
|
||||
async fn start(name: &str, setup: &Value) -> Self {
|
||||
let dir = std::env::temp_dir().join(format!("strata-http-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let context = setup["max_context"].as_u64().unwrap_or(4096);
|
||||
let loaded = setup["loaded"].as_bool().unwrap_or(true);
|
||||
let engine =
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mock_engine.sh");
|
||||
let config = WorkerConfig {
|
||||
executable: engine.into_os_string(),
|
||||
args: vec![
|
||||
"lifecycle".into(),
|
||||
dir.to_string_lossy().into_owned(),
|
||||
context.to_string(),
|
||||
"--max-context".into(),
|
||||
context.to_string(),
|
||||
],
|
||||
startup_timeout: Duration::from_secs(10),
|
||||
lazy: !loaded,
|
||||
..Default::default()
|
||||
};
|
||||
let status = Arc::new(RwLock::new(WorkerStatus::default()));
|
||||
let (stop, stop_rx) = watch::channel(false);
|
||||
let (requests, requests_rx) = mpsc::channel(4);
|
||||
let (control, control_rx) = mpsc::channel(4);
|
||||
let worker = tokio::spawn(run_supervised(
|
||||
config,
|
||||
status.clone(),
|
||||
stop_rx,
|
||||
requests_rx,
|
||||
control_rx,
|
||||
));
|
||||
|
||||
let config_sampling =
|
||||
sampling_defaults_from_config(setup.get("config_sampling").unwrap_or(&Value::Null))
|
||||
.unwrap();
|
||||
let settings = Settings::new(config_sampling);
|
||||
if let Some(shared) = setup.get("shared") {
|
||||
settings.set_shared(shared).unwrap();
|
||||
}
|
||||
let strings = |key: &str| -> Vec<String> {
|
||||
setup[key]
|
||||
.as_array()
|
||||
.map(|a| a.iter().map(|v| v.as_str().unwrap().to_owned()).collect())
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let api_key = setup["api_key"]
|
||||
.as_str()
|
||||
.filter(|k| !k.is_empty())
|
||||
.map(|key| {
|
||||
let path = dir.join("api-key");
|
||||
std::fs::write(&path, key).unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))
|
||||
.unwrap();
|
||||
}
|
||||
Arc::new(strata_control::auth::ApiKey::from_file(&path).unwrap())
|
||||
});
|
||||
let state = AppState {
|
||||
model: Some(setup["model"].as_str().unwrap_or("strata-test").to_owned()),
|
||||
worker: status,
|
||||
generation: Some(requests),
|
||||
control: Some(control),
|
||||
settings: Arc::new(settings),
|
||||
aliases: Arc::new(strings("aliases")),
|
||||
cors: Arc::new(Cors::new(strings("cors_origins"))),
|
||||
trusted_origins: Arc::new(strings("trusted_origins")),
|
||||
api_key,
|
||||
..Default::default()
|
||||
};
|
||||
// The Python scenarios mark a request as running/queued through its status dict.
|
||||
let mut guards = Vec::new();
|
||||
if let Some(status_setup) = setup.get("status") {
|
||||
let busy = status_setup["busy"].as_bool().unwrap_or(false);
|
||||
let queued = status_setup["queued"].as_u64().unwrap_or(0);
|
||||
if busy {
|
||||
state.worker.write().await.metrics.start();
|
||||
}
|
||||
for _ in 0..(queued + u64::from(busy)) {
|
||||
guards.push(state.lifecycle.generation());
|
||||
}
|
||||
}
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let base = format!("http://{}", listener.local_addr().unwrap());
|
||||
let app = router(state.clone());
|
||||
let server = tokio::spawn(async move {
|
||||
let _ = axum::serve(listener, app).await;
|
||||
});
|
||||
let wanted = if loaded {
|
||||
WorkerState::Ready
|
||||
} else {
|
||||
WorkerState::Unloaded
|
||||
};
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
while state.worker.read().await.state != wanted {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("worker state");
|
||||
Self {
|
||||
base,
|
||||
state,
|
||||
stop,
|
||||
worker,
|
||||
server,
|
||||
dir,
|
||||
_guards: guards,
|
||||
}
|
||||
}
|
||||
|
||||
async fn finish(self) {
|
||||
self.server.abort();
|
||||
self.stop.send(true).unwrap();
|
||||
let _ = tokio::time::timeout(Duration::from_secs(25), self.worker).await;
|
||||
let _ = std::fs::remove_dir_all(self.dir);
|
||||
}
|
||||
}
|
||||
|
||||
fn fixture() -> Value {
|
||||
serde_json::from_str(include_str!("fixtures/golden/http_surface.json")).unwrap()
|
||||
}
|
||||
|
||||
/// Remove what is allowed to differ and return the rest.
|
||||
fn normalized(path: &str, mut value: Value) -> Value {
|
||||
let path = path.split('?').next().unwrap();
|
||||
let remove = |value: &mut Value, keys: &[&str]| {
|
||||
if let Some(map) = value.as_object_mut() {
|
||||
for key in keys {
|
||||
map.remove(*key);
|
||||
}
|
||||
}
|
||||
};
|
||||
match path {
|
||||
// Both servers list the model and its aliases; the Python records carry llama-server extras.
|
||||
"/v1/models" | "/models" => {
|
||||
let reduced: Vec<Value> = value["data"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|record| {
|
||||
json!({"id": record["id"], "alias_of": record["alias_of"],
|
||||
"aliases": record["aliases"],
|
||||
"status": record["status"]["value"].as_str().unwrap_or("loaded")})
|
||||
})
|
||||
.collect();
|
||||
value = json!({"data": reduced});
|
||||
}
|
||||
// `/health` stays the minimal liveness body of the existing smoke contract; `/api/health`
|
||||
// carries the Python fields.
|
||||
"/health" => value = json!({"status": value["status"]}),
|
||||
"/props" => remove(&mut value, &["chat_template", "build_info", "model_path"]),
|
||||
"/v1/status" | "/v1/load" | "/v1/unload" => {
|
||||
remove(
|
||||
&mut value,
|
||||
&[
|
||||
"engine",
|
||||
"started",
|
||||
"uptime_s",
|
||||
"machine",
|
||||
"dialects",
|
||||
"last_timings",
|
||||
],
|
||||
);
|
||||
if let Some(activity) = value.get_mut("activity") {
|
||||
remove(activity, &["last_request_at"]);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
/// The Python server forwards its JSON parser's message; the Rust parser words it differently.
|
||||
fn is_parser_message(status: u64, body: &Value) -> bool {
|
||||
status == 400
|
||||
&& body["error"]["message"]
|
||||
.as_str()
|
||||
.is_some_and(|m| m.contains("line 1 column") || m.contains("Expecting"))
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn the_rust_surface_answers_like_the_python_server() {
|
||||
let fixture = fixture();
|
||||
let scenarios = fixture["scenarios"].as_object().unwrap();
|
||||
assert!(scenarios.len() >= 17);
|
||||
let client = reqwest::Client::builder()
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.build()
|
||||
.unwrap();
|
||||
let mut compared = 0;
|
||||
let mut skipped = 0;
|
||||
for (name, scenario) in scenarios {
|
||||
let harness = Harness::start(name, &scenario["setup"]).await;
|
||||
for (index, step) in scenario["steps"].as_array().unwrap().iter().enumerate() {
|
||||
let request = &step["request"];
|
||||
let method = request["method"].as_str().unwrap();
|
||||
let path = request["path"].as_str().unwrap();
|
||||
let context = format!("{name} step {index}: {method} {path}");
|
||||
let headers = request["headers"].as_object().cloned().unwrap_or_default();
|
||||
if headers.keys().any(|k| k.eq_ignore_ascii_case("x-api-key")) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
let mut builder = client.request(
|
||||
reqwest::Method::from_bytes(method.as_bytes()).unwrap(),
|
||||
format!("{}{path}", harness.base),
|
||||
);
|
||||
let mut has_content_type = false;
|
||||
for (key, value) in &headers {
|
||||
has_content_type |= key.eq_ignore_ascii_case("content-type");
|
||||
builder = builder.header(key.as_str(), value.as_str().unwrap());
|
||||
}
|
||||
match &request["body"] {
|
||||
Value::Null => {}
|
||||
Value::String(raw) => builder = builder.body(raw.clone()),
|
||||
other => {
|
||||
if !has_content_type {
|
||||
builder = builder.header("content-type", "application/json");
|
||||
}
|
||||
builder = builder.body(other.to_string());
|
||||
}
|
||||
}
|
||||
let response = builder
|
||||
.send()
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("{context}: {e}"));
|
||||
let status = response.status().as_u16();
|
||||
let got_headers: Vec<(String, String)> = response
|
||||
.headers()
|
||||
.iter()
|
||||
.filter(|(k, _)| k.as_str().starts_with("access-control-") || k.as_str() == "vary")
|
||||
.map(|(k, v)| (k.as_str().to_owned(), v.to_str().unwrap().to_owned()))
|
||||
.collect();
|
||||
let text = response.text().await.unwrap();
|
||||
let got_body: Value = if text.is_empty() {
|
||||
Value::Null
|
||||
} else {
|
||||
serde_json::from_str(&text).unwrap_or(Value::String(text))
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
u64::from(status),
|
||||
step["status"].as_u64().unwrap(),
|
||||
"{context}: {got_body}"
|
||||
);
|
||||
let want_headers = step["headers"].as_object().unwrap();
|
||||
assert_eq!(
|
||||
got_headers.len(),
|
||||
want_headers.len(),
|
||||
"{context}: {got_headers:?}"
|
||||
);
|
||||
for (key, value) in want_headers {
|
||||
assert!(
|
||||
got_headers
|
||||
.iter()
|
||||
.any(|(k, v)| k == key && v == value.as_str().unwrap()),
|
||||
"{context}: header {key}: {got_headers:?}"
|
||||
);
|
||||
}
|
||||
if status == 401 {
|
||||
// The Rust server's authentication body is its own (OpenAI-style code and message).
|
||||
assert_eq!(
|
||||
got_body["error"]["type"], step["body"]["error"]["type"],
|
||||
"{context}"
|
||||
);
|
||||
} else if is_parser_message(step["status"].as_u64().unwrap(), &step["body"]) {
|
||||
assert_eq!(
|
||||
got_body["error"]["type"], step["body"]["error"]["type"],
|
||||
"{context}"
|
||||
);
|
||||
skipped += 1;
|
||||
} else {
|
||||
let want_path = path.split('?').next().unwrap();
|
||||
let want_body = normalized(want_path, step["body"].clone());
|
||||
let got_body = normalized(want_path, got_body);
|
||||
assert_eq!(got_body, want_body, "{context}");
|
||||
}
|
||||
let loaded = harness.state.worker.read().await.state == WorkerState::Ready;
|
||||
assert_eq!(
|
||||
loaded,
|
||||
step["state"]["loaded"].as_bool().unwrap(),
|
||||
"{context}: loaded"
|
||||
);
|
||||
assert_eq!(
|
||||
harness.state.settings.shared().to_json(),
|
||||
step["state"]["shared"],
|
||||
"{context}: shared settings"
|
||||
);
|
||||
compared += 1;
|
||||
}
|
||||
harness.finish().await;
|
||||
}
|
||||
assert!(compared > 120, "{compared} compared, {skipped} skipped");
|
||||
}
|
||||
@@ -0,0 +1,444 @@
|
||||
//! The MCP hub against the Python fake server of the Original (`engine/strata/serve/mcp_fake_server.py`,
|
||||
//! standard library only; a test double, not part of serving): stdio and Streamable HTTP clients,
|
||||
//! paging, namespacing, errors as text, timeouts, the result cap, restart on demand, cancellation.
|
||||
//! The tests are skipped (with a message) when `python3` is not installed.
|
||||
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
io::{BufRead, BufReader},
|
||||
path::PathBuf,
|
||||
process::{Child, Command, Stdio},
|
||||
};
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use strata_control::mcp::{Hub, McpError, Settings, servers_from, settings_from};
|
||||
use tokio::sync::watch;
|
||||
|
||||
fn fake_path() -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../engine/strata/serve/mcp_fake_server.py")
|
||||
}
|
||||
|
||||
fn python() -> Option<&'static str> {
|
||||
Command::new("python3")
|
||||
.arg("--version")
|
||||
.stdout(Stdio::null())
|
||||
.status()
|
||||
.ok()
|
||||
.filter(|s| s.success())
|
||||
.map(|_| "python3")
|
||||
}
|
||||
|
||||
fn stdio(args: &[&str], log: Option<&PathBuf>) -> Map<String, Value> {
|
||||
let mut all = vec![fake_path().to_string_lossy().into_owned()];
|
||||
all.extend(args.iter().map(|a| (*a).to_owned()));
|
||||
let mut config = json!({"command": "python3", "args": all});
|
||||
if let Some(log) = log {
|
||||
config["env"] = json!({"FAKE_MCP_LOG": log});
|
||||
}
|
||||
config.as_object().unwrap().clone()
|
||||
}
|
||||
|
||||
fn hub(servers: Vec<(&str, Map<String, Value>)>, settings: Settings) -> Hub {
|
||||
Hub::new(
|
||||
servers
|
||||
.into_iter()
|
||||
.map(|(n, c)| (n.to_owned(), c))
|
||||
.collect::<BTreeMap<_, _>>(),
|
||||
settings,
|
||||
)
|
||||
}
|
||||
|
||||
fn names(status: &Value, server: &str) -> Vec<String> {
|
||||
status["servers"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|s| s["name"] == server)
|
||||
.unwrap()["tools"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|t| t["name"].as_str().unwrap().to_owned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
const TOOLS: [&str; 6] = ["echo", "fail", "sleep", "big", "die", "add"];
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn stdio_servers_list_call_and_fail_like_the_python_hub() {
|
||||
if python().is_none() {
|
||||
eprintln!("python3 not found: skipped");
|
||||
return;
|
||||
}
|
||||
let log = std::env::temp_dir().join(format!("strata-mcp-{}.jsonl", std::process::id()));
|
||||
let _ = std::fs::remove_file(&log);
|
||||
let settings = Settings {
|
||||
timeout_s: 1.5,
|
||||
max_result_chars: 1000,
|
||||
..Settings::default()
|
||||
};
|
||||
let hub = hub(
|
||||
vec![
|
||||
("fake", stdio(&[], Some(&log))),
|
||||
("paged", stdio(&["--page", "4"], None)),
|
||||
("broken", stdio(&["--crash-at-start"], None)),
|
||||
(
|
||||
"missing",
|
||||
json!({"command": "strata-no-such-program"})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
),
|
||||
],
|
||||
settings,
|
||||
);
|
||||
hub.start().await;
|
||||
let status = hub.status().await;
|
||||
let by_name = |n: &str| -> Value {
|
||||
status["servers"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|s| s["name"] == n)
|
||||
.unwrap()
|
||||
.clone()
|
||||
};
|
||||
|
||||
// initialize + tools/list over every page
|
||||
assert_eq!(by_name("fake")["status"], "ready");
|
||||
assert_eq!(by_name("fake")["transport"], "stdio");
|
||||
assert_eq!(by_name("fake")["info"]["name"], "fake");
|
||||
assert_eq!(by_name("fake")["info"]["protocol"], "2025-06-18");
|
||||
let want: Vec<String> = TOOLS.iter().map(|t| format!("fake__{t}")).collect();
|
||||
assert_eq!(names(&status, "fake"), want);
|
||||
assert_eq!(
|
||||
names(&status, "paged"),
|
||||
TOOLS
|
||||
.iter()
|
||||
.map(|t| format!("paged__{t}"))
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(status["tools"], 12);
|
||||
assert_eq!(status["settings"]["max_result_chars"], 1000);
|
||||
|
||||
// servers that do not start are left out, with the reason
|
||||
assert_eq!(by_name("broken")["status"], "failed");
|
||||
assert!(
|
||||
by_name("broken")["error"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("missing configuration"),
|
||||
"{}",
|
||||
by_name("broken")
|
||||
);
|
||||
assert_eq!(by_name("missing")["status"], "failed");
|
||||
assert!(
|
||||
by_name("missing")["error"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("could not start")
|
||||
);
|
||||
|
||||
// the tools in the chat template's form
|
||||
let tools = hub.template_tools(&["paged__echo".to_owned()]).await;
|
||||
let echo = tools.iter().find(|t| t["name"] == "fake__echo").unwrap();
|
||||
assert_eq!(echo["parameters"]["properties"]["text"]["type"], "string");
|
||||
assert_eq!(echo["description"], "Returns the text it is given.");
|
||||
assert!(tools.iter().all(|t| t["name"] != "paged__echo"));
|
||||
assert_eq!(tools.len(), 11);
|
||||
|
||||
// calls
|
||||
let r = hub
|
||||
.call("fake__echo", json!({"text": "hello wörld"}), None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(r.ok, r.text.as_str(), r.server.as_deref(), r.tool.as_str()),
|
||||
(true, "hello wörld", Some("fake"), "echo")
|
||||
);
|
||||
assert_eq!(
|
||||
hub.call("fake__add", json!({"a": 2, "b": 40}), None)
|
||||
.await
|
||||
.unwrap()
|
||||
.text,
|
||||
"42"
|
||||
);
|
||||
let r = hub.call("fake__fail", json!({}), None).await.unwrap();
|
||||
assert!(!r.ok);
|
||||
assert_eq!(r.text, "error: it failed on purpose");
|
||||
let r = hub.call("nobody__nothing", json!({}), None).await.unwrap();
|
||||
assert!(
|
||||
!r.ok && r.text.starts_with("error: there is no tool"),
|
||||
"{}",
|
||||
r.text
|
||||
);
|
||||
// arguments that are not an object are sent as {}
|
||||
assert_eq!(
|
||||
hub.call("fake__echo", json!("x"), None).await.unwrap().text,
|
||||
""
|
||||
);
|
||||
// a JSON-RPC error from the server
|
||||
let fake = hub.servers.iter().find(|s| s.name == "fake").unwrap();
|
||||
let error = fake
|
||||
.call(
|
||||
"no-such-tool",
|
||||
json!({}),
|
||||
std::time::Duration::from_secs(5),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("unknown tool"), "{error}");
|
||||
|
||||
// a call that outlasts the timeout, then the server still answers
|
||||
let started = std::time::Instant::now();
|
||||
let r = hub
|
||||
.call("fake__sleep", json!({"seconds": 5}), None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(started.elapsed().as_secs_f64() < 4.0);
|
||||
assert!(!r.ok);
|
||||
assert!(r.text.contains("timed out after 1.5 s"), "{}", r.text);
|
||||
assert_eq!(
|
||||
hub.call("fake__echo", json!({"text": "still here"}), None)
|
||||
.await
|
||||
.unwrap()
|
||||
.text,
|
||||
"still here"
|
||||
);
|
||||
|
||||
// the result cap
|
||||
let r = hub
|
||||
.call("fake__big", json!({"n": 50000}), None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(r.ok && r.truncated);
|
||||
assert_eq!(r.chars, 50000);
|
||||
assert!(
|
||||
r.text
|
||||
.starts_with(&format!("{}\n\n[... truncated", "y".repeat(1000)))
|
||||
);
|
||||
assert!(r.text.contains("50,000 characters"));
|
||||
assert!(r.text.chars().count() < 1200);
|
||||
|
||||
// cancellation reaches the server as notifications/cancelled
|
||||
let (stop, cancel) = watch::channel(false);
|
||||
let canceller = tokio::spawn(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
|
||||
let _ = stop.send(true);
|
||||
});
|
||||
let started = std::time::Instant::now();
|
||||
let outcome = hub
|
||||
.call("fake__sleep", json!({"seconds": 1.2}), Some(cancel))
|
||||
.await;
|
||||
assert_eq!(outcome.unwrap_err(), McpError::Cancelled);
|
||||
assert!(started.elapsed().as_secs_f64() < 1.0);
|
||||
canceller.await.unwrap();
|
||||
tokio::time::sleep(std::time::Duration::from_millis(400)).await;
|
||||
let seen = std::fs::read_to_string(&log).unwrap();
|
||||
assert!(seen.contains("\"cancelled\""), "{seen}");
|
||||
|
||||
hub.close().await;
|
||||
let _ = std::fs::remove_file(&log);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_server_that_dies_mid_call_is_started_again_by_the_next_call() {
|
||||
if python().is_none() {
|
||||
eprintln!("python3 not found: skipped");
|
||||
return;
|
||||
}
|
||||
let hub = hub(
|
||||
vec![("solo", stdio(&[], None))],
|
||||
Settings {
|
||||
timeout_s: 5.0,
|
||||
..Settings::default()
|
||||
},
|
||||
);
|
||||
hub.start().await;
|
||||
let r = hub.call("solo__die", json!({}), None).await.unwrap();
|
||||
assert!(!r.ok);
|
||||
assert!(r.text.contains("the server stopped"), "{}", r.text);
|
||||
assert!(r.text.contains("dying on purpose"), "{}", r.text);
|
||||
let status = hub.status().await;
|
||||
assert_eq!(status["servers"][0]["status"], "stopped");
|
||||
assert_eq!(
|
||||
status["tools"], 6,
|
||||
"its tools stay: the next call restarts it"
|
||||
);
|
||||
let r = hub
|
||||
.call("solo__echo", json!({"text": "back"}), None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(r.text, "back");
|
||||
assert_eq!(hub.status().await["servers"][0]["status"], "ready");
|
||||
hub.close().await;
|
||||
}
|
||||
|
||||
struct HttpFake(Child);
|
||||
|
||||
impl HttpFake {
|
||||
fn start(port: u16) -> Self {
|
||||
let mut child = Command::new("python3")
|
||||
.arg(fake_path())
|
||||
.args(["--http", &port.to_string()])
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut line = String::new();
|
||||
BufReader::new(child.stdout.take().unwrap())
|
||||
.read_line(&mut line)
|
||||
.unwrap();
|
||||
assert!(line.contains("listening"), "{line}");
|
||||
Self(child)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for HttpFake {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn streamable_http_servers_answer_as_json_or_as_an_event_stream() {
|
||||
if python().is_none() {
|
||||
eprintln!("python3 not found: skipped");
|
||||
return;
|
||||
}
|
||||
let port = {
|
||||
let probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
probe.local_addr().unwrap().port()
|
||||
};
|
||||
let _server = HttpFake::start(port);
|
||||
let hub =
|
||||
hub(
|
||||
vec![
|
||||
(
|
||||
"web",
|
||||
json!({"url": format!("http://127.0.0.1:{port}/mcp"), "headers": {"X-Test": "1"}})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
),
|
||||
(
|
||||
"down",
|
||||
json!({"url": "http://127.0.0.1:9/mcp"}).as_object().unwrap().clone(),
|
||||
),
|
||||
],
|
||||
Settings {
|
||||
timeout_s: 1.5,
|
||||
..Settings::default()
|
||||
},
|
||||
);
|
||||
hub.start().await;
|
||||
let status = hub.status().await;
|
||||
let server = |n: &str, status: &Value| -> Value {
|
||||
status["servers"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|s| s["name"] == n)
|
||||
.unwrap()
|
||||
.clone()
|
||||
};
|
||||
assert_eq!(server("web", &status)["transport"], "http");
|
||||
assert_eq!(server("web", &status)["status"], "ready", "{status}");
|
||||
assert_eq!(names(&status, "web").len(), 6); // paged, with the session id on every request
|
||||
// tools/call answers as an event stream with a progress notification first
|
||||
assert_eq!(
|
||||
hub.call("web__echo", json!({"text": "over http"}), None)
|
||||
.await
|
||||
.unwrap()
|
||||
.text,
|
||||
"over http"
|
||||
);
|
||||
assert_eq!(
|
||||
hub.call("web__fail", json!({}), None).await.unwrap().text,
|
||||
"error: it failed on purpose"
|
||||
);
|
||||
let r = hub
|
||||
.call("web__sleep", json!({"seconds": 4}), None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(r.text.contains("timed out"), "{}", r.text);
|
||||
let down = server("down", &hub.status().await);
|
||||
assert_eq!(down["status"], "failed");
|
||||
assert!(down["error"].as_str().unwrap().contains("could not reach"));
|
||||
hub.close().await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_accepts_both_spellings_and_checks_every_entry() {
|
||||
let both = servers_from(
|
||||
&json!({"a": {"command": "x"}, "off": {"url": "http://h/mcp", "disabled": true}}),
|
||||
"config mcp_servers",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(both.keys().collect::<Vec<_>>(), ["a"]);
|
||||
for (bad, why) in [
|
||||
(json!({"a": {}}), "needs \"command\""),
|
||||
(
|
||||
json!({"a": {"command": "x", "args": "y"}}),
|
||||
"\"args\" must be a list",
|
||||
),
|
||||
(
|
||||
json!({"a": {"url": "http://h", "type": "sse"}}),
|
||||
"old SSE transport",
|
||||
),
|
||||
(
|
||||
json!({"a": {"url": "http://h", "headers": ["x"]}}),
|
||||
"\"headers\" must be an object",
|
||||
),
|
||||
] {
|
||||
let error = servers_from(&bad, "config mcpServers").unwrap_err();
|
||||
assert!(error.contains(why), "{error}");
|
||||
assert!(
|
||||
error.starts_with("[strata] config mcpServers: MCP server 'a'"),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
settings_from(&json!({"max_rounds": 0}))
|
||||
.unwrap_err()
|
||||
.contains("positive integer")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn get_mcp_reports_the_hub_or_an_empty_list() {
|
||||
use std::sync::Arc;
|
||||
use strata_control::app::{AppState, router};
|
||||
|
||||
async fn get(state: AppState) -> Value {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("http://{}/mcp", listener.local_addr().unwrap());
|
||||
let app = router(state);
|
||||
let server = tokio::spawn(async move {
|
||||
let _ = axum::serve(listener, app).await;
|
||||
});
|
||||
let text = reqwest::get(url).await.unwrap().text().await.unwrap();
|
||||
let answer: Value = serde_json::from_str(&text).unwrap();
|
||||
server.abort();
|
||||
answer
|
||||
}
|
||||
assert_eq!(
|
||||
get(AppState::default()).await,
|
||||
json!({"servers": [], "tools": 0})
|
||||
);
|
||||
let hub = Arc::new(hub(
|
||||
vec![("broken", stdio(&["--crash-at-start"], None))],
|
||||
Settings::default(),
|
||||
));
|
||||
hub.start().await;
|
||||
let state = AppState {
|
||||
mcp: Some(hub.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
let answer = get(state).await;
|
||||
assert_eq!(answer["servers"][0]["status"], "failed");
|
||||
assert_eq!(answer["tools"], 0);
|
||||
assert_eq!(answer["settings"]["max_rounds"], 8);
|
||||
hub.close().await;
|
||||
}
|
||||
@@ -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
|
||||
Executable
+36
@@ -0,0 +1,36 @@
|
||||
#!/bin/sh
|
||||
# Rebuild the host oracles and regenerate the committed fixtures. macOS or Linux, clang++ or g++, no CUDA.
|
||||
# crates/serving-policy/oracle/build_oracle.sh [output_dir]
|
||||
# The vision oracle compiles code EXTRACTED from the pinned generate.cpp (not retyped): the GENI embeddings /
|
||||
# M-RoPE block and fnv1a, found by their text, so a change in the pinned source shows up as a failed extraction
|
||||
# or a fixture diff.
|
||||
set -eu
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
root=$(cd "$here/../../.." && pwd)
|
||||
engine="$root/engine/strata"
|
||||
out=${1:-"$here/../tests/fixtures"}
|
||||
work=${TMPDIR:-/tmp}/leleka_serving_oracle.$$
|
||||
mkdir -p "$work" "$out"
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
|
||||
# ---- stride + watchdog
|
||||
${CXX:-clang++} -std=c++17 -O1 -Wno-unused-function -I "$engine/include" "$here/gen_host_fixtures.cpp" -o "$work/host"
|
||||
"$work/host" "$out/host_oracle.json"
|
||||
|
||||
# ---- GENI embeddings block, verbatim
|
||||
gen="$engine/src/program/generate.cpp"
|
||||
awk '/^uint64_t fnv1a\(/ {p=1} p {print} p && /^}/ {exit}' "$gen" > "$work/fnv1a.inc"
|
||||
awk '/if \(geni \|\| !mrope_identity\) \{/ {p=1} /tr\("positions built"/ {p=0} p {print}' "$gen" > "$work/generate_block.inc"
|
||||
[ -s "$work/fnv1a.inc" ] && [ -s "$work/generate_block.inc" ] || { echo "could not extract the GENI block from $gen" >&2; exit 1; }
|
||||
grep -q 'bad embeddings file' "$work/generate_block.inc" || { echo "extracted block is not the GENI embeddings code" >&2; exit 1; }
|
||||
${CXX:-clang++} -std=c++20 -O1 -Wno-unused-function -Wno-unused-variable -I "$engine/include" -I "$work" \
|
||||
"$here/gen_vision_fixtures.cpp" -o "$work/vision"
|
||||
"$work/vision" "$out/vision_oracle.json"
|
||||
|
||||
# ---- control vector loader, verbatim
|
||||
awk '/^bool load_control_vectors\(/ {p=1} p {print} p && /^}/ {exit}' "$gen" > "$work/load_control_vectors.inc"
|
||||
[ -s "$work/load_control_vectors.inc" ] && grep -q 'no direction.<layer> tensors' "$work/load_control_vectors.inc" \
|
||||
|| { echo "could not extract load_control_vectors from $gen" >&2; exit 1; }
|
||||
${CXX:-clang++} -std=c++20 -O1 -ffp-contract=off -fno-fast-math -Wno-unused-function -Wno-unused-variable -I "$engine/include" -I "$work" \
|
||||
"$here/gen_cvec_fixtures.cpp" -o "$work/cvec"
|
||||
"$work/cvec" "$out/cvec_oracle.json"
|
||||
@@ -0,0 +1,206 @@
|
||||
// Host oracle for control vectors: `load_control_vectors` of src/program/generate.cpp INCLUDED VERBATIM
|
||||
// (extracted by build_oracle.sh) with the Options / ModelGeometry / cvec_upload it needs stubbed, driven over
|
||||
// small GGUF control-vector files this harness writes. The tables it would upload (dir, s) are recorded as
|
||||
// raw float bits, so the Rust loader can be compared bit for bit (-ffp-contract=off pins the host arithmetic).
|
||||
//
|
||||
// Usage: gen_cvec_fixtures OUT.json
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <unistd.h>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "strata/artifact/gguf_reader.hpp"
|
||||
|
||||
struct Options {
|
||||
std::vector<std::pair<std::string, float>> cvec_files;
|
||||
int cvec_first = -1, cvec_last = -1;
|
||||
int cvec_mode = 1;
|
||||
int cvec_single = -1;
|
||||
};
|
||||
namespace strata::core { struct ModelGeometry { int64_t n_layers = 0, n_embd = 0, hc = 0; }; }
|
||||
namespace strata::kernels {
|
||||
struct Captured { std::vector<float> dir, s; int mode = 0, first = 0, last = 0; bool called = false; };
|
||||
Captured g_up;
|
||||
bool cvec_upload(const std::vector<float>& dir, const std::vector<float>& s, int mode, int first, int last, int64_t, int64_t,
|
||||
std::string&) {
|
||||
g_up = {dir, s, mode, first, last, true};
|
||||
return true;
|
||||
}
|
||||
} // namespace strata::kernels
|
||||
|
||||
#include "load_control_vectors.inc"
|
||||
|
||||
// ---- a minimal GGUF v3 writer ---------------------------------------------------------------------------------
|
||||
struct Tensor { std::string name; uint32_t type; std::vector<uint64_t> dims; std::vector<float> data; };
|
||||
static void w32(std::string& s, uint32_t v) { s.append((const char*) &v, 4); }
|
||||
static void w64(std::string& s, uint64_t v) { s.append((const char*) &v, 8); }
|
||||
static void wstr(std::string& s, const std::string& v) { w64(s, v.size()); s += v; }
|
||||
static std::string gguf(const std::vector<std::pair<std::string, std::string>>& kv, const std::vector<Tensor>& ts) {
|
||||
std::string s = "GGUF";
|
||||
w32(s, 3);
|
||||
w64(s, ts.size());
|
||||
w64(s, kv.size());
|
||||
for (const auto& [k, v] : kv) { wstr(s, k); w32(s, 8); wstr(s, v); }
|
||||
uint64_t offset = 0;
|
||||
std::vector<uint64_t> offsets;
|
||||
for (const Tensor& t : ts) {
|
||||
wstr(s, t.name);
|
||||
w32(s, (uint32_t) t.dims.size());
|
||||
for (uint64_t d : t.dims) w64(s, d);
|
||||
w32(s, t.type);
|
||||
w64(s, offset);
|
||||
offsets.push_back(offset);
|
||||
offset += (t.data.size() * 4 + 31) / 32 * 32;
|
||||
}
|
||||
while (s.size() % 32) s += '\0';
|
||||
for (const Tensor& t : ts) {
|
||||
s.append((const char*) t.data.data(), t.data.size() * 4);
|
||||
while (s.size() % 32) s += '\0';
|
||||
}
|
||||
return s;
|
||||
}
|
||||
static std::string hex(const std::string& s) {
|
||||
static const char* d = "0123456789abcdef";
|
||||
std::string o;
|
||||
for (unsigned char c : s) { o += d[c >> 4]; o += d[c & 15]; }
|
||||
return o;
|
||||
}
|
||||
static std::string jstr(const std::string& s) {
|
||||
std::string o = "\"";
|
||||
for (char c : s) { if (c == '"' || c == '\\') o += '\\'; o += c; }
|
||||
return o + "\"";
|
||||
}
|
||||
static Tensor dir(const std::string& name, int64_t n, float seed, float step = 0.37f) {
|
||||
Tensor t{name, 0, {(uint64_t) n}, {}};
|
||||
for (int64_t j = 0; j < n; ++j) t.data.push_back(seed + step * (float) j - (j % 3 == 0 ? 0.5f : 0.0f));
|
||||
return t;
|
||||
}
|
||||
|
||||
struct Case {
|
||||
std::string name;
|
||||
std::vector<std::pair<std::string, float>> files; // index into blobs, scale
|
||||
int first, last, mode, single;
|
||||
};
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc < 2) return 2;
|
||||
constexpr int64_t L = 6, N = 5, HC = 2;
|
||||
const std::string base = std::string(std::getenv("TMPDIR") ? std::getenv("TMPDIR") : "/tmp") + "/strata_cvec_oracle_" + std::to_string((long long) getpid());
|
||||
const std::vector<std::pair<std::string, std::string>> good = {{"general.architecture", "controlvector"}, {"controlvector.model_hint", "qwen4exp"}};
|
||||
std::vector<std::string> blobs = {
|
||||
// 0: directions for layers 1, 2, 4 (3 and 5 have none)
|
||||
gguf(good, {dir("direction.1", N, 1.0f), dir("direction.2", N, -0.5f), dir("direction.4", N, 2.0f)}),
|
||||
// 1: directions for 2, 3
|
||||
gguf(good, {dir("direction.2", N, 0.25f, 0.11f), dir("direction.3", N, 3.0f)}),
|
||||
// 2: not a control vector
|
||||
gguf({{"general.architecture", "llama"}}, {dir("direction.1", N, 1.0f)}),
|
||||
// 3: no direction tensors
|
||||
gguf(good, {dir("other.1", N, 1.0f)}),
|
||||
// 4: wrong size
|
||||
gguf(good, {dir("direction.1", N + 1, 1.0f)}),
|
||||
// 5: wrong type (F16 id 1)
|
||||
gguf(good, {Tensor{"direction.1", 1, {(uint64_t) N}, std::vector<float>(3, 0.0f)}}),
|
||||
// 6: layer 0, past the model, a non-number, a padded number: ignored / strtol semantics
|
||||
gguf(good, {dir("direction.0", N, 9.0f), dir("direction.6", N, 9.0f), dir("direction.99", N, 9.0f), dir("direction.abc", N, 9.0f),
|
||||
dir("direction.03", N, 0.75f)}),
|
||||
// 7: all zeros
|
||||
gguf(good, {Tensor{"direction.1", 0, {(uint64_t) N}, std::vector<float>(N, 0.0f)}, Tensor{"direction.2", 0, {(uint64_t) N}, std::vector<float>(N, 0.0f)}}),
|
||||
// 8: another model's hint (a warning on stderr only)
|
||||
gguf({{"general.architecture", "controlvector"}, {"controlvector.model_hint", "llama"}}, {dir("direction.1", N, 1.0f)}),
|
||||
// 9: no hint at all
|
||||
gguf({{"general.architecture", "controlvector"}}, {dir("direction.5", N, -1.0f)}),
|
||||
};
|
||||
std::vector<Case> cases = {
|
||||
{"add, one file, default range", {{"0", 1.0f}}, -1, -1, 1, -1},
|
||||
{"add, two files scaled and summed", {{"0", 0.5f}, {"1", -2.0f}}, -1, -1, 1, -1},
|
||||
{"project, one file", {{"0", 1.0f}}, -1, -1, 0, -1},
|
||||
{"project, two files", {{"0", 1.5f}, {"1", 1.0f}}, -1, -1, 0, -1},
|
||||
{"add, layer range 2..3", {{"0", 1.0f}, {"1", 1.0f}}, 2, 3, 1, -1},
|
||||
{"add, range past the model", {{"0", 1.0f}}, 1, 99, 1, -1},
|
||||
{"project, range first only", {{"0", 1.0f}}, 3, -1, 0, -1},
|
||||
{"project single:2", {{"0", 1.0f}}, -1, -1, 0, 2},
|
||||
{"project single:2 over a range", {{"0", 1.0f}, {"1", 1.0f}}, 2, 5, 0, 2},
|
||||
{"add ignores single", {{"0", 1.0f}}, -1, -1, 1, 2},
|
||||
{"project single without a direction", {{"0", 1.0f}}, -1, -1, 0, 3},
|
||||
{"project single past the model", {{"0", 1.0f}}, -1, -1, 0, 6},
|
||||
{"scale zero adds nothing but still counts as found", {{"0", 0.0f}}, -1, -1, 1, -1},
|
||||
{"scale zero in project mode steers nothing", {{"0", 0.0f}}, -1, -1, 0, -1},
|
||||
{"layers 0 / past-model / non-numeric ignored, 03 is layer 3", {{"6", 1.0f}}, -1, -1, 1, -1},
|
||||
{"not a control vector", {{"2", 1.0f}}, -1, -1, 1, -1},
|
||||
{"no direction tensors", {{"3", 1.0f}}, -1, -1, 1, -1},
|
||||
{"wrong tensor size", {{"4", 1.0f}}, -1, -1, 1, -1},
|
||||
{"wrong tensor type", {{"5", 1.0f}}, -1, -1, 1, -1},
|
||||
{"all-zero directions in project mode", {{"7", 1.0f}}, -1, -1, 0, -1},
|
||||
{"all-zero directions in add mode", {{"7", 1.0f}}, -1, -1, 1, -1},
|
||||
{"another model's hint still loads", {{"8", 1.0f}}, -1, -1, 1, -1},
|
||||
{"no hint", {{"9", 1.0f}}, -1, -1, 1, -1},
|
||||
{"second file bad", {{"0", 1.0f}, {"3", 1.0f}}, -1, -1, 1, -1},
|
||||
{"no steered layer in the range", {{"0", 1.0f}}, 5, 5, 1, -1},
|
||||
};
|
||||
std::FILE* f = std::fopen(argv[1], "w");
|
||||
if (!f) return 2;
|
||||
std::fprintf(f, "{\n \"source\": \"src/program/generate.cpp load_control_vectors (verbatim) over GGUF files written by gen_cvec_fixtures.cpp\",\n"
|
||||
" \"n_layers\": %lld, \"n_embd\": %lld, \"hc\": %lld,\n \"blobs\": [", (long long) L, (long long) N, (long long) HC);
|
||||
for (size_t i = 0; i < blobs.size(); ++i) std::fprintf(f, "%s\"%s\"", i ? "," : "", hex(blobs[i]).c_str());
|
||||
std::fprintf(f, "],\n \"cases\": [");
|
||||
bool first = true;
|
||||
for (const Case& c : cases) {
|
||||
Options o;
|
||||
o.cvec_first = c.first;
|
||||
o.cvec_last = c.last;
|
||||
o.cvec_mode = c.mode;
|
||||
o.cvec_single = c.single;
|
||||
std::vector<std::pair<int, float>> used;
|
||||
for (size_t k = 0; k < c.files.size(); ++k) {
|
||||
const int blob = std::atoi(c.files[k].first.c_str());
|
||||
const std::string path = base + "_" + std::to_string(blob) + ".gguf";
|
||||
std::FILE* w = std::fopen(path.c_str(), "wb");
|
||||
std::fwrite(blobs[(size_t) blob].data(), 1, blobs[(size_t) blob].size(), w);
|
||||
std::fclose(w);
|
||||
o.cvec_files.push_back({path, c.files[k].second});
|
||||
used.push_back({blob, c.files[k].second});
|
||||
}
|
||||
strata::core::ModelGeometry g;
|
||||
g.n_layers = L; g.n_embd = N; g.hc = HC;
|
||||
strata::kernels::g_up = {};
|
||||
std::string summary, err;
|
||||
const bool ok = load_control_vectors(o, g, summary, err);
|
||||
// the temp paths carry this process's id: name the files by their blob instead
|
||||
for (size_t k = 0; k < used.size(); ++k) {
|
||||
const std::string path = o.cvec_files[k].first, label = "FILE" + std::to_string(used[k].first);
|
||||
for (size_t at = err.find(path); at != std::string::npos; at = err.find(path)) err.replace(at, path.size(), label);
|
||||
}
|
||||
std::fprintf(f, "%s\n {\"name\": %s, \"files\": [", first ? "" : ",", jstr(c.name).c_str());
|
||||
for (size_t k = 0; k < used.size(); ++k) {
|
||||
uint32_t bits; std::memcpy(&bits, &used[k].second, 4);
|
||||
std::fprintf(f, "%s[%d, %u]", k ? "," : "", used[k].first, bits);
|
||||
}
|
||||
std::fprintf(f, "], \"first\": %d, \"last\": %d, \"mode\": \"%s\", \"single\": %d, \"ok\": %s, \"err\": %s, \"summary\": %s",
|
||||
c.first, c.last, c.mode == 0 ? "project" : "add", c.single, ok ? "true" : "false", jstr(err).c_str(), jstr(summary).c_str());
|
||||
if (ok) {
|
||||
std::fprintf(f, ", \"up\": {\"mode\": %d, \"first\": %d, \"last\": %d, \"dir_bits\": [", strata::kernels::g_up.mode,
|
||||
strata::kernels::g_up.first, strata::kernels::g_up.last);
|
||||
for (size_t i = 0; i < strata::kernels::g_up.dir.size(); ++i) {
|
||||
uint32_t bits; std::memcpy(&bits, &strata::kernels::g_up.dir[i], 4);
|
||||
std::fprintf(f, "%s%u", i ? "," : "", bits);
|
||||
}
|
||||
std::fprintf(f, "], \"s_bits\": [");
|
||||
for (size_t i = 0; i < strata::kernels::g_up.s.size(); ++i) {
|
||||
uint32_t bits; std::memcpy(&bits, &strata::kernels::g_up.s[i], 4);
|
||||
std::fprintf(f, "%s%u", i ? "," : "", bits);
|
||||
}
|
||||
std::fprintf(f, "]}");
|
||||
}
|
||||
std::fprintf(f, "}");
|
||||
first = false;
|
||||
for (const auto& [p, s] : o.cvec_files) { (void) s; std::remove(p.c_str()); }
|
||||
}
|
||||
std::fprintf(f, "\n ]\n}\n");
|
||||
std::fclose(f);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
// Host oracle for the serving policies that are plain C++ in the Original (no CUDA):
|
||||
// * logits_selection.hpp - compiled UNMODIFIED from engine/strata/include;
|
||||
// * the stall watchdog: core/progress.hpp (Progress, progress_now_ms) compiled unmodified, and the
|
||||
// poll body of the watchdog thread in src/program/generate.cpp (the lines marked below) driven by an
|
||||
// injected clock instead of sleep_for(1 s).
|
||||
// Output: tests/fixtures/host_oracle.json (stride + watchdog scenarios). Usage: gen_host_fixtures OUT.json
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "strata/core/progress.hpp"
|
||||
#include "strata/program/logits_selection.hpp"
|
||||
|
||||
namespace ls = strata::program::logits_selection;
|
||||
|
||||
static std::string esc(const std::string& s) {
|
||||
std::string o;
|
||||
for (char c : s) {
|
||||
if (c == '"' || c == '\\') o += '\\';
|
||||
o += c;
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
// ---- the watchdog thread of generate.cpp, with the clock and the counters passed in --------------------------
|
||||
struct Dog {
|
||||
int limit;
|
||||
uint64_t last;
|
||||
uint64_t ticks_at;
|
||||
int64_t since_ms;
|
||||
Dog(int limit_s, int64_t now_ms, uint64_t beats, uint64_t ticks)
|
||||
: limit(limit_s), last(beats), ticks_at(ticks), since_ms(now_ms) {}
|
||||
// Returns -1 healthy, otherwise the "layers served since the last finished step" the report prints.
|
||||
// The statements below are generate.cpp's loop body (lines "const uint64_t b = ..." to "std::abort()").
|
||||
int64_t poll(int64_t now_ms, uint64_t beats, bool busy, uint64_t ticks) {
|
||||
if (limit <= 0) return -1; // `if (limit > 0) std::thread(...)`: no thread at all
|
||||
const uint64_t b = beats;
|
||||
if (!busy || b != last) { last = b; ticks_at = ticks; since_ms = now_ms; return -1; }
|
||||
if (now_ms - since_ms < (int64_t) limit * 1000) return -1;
|
||||
return (int64_t) (ticks - ticks_at); // stall_report(stderr, p.ticks.load() - ticks_at); abort
|
||||
}
|
||||
};
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc < 2) return 2;
|
||||
std::FILE* f = std::fopen(argv[1], "w");
|
||||
if (!f) return 2;
|
||||
std::fprintf(f, "{\n \"source\": \"include/strata/program/logits_selection.hpp + core/progress.hpp + the watchdog thread of src/program/generate.cpp (host build)\",\n");
|
||||
|
||||
// ---- stride
|
||||
std::fprintf(f, " \"parse\": [");
|
||||
const char* texts[] = {"1", "2", "128", "9223372036854775807", "9223372036854775808", "0", "00", "007", "-1", "+1",
|
||||
" 1", "1 ", "1x", "x", "", "1.5", "99999999999999999999", "12345678901234567890"};
|
||||
bool first = true;
|
||||
for (const char* t : texts) {
|
||||
int64_t v = -777;
|
||||
const bool ok = ls::parse_stride(t, v);
|
||||
std::fprintf(f, "%s\n {\"text\": \"%s\", \"ok\": %s, \"value\": %lld}", first ? "" : ",", esc(t).c_str(), ok ? "true" : "false",
|
||||
(long long) (ok ? v : -777));
|
||||
first = false;
|
||||
}
|
||||
std::fprintf(f, "\n ],\n \"selected\": [");
|
||||
first = true;
|
||||
const int64_t totals[] = {-1, 0, 1, 2, 5, 9, 10, 11, 64, 100};
|
||||
const int64_t strides[] = {-1, 0, 1, 2, 3, 4, 7, 10, 64, 1000};
|
||||
for (int64_t total : totals)
|
||||
for (int64_t stride : strides) {
|
||||
std::fprintf(f, "%s\n {\"total\": %lld, \"stride\": %lld, \"rows\": %lld, \"kept\": [", first ? "" : ",", (long long) total,
|
||||
(long long) stride, (long long) ls::row_count(total, stride));
|
||||
bool kf = true;
|
||||
for (int64_t p = -2; p < total + 2; ++p)
|
||||
if (ls::selected(p, total, stride)) {
|
||||
std::fprintf(f, "%s%lld", kf ? "" : ",", (long long) p);
|
||||
kf = false;
|
||||
}
|
||||
std::fprintf(f, "]}");
|
||||
first = false;
|
||||
}
|
||||
std::fprintf(f, "\n ],\n");
|
||||
|
||||
// ---- watchdog scenarios: [limit_s, [[dt_ms, beats, busy, ticks], ...]] -> verdicts
|
||||
struct Step { int64_t at_ms; uint64_t beats; bool busy; uint64_t ticks; };
|
||||
struct Scenario { int limit; std::vector<Step> steps; };
|
||||
std::vector<Scenario> sc = {
|
||||
{3, {{1000, 0, true, 0}, {2000, 0, true, 5}, {2999, 0, true, 9}, {3000, 0, true, 9}, {4000, 0, true, 9}}},
|
||||
{2, {{1900, 1, true, 40}, {3800, 1, true, 40}, {3900, 1, true, 40}, {4000, 2, true, 41}, {5999, 2, true, 41}, {6000, 2, true, 80}}},
|
||||
{2, {{1000, 0, false, 1}, {2000, 0, false, 2}, {3000, 0, false, 3}, {100000, 0, true, 100}, {101999, 0, true, 100}, {102000, 0, true, 100}}},
|
||||
{0, {{1000, 0, true, 0}, {10000000, 0, true, 0}}},
|
||||
{-5, {{1000, 0, true, 0}, {10000000, 0, true, 0}}},
|
||||
{1, {{1000, 0, true, 3}, {2000, 0, true, 3}, {3000, 1, true, 3}, {3999, 1, true, 7}, {4000, 1, true, 7}}},
|
||||
{60, {{59000, 0, true, 0}, {59999, 0, true, 0}, {60000, 0, true, 12}, {61000, 5, false, 12}, {200000, 5, true, 12}}},
|
||||
};
|
||||
std::fprintf(f, " \"watchdog\": [");
|
||||
first = true;
|
||||
for (const Scenario& s : sc) {
|
||||
Dog dog(s.limit, 0, 0, 0);
|
||||
std::fprintf(f, "%s\n {\"limit_s\": %d, \"steps\": [", first ? "" : ",", s.limit);
|
||||
bool sf = true;
|
||||
for (const Step& st : s.steps) {
|
||||
const int64_t v = dog.poll(st.at_ms, st.beats, st.busy, st.ticks);
|
||||
std::fprintf(f, "%s\n {\"at_ms\": %lld, \"beats\": %llu, \"busy\": %s, \"ticks\": %llu, \"layers_since\": %lld}", sf ? "" : ",",
|
||||
(long long) st.at_ms, (unsigned long long) st.beats, st.busy ? "true" : "false", (unsigned long long) st.ticks,
|
||||
(long long) v);
|
||||
sf = false;
|
||||
}
|
||||
std::fprintf(f, "\n ]}");
|
||||
first = false;
|
||||
}
|
||||
std::fprintf(f, "\n ]\n}\n");
|
||||
std::fclose(f);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
// Host oracle for the image-embeddings path of `--serve` (GENI): the SVE1 record reader and the M-RoPE
|
||||
// position table of src/program/generate.cpp.
|
||||
//
|
||||
// The block between "if (geni || !mrope_identity) {" and "tr(\"positions built\"" is INCLUDED VERBATIM from the
|
||||
// pinned generate.cpp (extracted by build_oracle.sh, see generate_block.inc) - not retyped - and so is `fnv1a`.
|
||||
// Everything around it (the variables the block reads, a CUDA-free `put` target) is declared here.
|
||||
//
|
||||
// Usage: gen_vision_fixtures OUT.json (writes its scratch embedding files to $TMPDIR)
|
||||
#include <unistd.h>
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "strata/core/conversation_cache.hpp"
|
||||
|
||||
using ImgKey = strata::core::ConversationImageKey;
|
||||
|
||||
#include "fnv1a.inc"
|
||||
|
||||
struct Geometry { int64_t n_embd; };
|
||||
|
||||
struct Result {
|
||||
std::string ve;
|
||||
std::vector<int32_t> table;
|
||||
std::vector<int64_t> row_offset; // float offset into img_rows per token, -1 = none
|
||||
std::vector<ImgKey> imgs;
|
||||
};
|
||||
|
||||
constexpr int64_t kImagePad = 248056;
|
||||
|
||||
static Result run(bool geni, const std::vector<int64_t>& ids, const std::string& emb_path, int64_t n_embd, int64_t cells,
|
||||
bool mrope_identity) {
|
||||
Geometry g{n_embd};
|
||||
const int64_t n = (int64_t) ids.size();
|
||||
std::vector<ImgKey> req_imgs;
|
||||
std::vector<int32_t> mrope_host((size_t) cells * 3);
|
||||
for (int64_t c = 0; c < cells; ++c) mrope_host[(size_t) c * 3] = mrope_host[(size_t) c * 3 + 1] = mrope_host[(size_t) c * 3 + 2] = (int32_t) c;
|
||||
std::vector<float> img_rows;
|
||||
std::vector<const float*> row_ptr;
|
||||
Result out;
|
||||
{
|
||||
// ---------------------------------------------------------------- verbatim from generate.cpp
|
||||
#include "generate_block.inc"
|
||||
out.ve = ve;
|
||||
} // closes the `if (geni || !mrope_identity) {` that the block opens
|
||||
}
|
||||
out.table = mrope_host;
|
||||
out.imgs = req_imgs;
|
||||
for (const float* p : row_ptr) out.row_offset.push_back(p ? (int64_t) (p - img_rows.data()) : -1);
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- SVE1 file builders ---------------------------------------------------------------------------------------
|
||||
static void put_i32(std::string& s, int32_t v) { s.append((const char*) &v, 4); }
|
||||
static std::string image(int32_t n, int32_t nx, int32_t ny, int32_t width, float seed, int32_t magic = 0x31455653) {
|
||||
std::string s;
|
||||
for (int32_t v : {magic, n, nx, ny, width}) put_i32(s, v);
|
||||
for (int32_t i = 0; i < n * width; ++i) {
|
||||
const float f = seed + (float) i * 0.5f;
|
||||
s.append((const char*) &f, 4);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
static std::string hex(const std::string& s) {
|
||||
static const char* d = "0123456789abcdef";
|
||||
std::string o;
|
||||
for (unsigned char c : s) { o += d[c >> 4]; o += d[c & 15]; }
|
||||
return o;
|
||||
}
|
||||
|
||||
static std::string jstr(const std::string& s) {
|
||||
std::string o = "\"";
|
||||
for (char c : s) { if (c == '"' || c == '\\') o += '\\'; o += c; }
|
||||
return o + "\"";
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc < 2) return 2;
|
||||
const char* tmp = std::getenv("TMPDIR");
|
||||
const std::string scratch = std::string(tmp ? tmp : "/tmp") + "/strata_sve_oracle_" + std::to_string((long long) getpid()) + ".sve";
|
||||
std::FILE* f = std::fopen(argv[1], "w");
|
||||
if (!f) return 2;
|
||||
std::fprintf(f, "{\n \"source\": \"src/program/generate.cpp GENI embeddings block + fnv1a (verbatim, host build)\",\n \"cases\": [");
|
||||
|
||||
struct Case { const char* name; bool geni; std::vector<int64_t> ids; std::string file; int64_t n_embd; int64_t cells; bool identity; };
|
||||
const int64_t P = kImagePad;
|
||||
const std::string i1 = image(1, 1, 1, 4, 1.0f), i6 = image(6, 3, 2, 4, 10.0f), i8 = image(8, 2, 4, 4, 20.0f), i25 = image(25, 5, 5, 4, 30.0f);
|
||||
std::vector<Case> cases = {
|
||||
{"text identity after an image request", false, {5, 6, 7}, "", 4, 32, false},
|
||||
{"text only with no file", true, {5, 6, 7, 8}, "", 4, 32, true},
|
||||
{"one 1x1 image", true, {1, 2, P, 3, 4}, i1, 4, 32, true},
|
||||
{"one 3x2 image", true, {1, P, P, P, P, P, P, 9, 10}, i6, 4, 40, true},
|
||||
{"one 2x4 image (tall: ny > nx)", true, {7, P, P, P, P, P, P, P, P, 8}, i8, 4, 40, true},
|
||||
{"two images in order", true, {1, P, P, P, P, P, P, 2, P, P, P, P, P, P, P, P, 3}, i6 + i8, 4, 64, true},
|
||||
{"5x5 image then text", true, {1, 2, 3, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, 4, 5}, i25, 4, 64, true},
|
||||
{"adjacent images", true, {P, P, P, P, P, P, P, P, P, P, P, P, P, P, 1}, i6 + i8, 4, 40, true},
|
||||
{"image at the start", true, {P, 4}, i1, 4, 16, true},
|
||||
{"identity request after (not geni, not identity)", false, {1, 2}, "", 4, 16, false},
|
||||
// errors
|
||||
{"prompt ends in an image", true, {1, P, P, P, P, P, P}, i6, 4, 32, true},
|
||||
{"more images in the prompt than the file", true, {1, P, 2, P, 3}, i1, 4, 32, true},
|
||||
{"more images in the file than the prompt", true, {1, P, 2, 3}, i1 + i1, 4, 32, true},
|
||||
{"fewer image_pad tokens than rows", true, {1, P, P, 2, 3, 4, 5, 6, 7}, i6, 4, 32, true},
|
||||
{"bad magic", true, {1, P, 2}, image(1, 1, 1, 4, 1.0f, 0x12345678), 4, 32, true},
|
||||
{"wrong width", true, {1, P, 2}, image(1, 1, 1, 8, 1.0f), 4, 32, true},
|
||||
{"grid does not multiply", true, {1, P, 2}, image(6, 3, 3, 4, 1.0f), 4, 32, true},
|
||||
{"zero rows", true, {1, P, 2}, image(0, 0, 0, 4, 1.0f), 4, 32, true},
|
||||
{"short header", true, {1, P, 2}, i1.substr(0, 12), 4, 32, true},
|
||||
{"short data", true, {1, P, 2}, i1.substr(0, i1.size() - 3), 4, 32, true},
|
||||
{"second record truncated", true, {1, P, 2, P, 3}, i1 + i1.substr(0, 25), 4, 32, true},
|
||||
};
|
||||
bool first = true;
|
||||
for (const Case& c : cases) {
|
||||
if (!c.file.empty() || c.geni) {
|
||||
std::FILE* w = std::fopen(scratch.c_str(), "wb");
|
||||
std::fwrite(c.file.data(), 1, c.file.size(), w);
|
||||
std::fclose(w);
|
||||
}
|
||||
// "no file": point at a path that does not exist
|
||||
const std::string path = c.file.empty() && c.geni ? std::string("/nonexistent/embeddings.sve") : scratch;
|
||||
const Result r = run(c.geni, c.ids, path, c.n_embd, c.cells, c.identity);
|
||||
std::fprintf(f, "%s\n {\"name\": %s, \"geni\": %s, \"mrope_identity\": %s, \"n_embd\": %lld, \"cells\": %lld, \"file_hex\": \"%s\", \"ids\": [",
|
||||
first ? "" : ",", jstr(c.name).c_str(), c.geni ? "true" : "false", c.identity ? "true" : "false",
|
||||
(long long) c.n_embd, (long long) c.cells, hex(c.file).c_str());
|
||||
for (size_t i = 0; i < c.ids.size(); ++i) std::fprintf(f, "%s%lld", i ? "," : "", (long long) c.ids[i]);
|
||||
std::fprintf(f, "], \"ve\": %s, \"table\": [", jstr(r.ve).c_str());
|
||||
for (size_t i = 0; i < r.table.size(); ++i) std::fprintf(f, "%s%d", i ? "," : "", r.table[i]);
|
||||
std::fprintf(f, "], \"row_offset\": [");
|
||||
for (size_t i = 0; i < r.row_offset.size(); ++i) std::fprintf(f, "%s%lld", i ? "," : "", (long long) r.row_offset[i]);
|
||||
std::fprintf(f, "], \"imgs\": [");
|
||||
for (size_t i = 0; i < r.imgs.size(); ++i)
|
||||
std::fprintf(f, "%s[%lld,\"%016llx\"]", i ? "," : "", (long long) r.imgs[i].start, (unsigned long long) r.imgs[i].hash);
|
||||
std::fprintf(f, "]}");
|
||||
first = false;
|
||||
}
|
||||
std::remove(scratch.c_str());
|
||||
std::fprintf(f, "\n ]\n}\n");
|
||||
std::fclose(f);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
//! CORS and the "own page" guard (issue #321 of the Original): `Handler._cors`, `do_OPTIONS`,
|
||||
//! `Handler._own_page` and `origins_of` in `serve/server.py`.
|
||||
//!
|
||||
//! * `cors_origins`: browser pages of these origins may call `/v1/*` (`"*"` = any page, only
|
||||
//! sensible with an API key). Empty = no CORS headers at all.
|
||||
//! * `trusted_origins`: origins that count as Strata's own page for `/settings`, `/v1/load` and
|
||||
//! MCP tools (the web app behind a reverse proxy); never a wildcard.
|
||||
//! * Only JSON from an origin equal to the server's own `Host`, or a trusted one, may change
|
||||
//! settings or load/unload the model: a form post or a "simple" cross-site request cannot send
|
||||
//! JSON without a CORS preflight, which this server never grants for those paths.
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::shared::py_str_repr;
|
||||
|
||||
/// The allow-headers answer when the preflight asks for nothing specific.
|
||||
pub const DEFAULT_ALLOW_HEADERS: &str =
|
||||
"Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta";
|
||||
|
||||
/// `origins_of`: a config's origin list (`"https://chat.example.com"` or a list of them),
|
||||
/// `scheme://host[:port]` without a path; `"*"` only where `wildcard` allows it. `Err` is the
|
||||
/// message that stops the start.
|
||||
pub fn origins_of(value: &Value, key: &str, wildcard: bool) -> Result<Vec<String>, String> {
|
||||
let items: Vec<&Value> = match value {
|
||||
Value::Null => return Ok(Vec::new()),
|
||||
Value::String(s) if s.is_empty() => return Ok(Vec::new()),
|
||||
Value::Array(a) if a.is_empty() => return Ok(Vec::new()),
|
||||
Value::String(_) => vec![value],
|
||||
Value::Array(a) => a.iter().collect(),
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"[strata] {key}: expected an origin or a list of origins"
|
||||
));
|
||||
}
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for item in items {
|
||||
let Some(text) = item.as_str() else {
|
||||
return Err(format!(
|
||||
"[strata] {key}: expected an origin or a list of origins"
|
||||
));
|
||||
};
|
||||
let origin = text.trim().trim_end_matches('/');
|
||||
if origin == "*" && wildcard {
|
||||
out.push(origin.to_owned());
|
||||
continue;
|
||||
}
|
||||
let valid = origin.split_once("://").is_some_and(|(scheme, rest)| {
|
||||
matches!(scheme, "http" | "https")
|
||||
&& !rest.is_empty()
|
||||
&& !rest.contains('/')
|
||||
&& !rest.contains('*')
|
||||
});
|
||||
if !valid {
|
||||
return Err(format!(
|
||||
"[strata] {key}: {} is not an origin like https://chat.example.com{}",
|
||||
py_str_repr(origin),
|
||||
if wildcard { "" } else { " (no wildcards here)" }
|
||||
));
|
||||
}
|
||||
out.push(origin.to_owned());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The origins allowed to call `/v1/*` from a browser.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Cors {
|
||||
origins: Vec<String>,
|
||||
}
|
||||
|
||||
impl Cors {
|
||||
pub fn new(origins: Vec<String>) -> Self {
|
||||
Self { origins }
|
||||
}
|
||||
|
||||
pub fn is_enabled(&self) -> bool {
|
||||
!self.origins.is_empty()
|
||||
}
|
||||
|
||||
pub fn origins(&self) -> &[String] {
|
||||
&self.origins
|
||||
}
|
||||
|
||||
/// The response headers for `request_path` (query string allowed) when the page at `origin`
|
||||
/// asks; empty when CORS does not apply. `asked_headers` is the preflight's
|
||||
/// `Access-Control-Request-Headers`.
|
||||
pub fn headers(
|
||||
&self,
|
||||
request_path: &str,
|
||||
origin: Option<&str>,
|
||||
asked_headers: Option<&str>,
|
||||
) -> Vec<(&'static str, String)> {
|
||||
let path = request_path.split('?').next().unwrap_or("");
|
||||
if self.origins.is_empty() || !path.starts_with("/v1/") {
|
||||
return Vec::new();
|
||||
}
|
||||
let origin = origin.unwrap_or("").trim_end_matches('/');
|
||||
let mut out = Vec::new();
|
||||
let allow = if self.origins.iter().any(|o| o == "*") {
|
||||
"*".to_owned()
|
||||
} else if !origin.is_empty() && self.origins.iter().any(|o| o == origin) {
|
||||
out.push(("Vary", "Origin".to_owned()));
|
||||
origin.to_owned()
|
||||
} else {
|
||||
return Vec::new();
|
||||
};
|
||||
out.push(("Access-Control-Allow-Origin", allow));
|
||||
out.push((
|
||||
"Access-Control-Allow-Methods",
|
||||
"GET, POST, OPTIONS".to_owned(),
|
||||
));
|
||||
// "*" does not cover Authorization, so echo what the preflight asked for.
|
||||
out.push((
|
||||
"Access-Control-Allow-Headers",
|
||||
match asked_headers {
|
||||
Some(asked) if !asked.is_empty() => asked.to_owned(),
|
||||
_ => DEFAULT_ALLOW_HEADERS.to_owned(),
|
||||
},
|
||||
));
|
||||
out.push(("Access-Control-Max-Age", "600".to_owned()));
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a request was refused by the own-page guard.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum OwnPageError {
|
||||
/// 415 `send application/json`.
|
||||
NotJson,
|
||||
/// 403, with the action in the message.
|
||||
ForeignOrigin(String),
|
||||
}
|
||||
|
||||
impl OwnPageError {
|
||||
pub fn status(&self) -> u16 {
|
||||
match self {
|
||||
Self::NotJson => 415,
|
||||
Self::ForeignOrigin(_) => 403,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn message(&self) -> String {
|
||||
match self {
|
||||
Self::NotJson => "send application/json".to_owned(),
|
||||
Self::ForeignOrigin(what) => format!(
|
||||
"{what} only from Strata's own page (or an origin in the config's trusted_origins)"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `Handler._own_page(what)`: JSON only, and no foreign `Origin`. The origin must be this server's
|
||||
/// own address (the `Host` header) or an origin the config trusts. Proxy headers
|
||||
/// (`X-Forwarded-*`, `CF-*`) prove nothing about the page that sent the request, so they open
|
||||
/// nothing.
|
||||
pub fn own_page(
|
||||
what: &str,
|
||||
content_type: Option<&str>,
|
||||
origin: Option<&str>,
|
||||
host: Option<&str>,
|
||||
trusted_origins: &[String],
|
||||
) -> Result<(), OwnPageError> {
|
||||
if !content_type.unwrap_or("").starts_with("application/json") {
|
||||
return Err(OwnPageError::NotJson);
|
||||
}
|
||||
let origin = origin.unwrap_or("").trim_end_matches('/');
|
||||
if !origin.is_empty() {
|
||||
let authority = origin.split_once("://").map_or(origin, |(_, rest)| rest);
|
||||
if authority != host.unwrap_or("") && !trusted_origins.iter().any(|o| o == origin) {
|
||||
return Err(OwnPageError::ForeignOrigin(what.to_owned()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn origin_lists_follow_the_originals_grammar() {
|
||||
assert_eq!(origins_of(&json!(null), "k", true), Ok(vec![]));
|
||||
assert_eq!(origins_of(&json!(""), "k", true), Ok(vec![]));
|
||||
assert_eq!(origins_of(&json!([]), "k", true), Ok(vec![]));
|
||||
assert_eq!(
|
||||
origins_of(&json!("https://a.example/"), "k", false),
|
||||
Ok(vec!["https://a.example".into()])
|
||||
);
|
||||
assert_eq!(
|
||||
origins_of(&json!([" http://localhost:3000 ", "*"]), "k", true),
|
||||
Ok(vec!["http://localhost:3000".into(), "*".into()])
|
||||
);
|
||||
for bad in [
|
||||
json!("ftp://x"),
|
||||
json!("https://a.example/path"),
|
||||
json!("https://*.example"),
|
||||
json!("example.com"),
|
||||
json!("https://"),
|
||||
json!(5),
|
||||
json!([1]),
|
||||
json!({"a": 1}),
|
||||
] {
|
||||
assert!(origins_of(&bad, "k", true).is_err(), "{bad}");
|
||||
}
|
||||
assert!(
|
||||
origins_of(&json!("*"), "trusted_origins", false)
|
||||
.unwrap_err()
|
||||
.ends_with("(no wildcards here)")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cors_headers_only_for_listed_origins_on_v1_paths() {
|
||||
let cors = Cors::new(vec!["https://a.example".into()]);
|
||||
assert!(
|
||||
cors.headers("/health", Some("https://a.example"), None)
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
cors.headers("/v1", Some("https://a.example"), None)
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
cors.headers("/v1/models", Some("https://b.example"), None)
|
||||
.is_empty()
|
||||
);
|
||||
assert!(cors.headers("/v1/models", None, None).is_empty());
|
||||
let headers = cors.headers("/v1/models?x=1", Some("https://a.example/"), Some("x-foo"));
|
||||
assert_eq!(headers[0], ("Vary", "Origin".into()));
|
||||
assert!(headers.contains(&("Access-Control-Allow-Origin", "https://a.example".into())));
|
||||
assert!(headers.contains(&("Access-Control-Allow-Headers", "x-foo".into())));
|
||||
let any = Cors::new(vec!["*".into()]);
|
||||
let headers = any.headers("/v1/chat/completions", None, None);
|
||||
assert!(headers.contains(&("Access-Control-Allow-Origin", "*".into())));
|
||||
assert!(headers.contains(&("Access-Control-Allow-Headers", DEFAULT_ALLOW_HEADERS.into())));
|
||||
assert!(!headers.iter().any(|(name, _)| *name == "Vary"));
|
||||
assert!(
|
||||
Cors::default()
|
||||
.headers("/v1/models", Some("https://a.example"), None)
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn own_page_requires_json_and_a_local_or_trusted_origin() {
|
||||
let trusted = vec!["https://strata.example.com".to_owned()];
|
||||
let ok = |ct, origin, host| own_page("x", ct, origin, host, &trusted);
|
||||
assert_eq!(
|
||||
ok(Some("application/json"), None, Some("localhost:8080")),
|
||||
Ok(())
|
||||
);
|
||||
assert_eq!(
|
||||
ok(
|
||||
Some("application/json; charset=utf-8"),
|
||||
Some("http://localhost:8080"),
|
||||
Some("localhost:8080")
|
||||
),
|
||||
Ok(())
|
||||
);
|
||||
assert_eq!(
|
||||
ok(
|
||||
Some("application/json"),
|
||||
Some("https://strata.example.com/"),
|
||||
Some("localhost:8080")
|
||||
),
|
||||
Ok(())
|
||||
);
|
||||
assert_eq!(
|
||||
ok(Some("text/plain"), None, None),
|
||||
Err(OwnPageError::NotJson)
|
||||
);
|
||||
assert_eq!(ok(None, None, None), Err(OwnPageError::NotJson));
|
||||
let foreign = ok(
|
||||
Some("application/json"),
|
||||
Some("https://evil.example"),
|
||||
Some("localhost:8080"),
|
||||
);
|
||||
assert_eq!(foreign.as_ref().unwrap_err().status(), 403);
|
||||
assert_eq!(
|
||||
foreign.unwrap_err().message(),
|
||||
"x only from Strata's own page (or an origin in the config's trusted_origins)"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,571 @@
|
||||
//! Control vectors (`include/strata/kernels/cvec.hpp`, `load_control_vectors` in
|
||||
//! `src/program/generate.cpp`): a steering direction added to, or projected out of, the residual
|
||||
//! stream after chosen layers, loaded from llama.cpp control-vector GGUF files.
|
||||
//!
|
||||
//! This is the host side: reading the files and building the `dir` / `s` tables the kernel
|
||||
//! uploads. The tables are bit-exact against the Original's loader (golden fixture compiled from
|
||||
//! the verbatim function, `oracle/gen_cvec_fixtures.cpp`). The device side
|
||||
//! (`h <- h + d` / `h <- h - s (h.v) v`) is a kernel and stays with the engine.
|
||||
//!
|
||||
//! * `add`: `d_l` = sum over files of `scale * direction.<l>`; the table row is `d_l`, `s_l = 1`.
|
||||
//! * `project`: `v_l = d_l / |d_l|`, `s_l = |d_l|` (norm in `f64`).
|
||||
//! * layer 0 has no direction; `direction.<l>` with `l >= n_layers` is ignored (as in llama.cpp).
|
||||
//! * `single:L` (project mode only) uses layer `L`'s direction at every steered layer.
|
||||
|
||||
/// The tensor facts the loader needs.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct VectorTensor {
|
||||
pub name: String,
|
||||
/// ggml type id (0 = F32).
|
||||
pub kind: u32,
|
||||
pub elements: u64,
|
||||
/// Present for F32 tensors.
|
||||
pub values: Vec<f32>,
|
||||
}
|
||||
|
||||
/// A parsed control-vector GGUF.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct VectorFile {
|
||||
pub architecture: Option<String>,
|
||||
pub model_hint: Option<String>,
|
||||
pub tensors: Vec<VectorTensor>,
|
||||
}
|
||||
|
||||
struct Cursor<'a> {
|
||||
bytes: &'a [u8],
|
||||
at: usize,
|
||||
}
|
||||
|
||||
impl<'a> Cursor<'a> {
|
||||
fn take(&mut self, n: usize) -> Result<&'a [u8], String> {
|
||||
let end = self
|
||||
.at
|
||||
.checked_add(n)
|
||||
.filter(|end| *end <= self.bytes.len())
|
||||
.ok_or("GGUF file is truncated")?;
|
||||
let slice = &self.bytes[self.at..end];
|
||||
self.at = end;
|
||||
Ok(slice)
|
||||
}
|
||||
|
||||
fn u32(&mut self) -> Result<u32, String> {
|
||||
Ok(u32::from_le_bytes(
|
||||
self.take(4)?.try_into().expect("4 bytes"),
|
||||
))
|
||||
}
|
||||
|
||||
fn u64(&mut self) -> Result<u64, String> {
|
||||
Ok(u64::from_le_bytes(
|
||||
self.take(8)?.try_into().expect("8 bytes"),
|
||||
))
|
||||
}
|
||||
|
||||
fn string(&mut self) -> Result<String, String> {
|
||||
let len = usize::try_from(self.u64()?).map_err(|_| "GGUF string is too long")?;
|
||||
if len > 1 << 24 {
|
||||
return Err("GGUF string is too long".into());
|
||||
}
|
||||
Ok(String::from_utf8_lossy(self.take(len)?).into_owned())
|
||||
}
|
||||
}
|
||||
|
||||
/// Skip (or read, for strings) one metadata value of type `kind`.
|
||||
fn value(cursor: &mut Cursor<'_>, kind: u32) -> Result<Option<String>, String> {
|
||||
let fixed = |bytes: usize, cursor: &mut Cursor<'_>| cursor.take(bytes).map(|_| None);
|
||||
match kind {
|
||||
0 | 1 | 7 => fixed(1, cursor),
|
||||
2 | 3 => fixed(2, cursor),
|
||||
4..=6 => fixed(4, cursor),
|
||||
10..=12 => fixed(8, cursor),
|
||||
8 => cursor.string().map(Some),
|
||||
9 => {
|
||||
let element = cursor.u32()?;
|
||||
let count = cursor.u64()?;
|
||||
if count > 1 << 28 {
|
||||
return Err("GGUF array is too long".into());
|
||||
}
|
||||
for _ in 0..count {
|
||||
value(cursor, element)?;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
other => Err(format!("unknown GGUF metadata type {other}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a GGUF v2/v3 file held in memory (little endian).
|
||||
pub fn parse_gguf(bytes: &[u8]) -> Result<VectorFile, String> {
|
||||
let mut cursor = Cursor { bytes, at: 0 };
|
||||
if cursor.take(4)? != b"GGUF" {
|
||||
return Err("not a GGUF file".into());
|
||||
}
|
||||
let version = cursor.u32()?;
|
||||
if !(2..=3).contains(&version) {
|
||||
return Err(format!("unsupported GGUF version {version}"));
|
||||
}
|
||||
let tensors = cursor.u64()?;
|
||||
let entries = cursor.u64()?;
|
||||
if tensors > 1 << 20 || entries > 1 << 20 {
|
||||
return Err("GGUF header counts are implausible".into());
|
||||
}
|
||||
let mut file = VectorFile::default();
|
||||
let mut alignment = 32u64;
|
||||
for _ in 0..entries {
|
||||
let key = cursor.string()?;
|
||||
let kind = cursor.u32()?;
|
||||
if key == "general.alignment" && kind == 4 {
|
||||
alignment = u64::from(cursor.u32()?).max(1);
|
||||
continue;
|
||||
}
|
||||
let text = value(&mut cursor, kind)?;
|
||||
match key.as_str() {
|
||||
"general.architecture" => file.architecture = text,
|
||||
"controlvector.model_hint" => file.model_hint = text,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
struct Info {
|
||||
name: String,
|
||||
kind: u32,
|
||||
elements: u64,
|
||||
offset: u64,
|
||||
}
|
||||
let mut infos = Vec::new();
|
||||
for _ in 0..tensors {
|
||||
let name = cursor.string()?;
|
||||
let dims = cursor.u32()?;
|
||||
if dims > 8 {
|
||||
return Err("GGUF tensor has too many dimensions".into());
|
||||
}
|
||||
let mut elements = 1u64;
|
||||
for _ in 0..dims {
|
||||
elements = elements
|
||||
.checked_mul(cursor.u64()?)
|
||||
.ok_or("GGUF tensor is too large")?;
|
||||
}
|
||||
let kind = cursor.u32()?;
|
||||
let offset = cursor.u64()?;
|
||||
infos.push(Info {
|
||||
name,
|
||||
kind,
|
||||
elements,
|
||||
offset,
|
||||
});
|
||||
}
|
||||
let data_start = (cursor.at as u64).div_ceil(alignment) * alignment;
|
||||
for info in infos {
|
||||
let mut values = Vec::new();
|
||||
if info.kind == 0 {
|
||||
let begin = data_start
|
||||
.checked_add(info.offset)
|
||||
.ok_or("GGUF tensor offset overflows")?;
|
||||
let len = info
|
||||
.elements
|
||||
.checked_mul(4)
|
||||
.ok_or("GGUF tensor is too large")?;
|
||||
let end = begin
|
||||
.checked_add(len)
|
||||
.ok_or("GGUF tensor offset overflows")?;
|
||||
let data = usize::try_from(begin)
|
||||
.ok()
|
||||
.zip(usize::try_from(end).ok())
|
||||
.and_then(|(b, e)| bytes.get(b..e))
|
||||
.ok_or("GGUF tensor data is truncated")?;
|
||||
values = data
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|c| f32::from_le_bytes(*c))
|
||||
.collect();
|
||||
}
|
||||
file.tensors.push(VectorTensor {
|
||||
name: info.name,
|
||||
kind: info.kind,
|
||||
elements: info.elements,
|
||||
values,
|
||||
});
|
||||
}
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Mode {
|
||||
Project,
|
||||
Add,
|
||||
}
|
||||
|
||||
/// The loader's options (`--cvec-mode`, `--cvec-dir`, `--control-vector-layer-range`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Options {
|
||||
/// `<= 0`: layer 1 (layer 0 has no direction).
|
||||
pub first: i32,
|
||||
/// `<= 0` or `>= n_layers`: the last layer.
|
||||
pub last: i32,
|
||||
pub mode: Mode,
|
||||
/// `single:L` (project mode): layer L's direction at every steered layer; `-1` = per layer.
|
||||
pub single: i32,
|
||||
}
|
||||
|
||||
impl Default for Options {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
first: -1,
|
||||
last: -1,
|
||||
mode: Mode::Add,
|
||||
single: -1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the kernel uploads.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Tables {
|
||||
/// `n_layers * n_embd`: project = the unit `v_l`, add = `d_l`; zero rows elsewhere.
|
||||
pub dir: Vec<f32>,
|
||||
/// `n_layers`: project = `s_l`, add = 1, 0 = the layer is not steered.
|
||||
pub s: Vec<f32>,
|
||||
pub mode: Mode,
|
||||
pub first: i32,
|
||||
pub last: i32,
|
||||
pub steered: usize,
|
||||
/// What `INFO` reports: `project:1-47`, `add:2-3`, `project:1-47:single12`.
|
||||
pub summary: String,
|
||||
/// Non-fatal remarks (a vector made for another model).
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// C `strtol(s, nullptr, 10)`: whitespace, sign, digits; no digits is 0.
|
||||
fn strtol(text: &str) -> i64 {
|
||||
let trimmed = text.trim_start();
|
||||
let (negative, digits) = match trimmed.as_bytes().first() {
|
||||
Some(b'-') => (true, &trimmed[1..]),
|
||||
Some(b'+') => (false, &trimmed[1..]),
|
||||
_ => (false, trimmed),
|
||||
};
|
||||
let mut value: i64 = 0;
|
||||
for byte in digits.bytes().take_while(u8::is_ascii_digit) {
|
||||
value = value
|
||||
.saturating_mul(10)
|
||||
.saturating_add(i64::from(byte - b'0'));
|
||||
}
|
||||
if negative { -value } else { value }
|
||||
}
|
||||
|
||||
/// `load_control_vectors`: `files` are `(label for messages, parsed file, scale)`.
|
||||
pub fn build_tables(
|
||||
files: &[(String, VectorFile, f32)],
|
||||
n_layers: usize,
|
||||
n_embd: usize,
|
||||
options: Options,
|
||||
) -> Result<Tables, String> {
|
||||
let (layers, width) = (n_layers as i64, n_embd as i64);
|
||||
let mut data = vec![0.0f32; n_layers * n_embd];
|
||||
let mut have = vec![false; n_layers];
|
||||
let mut warnings = Vec::new();
|
||||
for (label, file, scale) in files {
|
||||
if file.architecture.as_deref() != Some("controlvector") {
|
||||
return Err(format!(
|
||||
"{label}: not a control vector GGUF (general.architecture is not 'controlvector')"
|
||||
));
|
||||
}
|
||||
if let Some(hint) = file.model_hint.as_deref()
|
||||
&& hint != "qwen4exp"
|
||||
{
|
||||
warnings.push(format!("{label} was made for '{hint}', not qwen4exp"));
|
||||
}
|
||||
let mut found = 0;
|
||||
for tensor in &file.tensors {
|
||||
let Some(rest) = tensor.name.strip_prefix("direction.") else {
|
||||
continue;
|
||||
};
|
||||
let layer = strtol(rest);
|
||||
if layer < 1 || layer >= layers {
|
||||
continue; // layer 0 has no vector; past the model is ignored, as in llama.cpp
|
||||
}
|
||||
if tensor.kind != 0 || tensor.elements != n_embd as u64 {
|
||||
return Err(format!("{label}: {} must be {width} f32", tensor.name));
|
||||
}
|
||||
let row = &mut data[layer as usize * n_embd..(layer as usize + 1) * n_embd];
|
||||
for (target, source) in row.iter_mut().zip(&tensor.values) {
|
||||
*target += scale * source;
|
||||
}
|
||||
have[layer as usize] = true;
|
||||
found += 1;
|
||||
}
|
||||
if found == 0 {
|
||||
return Err(format!("{label}: no direction.<layer> tensors"));
|
||||
}
|
||||
}
|
||||
let first = if options.first <= 0 { 1 } else { options.first };
|
||||
let last = if options.last <= 0 || i64::from(options.last) >= layers {
|
||||
(layers - 1) as i32
|
||||
} else {
|
||||
options.last
|
||||
};
|
||||
let single = if options.mode == Mode::Project {
|
||||
options.single
|
||||
} else {
|
||||
-1
|
||||
};
|
||||
if single >= 0 && (i64::from(single) >= layers || !have[single as usize]) {
|
||||
return Err(format!(
|
||||
"--cvec-dir single:{single}: the vector has no direction for that layer"
|
||||
));
|
||||
}
|
||||
let mut dir = vec![0.0f32; n_layers * n_embd];
|
||||
let mut s = vec![0.0f32; n_layers];
|
||||
let mut steered = 0;
|
||||
for layer in first..=last {
|
||||
let source = if single >= 0 { single } else { layer } as usize;
|
||||
if source >= n_layers || !have[source] || layer as usize >= n_layers {
|
||||
continue;
|
||||
}
|
||||
let d = &data[source * n_embd..(source + 1) * n_embd];
|
||||
let target = layer as usize;
|
||||
match options.mode {
|
||||
Mode::Project => {
|
||||
let norm = d
|
||||
.iter()
|
||||
.map(|v| f64::from(*v) * f64::from(*v))
|
||||
.sum::<f64>()
|
||||
.sqrt();
|
||||
if norm <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
s[target] = norm as f32;
|
||||
for (j, value) in d.iter().enumerate() {
|
||||
dir[target * n_embd + j] = (f64::from(*value) / norm) as f32;
|
||||
}
|
||||
}
|
||||
Mode::Add => {
|
||||
s[target] = 1.0;
|
||||
dir[target * n_embd..(target + 1) * n_embd].copy_from_slice(d);
|
||||
}
|
||||
}
|
||||
steered += 1;
|
||||
}
|
||||
if steered == 0 {
|
||||
return Err(format!(
|
||||
"the control vector has no direction in layers {first}..{last}"
|
||||
));
|
||||
}
|
||||
let summary = format!(
|
||||
"{}:{first}-{last}{}",
|
||||
if options.mode == Mode::Project {
|
||||
"project"
|
||||
} else {
|
||||
"add"
|
||||
},
|
||||
if single >= 0 {
|
||||
format!(":single{single}")
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
);
|
||||
Ok(Tables {
|
||||
dir,
|
||||
s,
|
||||
mode: options.mode,
|
||||
first,
|
||||
last,
|
||||
steered,
|
||||
summary,
|
||||
warnings,
|
||||
})
|
||||
}
|
||||
|
||||
/// `--control-vector-scaled FILE:SCALE[,FILE:SCALE...]`: the last colon splits, so a path with a
|
||||
/// drive letter keeps it. `Err` is the engine's usage message.
|
||||
pub fn parse_scaled_list(text: &str) -> Result<Vec<(String, f32)>, String> {
|
||||
let mut out = Vec::new();
|
||||
for item in text.split(',') {
|
||||
let bad = || format!("--control-vector-scaled: expected FILE:SCALE, got '{item}'");
|
||||
let (path, scale) = item.rsplit_once(':').ok_or_else(bad)?;
|
||||
if path.is_empty() {
|
||||
return Err(bad());
|
||||
}
|
||||
out.push((path.to_owned(), strtof_exact(scale).ok_or_else(bad)?));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `strtof` that must consume the whole text and find at least one character.
|
||||
fn strtof_exact(text: &str) -> Option<f32> {
|
||||
if text.is_empty() || text.trim() != text {
|
||||
return None;
|
||||
}
|
||||
text.parse::<f32>().ok()
|
||||
}
|
||||
|
||||
/// `--cvec-dir per-layer|single:L`.
|
||||
pub fn parse_dir(text: &str) -> Result<i32, String> {
|
||||
if text == "per-layer" {
|
||||
return Ok(-1);
|
||||
}
|
||||
if let Some(rest) = text.strip_prefix("single:") {
|
||||
return Ok(i32::try_from(strtol(rest)).unwrap_or(0));
|
||||
}
|
||||
Err(format!("--cvec-dir: per-layer or single:L, got '{text}'"))
|
||||
}
|
||||
|
||||
/// `--cvec-mode add|project`.
|
||||
pub fn parse_mode(text: &str) -> Result<Mode, String> {
|
||||
match text {
|
||||
"project" => Ok(Mode::Project),
|
||||
"add" => Ok(Mode::Add),
|
||||
other => Err(format!("--cvec-mode: add or project, got '{other}'")),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn vector(layers: &[(u32, [f32; 3])]) -> VectorFile {
|
||||
VectorFile {
|
||||
architecture: Some("controlvector".into()),
|
||||
model_hint: Some("qwen4exp".into()),
|
||||
tensors: layers
|
||||
.iter()
|
||||
.map(|(layer, values)| VectorTensor {
|
||||
name: format!("direction.{layer}"),
|
||||
kind: 0,
|
||||
elements: 3,
|
||||
values: values.to_vec(),
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_mode_sums_scaled_files() {
|
||||
let a = vector(&[(1, [1.0, 2.0, 3.0])]);
|
||||
let b = vector(&[(1, [10.0, 10.0, 10.0]), (2, [1.0, 0.0, 0.0])]);
|
||||
let tables = build_tables(
|
||||
&[("a".into(), a, 1.0), ("b".into(), b, 0.5)],
|
||||
4,
|
||||
3,
|
||||
Options::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(&tables.dir[3..6], &[6.0, 7.0, 8.0]);
|
||||
assert_eq!(&tables.dir[6..9], &[0.5, 0.0, 0.0]);
|
||||
assert_eq!(tables.s, vec![0.0, 1.0, 1.0, 0.0]);
|
||||
assert_eq!(tables.summary, "add:1-3");
|
||||
assert_eq!(tables.steered, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_mode_stores_the_unit_vector_and_its_norm() {
|
||||
let tables = build_tables(
|
||||
&[("a".into(), vector(&[(1, [3.0, 4.0, 0.0])]), 1.0)],
|
||||
2,
|
||||
3,
|
||||
Options {
|
||||
mode: Mode::Project,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(tables.s[1], 5.0);
|
||||
assert_eq!(&tables.dir[3..6], &[0.6f32, 0.8f32, 0.0]);
|
||||
assert_eq!(tables.summary, "project:1-1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loader_errors_use_the_engines_words() {
|
||||
let ok = vector(&[(1, [1.0, 1.0, 1.0])]);
|
||||
let not_cvec = VectorFile {
|
||||
architecture: Some("llama".into()),
|
||||
..ok.clone()
|
||||
};
|
||||
assert_eq!(
|
||||
build_tables(&[("f".into(), not_cvec, 1.0)], 4, 3, Options::default()).unwrap_err(),
|
||||
"f: not a control vector GGUF (general.architecture is not 'controlvector')"
|
||||
);
|
||||
let none = VectorFile {
|
||||
tensors: vec![],
|
||||
..ok.clone()
|
||||
};
|
||||
assert_eq!(
|
||||
build_tables(&[("f".into(), none, 1.0)], 4, 3, Options::default()).unwrap_err(),
|
||||
"f: no direction.<layer> tensors"
|
||||
);
|
||||
assert_eq!(
|
||||
build_tables(
|
||||
&[("f".into(), ok.clone(), 1.0)],
|
||||
4,
|
||||
3,
|
||||
Options {
|
||||
first: 3,
|
||||
last: 3,
|
||||
..Default::default()
|
||||
}
|
||||
)
|
||||
.unwrap_err(),
|
||||
"the control vector has no direction in layers 3..3"
|
||||
);
|
||||
assert_eq!(
|
||||
build_tables(
|
||||
&[("f".into(), ok, 1.0)],
|
||||
4,
|
||||
3,
|
||||
Options {
|
||||
mode: Mode::Project,
|
||||
single: 2,
|
||||
..Default::default()
|
||||
}
|
||||
)
|
||||
.unwrap_err(),
|
||||
"--cvec-dir single:2: the vector has no direction for that layer"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_values_parse_like_the_engine() {
|
||||
assert_eq!(
|
||||
parse_scaled_list("a.gguf:0.5,C:\\v.gguf:-2").unwrap(),
|
||||
vec![("a.gguf".to_owned(), 0.5), ("C:\\v.gguf".to_owned(), -2.0)]
|
||||
);
|
||||
for bad in ["a.gguf", ":1", "a.gguf:", "a.gguf:x", "a.gguf:1x"] {
|
||||
assert!(parse_scaled_list(bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(parse_dir("per-layer"), Ok(-1));
|
||||
assert_eq!(parse_dir("single:12"), Ok(12));
|
||||
assert!(parse_dir("every").is_err());
|
||||
assert_eq!(parse_mode("project"), Ok(Mode::Project));
|
||||
assert!(parse_mode("x").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gguf_files_round_trip_through_the_parser() {
|
||||
let mut file = b"GGUF".to_vec();
|
||||
file.extend_from_slice(&3u32.to_le_bytes());
|
||||
file.extend_from_slice(&1u64.to_le_bytes());
|
||||
file.extend_from_slice(&1u64.to_le_bytes());
|
||||
let key = b"general.architecture";
|
||||
file.extend_from_slice(&(key.len() as u64).to_le_bytes());
|
||||
file.extend_from_slice(key);
|
||||
file.extend_from_slice(&8u32.to_le_bytes());
|
||||
file.extend_from_slice(&13u64.to_le_bytes());
|
||||
file.extend_from_slice(b"controlvector");
|
||||
let name = b"direction.1";
|
||||
file.extend_from_slice(&(name.len() as u64).to_le_bytes());
|
||||
file.extend_from_slice(name);
|
||||
file.extend_from_slice(&1u32.to_le_bytes());
|
||||
file.extend_from_slice(&2u64.to_le_bytes());
|
||||
file.extend_from_slice(&0u32.to_le_bytes());
|
||||
file.extend_from_slice(&0u64.to_le_bytes());
|
||||
while !file.len().is_multiple_of(32) {
|
||||
file.push(0);
|
||||
}
|
||||
file.extend_from_slice(&1.5f32.to_le_bytes());
|
||||
file.extend_from_slice(&(-2.0f32).to_le_bytes());
|
||||
let parsed = parse_gguf(&file).unwrap();
|
||||
assert_eq!(parsed.architecture.as_deref(), Some("controlvector"));
|
||||
assert_eq!(parsed.tensors[0].values, vec![1.5, -2.0]);
|
||||
assert!(parse_gguf(&file[..file.len() - 1]).is_err());
|
||||
assert!(parse_gguf(b"GGUX").is_err());
|
||||
assert!(parse_gguf(&[]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
//! Sampling fields in the forms the in-process runtime protocol carries them: JSON request
|
||||
//! fields -> [`RequestSampling`] -> fixed point ([`FixedPoint`], thousandths / millionths).
|
||||
//!
|
||||
//! The runtime gRPC contract (`runtime.proto` `GenerateRequest`) and `backend-api`
|
||||
//! `SamplingOptions` keep requests `Eq` by using integers. A float that a client wrote with more
|
||||
//! fractional digits than the field carries is *refused*, never rounded: rounding would silently
|
||||
//! change the distribution the client asked for.
|
||||
|
||||
use leleka_sampler_ref::params::{FixedPoint, RequestSampling, SamplingError};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
/// JSON keys of the sampling fields.
|
||||
pub const SAMPLING_KEYS: [&str; 9] = [
|
||||
"temperature",
|
||||
"top_p",
|
||||
"top_k",
|
||||
"min_p",
|
||||
"repetition_penalty",
|
||||
"frequency_penalty",
|
||||
"presence_penalty",
|
||||
"penalty_last_n",
|
||||
"seed",
|
||||
];
|
||||
|
||||
fn err(field: &'static str, expected: &'static str) -> SamplingError {
|
||||
SamplingError { field, expected }
|
||||
}
|
||||
|
||||
/// `round(value * scale)` when `result / scale` is exactly `value` again.
|
||||
fn exact(value: f64, scale: f64) -> Option<i64> {
|
||||
let scaled = (value * scale).round();
|
||||
if !scaled.is_finite() || scaled.abs() > 9.0e15 {
|
||||
return None;
|
||||
}
|
||||
let candidate = scaled as i64;
|
||||
(candidate as f64 / scale == value).then_some(candidate)
|
||||
}
|
||||
|
||||
const PRECISION_MILLI: &str = "a decimal with at most 3 fractional digits";
|
||||
const PRECISION_MICRO: &str = "a decimal with at most 6 fractional digits";
|
||||
|
||||
/// Validate and convert. Order of checks: the request contract first
|
||||
/// ([`RequestSampling::validate`]), then representability.
|
||||
pub fn to_fixed_point(sampling: &RequestSampling) -> Result<FixedPoint, SamplingError> {
|
||||
sampling.validate()?;
|
||||
let micro_u32 =
|
||||
|field: &'static str, value: Option<f64>| -> Result<Option<u32>, SamplingError> {
|
||||
value
|
||||
.map(|v| {
|
||||
exact(v, 1_000_000.0)
|
||||
.and_then(|n| u32::try_from(n).ok())
|
||||
.ok_or_else(|| err(field, PRECISION_MICRO))
|
||||
})
|
||||
.transpose()
|
||||
};
|
||||
let micro_i32 =
|
||||
|field: &'static str, value: Option<f64>| -> Result<Option<i32>, SamplingError> {
|
||||
value
|
||||
.map(|v| {
|
||||
exact(v, 1_000_000.0)
|
||||
.and_then(|n| i32::try_from(n).ok())
|
||||
.ok_or_else(|| err(field, PRECISION_MICRO))
|
||||
})
|
||||
.transpose()
|
||||
};
|
||||
let temperature_milli = match sampling.temperature {
|
||||
None => 0,
|
||||
Some(t) => exact(t, 1000.0)
|
||||
.and_then(|n| u32::try_from(n).ok())
|
||||
.ok_or_else(|| err("temperature", PRECISION_MILLI))?,
|
||||
};
|
||||
Ok(FixedPoint {
|
||||
temperature_milli,
|
||||
top_p_micro: micro_u32("top_p", sampling.top_p)?,
|
||||
top_k: sampling.top_k.map(|k| u32::try_from(k).unwrap_or(u32::MAX)),
|
||||
min_p_micro: micro_u32("min_p", sampling.min_p)?,
|
||||
repetition_penalty_micro: micro_u32("repetition_penalty", sampling.repetition_penalty)?,
|
||||
frequency_penalty_micro: micro_i32("frequency_penalty", sampling.frequency_penalty)?,
|
||||
presence_penalty_micro: micro_i32("presence_penalty", sampling.presence_penalty)?,
|
||||
penalty_last_n: sampling
|
||||
.penalty_last_n
|
||||
.map(|n| {
|
||||
u32::try_from(n).map_err(|_| err("penalty_last_n", "an integer in 0..=2147483647"))
|
||||
})
|
||||
.transpose()?,
|
||||
seed: sampling.seed,
|
||||
})
|
||||
}
|
||||
|
||||
fn number(object: &Map<String, Value>, key: &'static str) -> Result<Option<f64>, SamplingError> {
|
||||
match object.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::Number(n)) => n
|
||||
.as_f64()
|
||||
.map(Some)
|
||||
.ok_or_else(|| err(key, "a finite number")),
|
||||
Some(_) => Err(err(key, "a number")),
|
||||
}
|
||||
}
|
||||
|
||||
fn integer(object: &Map<String, Value>, key: &'static str) -> Result<Option<i64>, SamplingError> {
|
||||
match object.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::Number(n)) => n.as_i64().map(Some).ok_or_else(|| err(key, "an integer")),
|
||||
Some(_) => Err(err(key, "an integer")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the sampling fields of a JSON request object (unrelated keys are ignored here; the caller
|
||||
/// owns the allow-list of the rest of its request). Types are strict: `top_k` must be an integer,
|
||||
/// `seed` an unsigned integer. Ranges are checked by [`RequestSampling::validate`].
|
||||
pub fn sampling_from_object(object: &Map<String, Value>) -> Result<RequestSampling, SamplingError> {
|
||||
let seed = match object.get("seed") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::Number(n)) => Some(
|
||||
n.as_u64()
|
||||
.ok_or_else(|| err("seed", "an unsigned integer"))?,
|
||||
),
|
||||
Some(_) => return Err(err("seed", "an unsigned integer")),
|
||||
};
|
||||
let sampling = RequestSampling {
|
||||
temperature: number(object, "temperature")?,
|
||||
top_p: number(object, "top_p")?,
|
||||
top_k: integer(object, "top_k")?,
|
||||
min_p: number(object, "min_p")?,
|
||||
repetition_penalty: number(object, "repetition_penalty")?,
|
||||
frequency_penalty: number(object, "frequency_penalty")?,
|
||||
presence_penalty: number(object, "presence_penalty")?,
|
||||
penalty_last_n: integer(object, "penalty_last_n")?,
|
||||
seed,
|
||||
};
|
||||
sampling.validate()?;
|
||||
Ok(sampling)
|
||||
}
|
||||
|
||||
/// A short stable error code for a rejected field (gateway error bodies carry codes, not prose).
|
||||
pub fn error_code(error: &SamplingError) -> &'static str {
|
||||
match error.field {
|
||||
"temperature" => "invalid_temperature",
|
||||
"top_p" => "invalid_top_p",
|
||||
"top_k" => "invalid_top_k",
|
||||
"min_p" => "invalid_min_p",
|
||||
"repetition_penalty" => "invalid_repetition_penalty",
|
||||
"frequency_penalty" => "invalid_frequency_penalty",
|
||||
"presence_penalty" => "invalid_presence_penalty",
|
||||
"penalty_last_n" => "invalid_penalty_last_n",
|
||||
"seed" => "invalid_seed",
|
||||
_ => "invalid_sampling",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn obj(v: Value) -> Map<String, Value> {
|
||||
v.as_object().unwrap().clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decimals_round_trip_through_fixed_point() {
|
||||
for t in [0.0, 0.1, 0.7, 0.8, 1.0, 1.5, 2.0, 0.123, 0.001] {
|
||||
let s = RequestSampling {
|
||||
temperature: Some(t),
|
||||
..Default::default()
|
||||
};
|
||||
let f = to_fixed_point(&s).unwrap();
|
||||
assert_eq!(
|
||||
RequestSampling::from_fixed_point(&f).temperature,
|
||||
Some(t),
|
||||
"{t}"
|
||||
);
|
||||
}
|
||||
let s = RequestSampling {
|
||||
temperature: Some(0.6),
|
||||
top_p: Some(0.95),
|
||||
top_k: Some(20),
|
||||
min_p: Some(0.05),
|
||||
repetition_penalty: Some(1.05),
|
||||
frequency_penalty: Some(-0.5),
|
||||
presence_penalty: Some(0.25),
|
||||
penalty_last_n: Some(256),
|
||||
seed: Some(99),
|
||||
};
|
||||
assert_eq!(
|
||||
RequestSampling::from_fixed_point(&to_fixed_point(&s).unwrap()),
|
||||
s
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_finer_than_the_wire_are_refused_not_rounded() {
|
||||
for s in [
|
||||
RequestSampling {
|
||||
temperature: Some(0.1234),
|
||||
..Default::default()
|
||||
},
|
||||
RequestSampling {
|
||||
top_p: Some(0.9999999),
|
||||
..Default::default()
|
||||
},
|
||||
RequestSampling {
|
||||
frequency_penalty: Some(0.0000001),
|
||||
..Default::default()
|
||||
},
|
||||
] {
|
||||
assert!(to_fixed_point(&s).is_err(), "{s:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn out_of_contract_values_are_refused() {
|
||||
for s in [
|
||||
RequestSampling {
|
||||
temperature: Some(2.001),
|
||||
..Default::default()
|
||||
},
|
||||
RequestSampling {
|
||||
top_p: Some(1.5),
|
||||
..Default::default()
|
||||
},
|
||||
RequestSampling {
|
||||
penalty_last_n: Some(-1),
|
||||
..Default::default()
|
||||
},
|
||||
] {
|
||||
assert!(to_fixed_point(&s).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_fields_are_read_strictly() {
|
||||
let s = sampling_from_object(&obj(json!({
|
||||
"temperature": 0.7, "top_p": 0.9, "top_k": 40, "min_p": 0.05, "repetition_penalty": 1.1,
|
||||
"frequency_penalty": 0.5, "presence_penalty": 0.5, "penalty_last_n": 64, "seed": 7,
|
||||
"model": "ignored", "temperature_null": null
|
||||
})))
|
||||
.unwrap();
|
||||
assert_eq!(s.top_k, Some(40));
|
||||
assert_eq!(s.seed, Some(7));
|
||||
for bad in [
|
||||
json!({"top_k": 1.5}),
|
||||
json!({"top_k": "5"}),
|
||||
json!({"seed": -1}),
|
||||
json!({"seed": 1.5}),
|
||||
json!({"temperature": "hot"}),
|
||||
json!({"temperature": 3}),
|
||||
json!({"min_p": 2}),
|
||||
] {
|
||||
assert!(sampling_from_object(&obj(bad.clone())).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(
|
||||
sampling_from_object(&obj(json!({"temperature": null}))).unwrap(),
|
||||
RequestSampling::default()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
//! Idle unload (`Service.unload` / `start_idle_unload` of `serve/server.py`): give the GPU back
|
||||
//! after a period without requests so other programs can use it; the next request loads the model
|
||||
//! again. Pure decision logic with injected time; the supervisor in `control-plane` performs the
|
||||
//! actual stop.
|
||||
|
||||
/// `--idle-unload SECONDS` polling interval: `max(1, min(30, idle / 4))` seconds.
|
||||
pub fn poll_interval_s(idle_s: f64) -> f64 {
|
||||
(idle_s / 4.0).clamp(0.0, 30.0).max(1.0)
|
||||
}
|
||||
|
||||
/// The outcome strings `/unload` answers with.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Outcome {
|
||||
Unloaded,
|
||||
NotLoaded,
|
||||
Busy,
|
||||
Unsupported,
|
||||
}
|
||||
|
||||
impl Outcome {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Unloaded => "unloaded",
|
||||
Self::NotLoaded => "not loaded",
|
||||
Self::Busy => "busy",
|
||||
Self::Unsupported => "unsupported",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the supervisor knows when asked to unload.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Situation {
|
||||
/// The engine can be unloaded at all (`hasattr(engine, "unload")`).
|
||||
pub supported: bool,
|
||||
/// The engine process is running.
|
||||
pub loaded: bool,
|
||||
/// A request is running or waiting.
|
||||
pub busy: bool,
|
||||
/// Seconds since a request last started or finished (or since start).
|
||||
pub idle_s: f64,
|
||||
}
|
||||
|
||||
/// `Service.unload(idle_for)`: `idle_for = None` is the explicit `/unload`, `Some(n)` the idle
|
||||
/// thread (only if no request ran within the last `n` seconds).
|
||||
pub fn decide(situation: Situation, idle_for: Option<f64>) -> Outcome {
|
||||
if !situation.supported {
|
||||
return Outcome::Unsupported;
|
||||
}
|
||||
if !situation.loaded {
|
||||
return Outcome::NotLoaded;
|
||||
}
|
||||
if situation.busy {
|
||||
return Outcome::Busy;
|
||||
}
|
||||
if idle_for.is_some_and(|limit| situation.idle_s < limit) {
|
||||
return Outcome::Busy;
|
||||
}
|
||||
Outcome::Unloaded
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn situation(loaded: bool, busy: bool, idle_s: f64) -> Situation {
|
||||
Situation {
|
||||
supported: true,
|
||||
loaded,
|
||||
busy,
|
||||
idle_s,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn poll_interval_follows_the_originals_formula() {
|
||||
assert_eq!(poll_interval_s(1.0), 1.0);
|
||||
assert_eq!(poll_interval_s(8.0), 2.0);
|
||||
assert_eq!(poll_interval_s(60.0), 15.0);
|
||||
assert_eq!(poll_interval_s(600.0), 30.0);
|
||||
assert_eq!(poll_interval_s(0.5), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_unload_ignores_idle_time_but_not_a_running_request() {
|
||||
assert_eq!(decide(situation(true, false, 0.0), None), Outcome::Unloaded);
|
||||
assert_eq!(decide(situation(true, true, 99.0), None), Outcome::Busy);
|
||||
assert_eq!(
|
||||
decide(situation(false, false, 99.0), None),
|
||||
Outcome::NotLoaded
|
||||
);
|
||||
assert_eq!(
|
||||
decide(
|
||||
Situation {
|
||||
supported: false,
|
||||
..situation(true, false, 0.0)
|
||||
},
|
||||
None
|
||||
),
|
||||
Outcome::Unsupported
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_idle_thread_waits_for_the_full_idle_period() {
|
||||
assert_eq!(
|
||||
decide(situation(true, false, 59.9), Some(60.0)),
|
||||
Outcome::Busy
|
||||
);
|
||||
assert_eq!(
|
||||
decide(situation(true, false, 60.0), Some(60.0)),
|
||||
Outcome::Unloaded
|
||||
);
|
||||
assert_eq!(
|
||||
decide(situation(false, false, 1e9), Some(60.0)),
|
||||
Outcome::NotLoaded
|
||||
);
|
||||
assert_eq!(Outcome::NotLoaded.as_str(), "not loaded");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
//! 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 cors;
|
||||
pub mod cvec;
|
||||
pub mod fixed;
|
||||
pub mod idle;
|
||||
pub mod reasoning;
|
||||
pub mod shared;
|
||||
pub mod stride;
|
||||
pub mod timings;
|
||||
pub mod vision;
|
||||
pub mod watchdog;
|
||||
@@ -0,0 +1,251 @@
|
||||
//! Reasoning-budget wrap-up (issue #123 of the Original): `Service.reasoning_budget` and the
|
||||
//! budget branch of `Service.run` in `serve/server.py`.
|
||||
//!
|
||||
//! A request may cap how many tokens the model spends thinking (`reasoning_budget_tokens`, else
|
||||
//! the config default). When the thinking reaches the cap at a *clean point* - no part of a
|
||||
//! `</think>` tag held back, no UTF-8 character split across tokens - generation is stopped, the
|
||||
//! fixed [`WRAP_UP`] text (which ends the thinking the way the model would) is appended to the
|
||||
//! output, and generation continues from `prompt + generated + wrap-up`, so the engine keeps the
|
||||
//! prefix it already holds.
|
||||
//!
|
||||
//! [`BudgetTracker`] is the pure decision part: feed it each generated token's bytes, it answers
|
||||
//! when to wrap up. It reproduces the interplay of the Original's incremental UTF-8 `Detokenizer`
|
||||
//! and `OutputParser` (state `reasoning`, `buf` = a held prefix of `</think>`).
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::shared::py_repr;
|
||||
|
||||
/// What closes the thinking when the budget is reached (`REASONING_WRAP_UP`).
|
||||
pub const WRAP_UP: &str =
|
||||
"\n\nI have thought about this long enough; time to give my answer.\n</think>\n\n";
|
||||
|
||||
const THINK_END: &str = "</think>";
|
||||
|
||||
/// `Service.reasoning_budget`: the request's `reasoning_budget_tokens`, else the config's; `0` or
|
||||
/// less means no budget (so a request can switch a configured one off); anything that is not a
|
||||
/// whole number is an error (a 400 in the Original).
|
||||
pub fn parse_budget(
|
||||
request: Option<&Value>,
|
||||
config_default: Option<&Value>,
|
||||
) -> Result<Option<u64>, String> {
|
||||
let value = match request {
|
||||
Some(v) if !v.is_null() => Some(v),
|
||||
_ => config_default.filter(|v| !v.is_null()),
|
||||
};
|
||||
let Some(value) = value else {
|
||||
return Ok(None);
|
||||
};
|
||||
let whole = match value {
|
||||
Value::Number(n) => n
|
||||
.as_i64()
|
||||
.map(i128::from)
|
||||
.or_else(|| n.as_u64().map(i128::from))
|
||||
.or_else(|| {
|
||||
n.as_f64()
|
||||
.filter(|f| f.is_finite() && f.fract() == 0.0 && f.abs() < 1e18)
|
||||
.map(|f| f as i128)
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
match whole {
|
||||
Some(n) if n > 0 => Ok(Some(u64::try_from(n).unwrap_or(u64::MAX))),
|
||||
Some(_) => Ok(None),
|
||||
None => Err(format!(
|
||||
"reasoning_budget_tokens={}: expected a whole number of tokens (0: no budget)",
|
||||
py_repr(value)
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The verdict after one generated token.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Verdict {
|
||||
Continue,
|
||||
/// Stop now and append [`WRAP_UP`].
|
||||
WrapUp,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BudgetTracker {
|
||||
budget: u64,
|
||||
thought: u64,
|
||||
reasoning: bool,
|
||||
/// The parser's `buf` in the reasoning state: a held proper prefix of `</think>`.
|
||||
held: String,
|
||||
/// Bytes of a UTF-8 character not yet complete (`Detokenizer.pending`).
|
||||
partial: Vec<u8>,
|
||||
}
|
||||
|
||||
impl BudgetTracker {
|
||||
/// `budget` must be positive (a missing budget means no tracker).
|
||||
pub fn new(budget: u64) -> Self {
|
||||
Self {
|
||||
budget,
|
||||
thought: 0,
|
||||
reasoning: true,
|
||||
held: String::new(),
|
||||
partial: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reasoning tokens counted so far.
|
||||
pub fn thought(&self) -> u64 {
|
||||
self.thought
|
||||
}
|
||||
|
||||
/// Still inside the thinking (before `</think>`).
|
||||
pub fn in_reasoning(&self) -> bool {
|
||||
self.reasoning
|
||||
}
|
||||
|
||||
/// Feed the next generated token's bytes.
|
||||
pub fn push(&mut self, token: &[u8]) -> Verdict {
|
||||
if !self.reasoning {
|
||||
return Verdict::Continue;
|
||||
}
|
||||
let text = self.decode(token);
|
||||
self.held.push_str(&text);
|
||||
if let Some(at) = self.held.find(THINK_END) {
|
||||
self.held.drain(..at + THINK_END.len());
|
||||
self.reasoning = false;
|
||||
return Verdict::Continue;
|
||||
}
|
||||
let keep = hold(&self.held, THINK_END);
|
||||
let cut = self.held.len() - keep;
|
||||
self.held.drain(..cut);
|
||||
self.thought += 1;
|
||||
if self.thought >= self.budget && self.held.is_empty() && self.partial.is_empty() {
|
||||
Verdict::WrapUp
|
||||
} else {
|
||||
Verdict::Continue
|
||||
}
|
||||
}
|
||||
|
||||
/// Incremental UTF-8 decode with replacement characters (Python's
|
||||
/// `codecs.getincrementaldecoder("utf-8")(errors="replace")`).
|
||||
fn decode(&mut self, token: &[u8]) -> String {
|
||||
self.partial.extend_from_slice(token);
|
||||
let mut out = String::new();
|
||||
loop {
|
||||
match std::str::from_utf8(&self.partial) {
|
||||
Ok(valid) => {
|
||||
out.push_str(valid);
|
||||
self.partial.clear();
|
||||
return out;
|
||||
}
|
||||
Err(error) => {
|
||||
let valid = error.valid_up_to();
|
||||
out.push_str(
|
||||
std::str::from_utf8(&self.partial[..valid]).expect("valid prefix"),
|
||||
);
|
||||
match error.error_len() {
|
||||
None => {
|
||||
self.partial.drain(..valid);
|
||||
return out;
|
||||
}
|
||||
Some(bad) => {
|
||||
out.push('\u{FFFD}');
|
||||
self.partial.drain(..valid + bad);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `OutputParser._hold`: the length of the longest suffix of `text` that is a proper prefix of `tag`.
|
||||
fn hold(text: &str, tag: &str) -> usize {
|
||||
(1..tag.len())
|
||||
.rev()
|
||||
.find(|n| text.ends_with(&tag[..*n]))
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// What the wrap-up appends, for the caller to turn into token ids.
|
||||
pub fn wrap_up_text() -> &'static str {
|
||||
WRAP_UP
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn budget_parsing_follows_the_originals_rules() {
|
||||
let none = None;
|
||||
assert_eq!(parse_budget(none, none), Ok(None));
|
||||
assert_eq!(parse_budget(Some(&json!(20)), none), Ok(Some(20)));
|
||||
assert_eq!(parse_budget(Some(&json!(20.0)), none), Ok(Some(20)));
|
||||
assert_eq!(parse_budget(Some(&json!(0)), Some(&json!(50))), Ok(None));
|
||||
assert_eq!(parse_budget(Some(&json!(-3)), none), Ok(None));
|
||||
assert_eq!(parse_budget(None, Some(&json!(50))), Ok(Some(50)));
|
||||
assert_eq!(
|
||||
parse_budget(Some(&json!(null)), Some(&json!(50))),
|
||||
Ok(Some(50))
|
||||
);
|
||||
for bad in [json!(true), json!("5"), json!(2.5), json!([1])] {
|
||||
let error = parse_budget(Some(&bad), none).unwrap_err();
|
||||
assert!(error.starts_with("reasoning_budget_tokens="), "{error}");
|
||||
assert!(error.ends_with("expected a whole number of tokens (0: no budget)"));
|
||||
}
|
||||
assert_eq!(
|
||||
parse_budget(Some(&json!("5")), none).unwrap_err(),
|
||||
"reasoning_budget_tokens='5': expected a whole number of tokens (0: no budget)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wraps_up_at_the_budget_on_a_clean_token() {
|
||||
let mut t = BudgetTracker::new(3);
|
||||
assert_eq!(t.push(b"a"), Verdict::Continue);
|
||||
assert_eq!(t.push(b"b"), Verdict::Continue);
|
||||
assert_eq!(t.push(b"c"), Verdict::WrapUp);
|
||||
assert_eq!(t.thought(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_held_tag_prefix_delays_the_wrap_up() {
|
||||
let mut t = BudgetTracker::new(2);
|
||||
assert_eq!(t.push(b"x"), Verdict::Continue);
|
||||
// the second token ends with "</": held back by the parser, not clean
|
||||
assert_eq!(t.push(b"</"), Verdict::Continue);
|
||||
assert_eq!(t.push(b"y"), Verdict::WrapUp);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_split_character_delays_the_wrap_up() {
|
||||
let mut t = BudgetTracker::new(1);
|
||||
assert_eq!(t.push(&[0xC3]), Verdict::Continue);
|
||||
assert_eq!(t.push(&[0xA9]), Verdict::WrapUp);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_the_thinking_ends_the_budget() {
|
||||
let mut t = BudgetTracker::new(2);
|
||||
assert_eq!(t.push(b"a"), Verdict::Continue);
|
||||
assert_eq!(t.push(b"</think>"), Verdict::Continue);
|
||||
assert!(!t.in_reasoning());
|
||||
assert_eq!(t.push(b"b"), Verdict::Continue);
|
||||
assert_eq!(t.push(b"c"), Verdict::Continue);
|
||||
assert_eq!(t.thought(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tag_split_over_tokens_is_still_found() {
|
||||
let mut t = BudgetTracker::new(100);
|
||||
for piece in [&b"</"[..], b"thi", b"nk", b">"] {
|
||||
let _ = t.push(piece);
|
||||
}
|
||||
assert!(!t.in_reasoning());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_utf8_becomes_replacement_characters_not_a_stall() {
|
||||
let mut t = BudgetTracker::new(2);
|
||||
assert_eq!(t.push(&[0xFF]), Verdict::Continue);
|
||||
assert_eq!(t.push(&[0xFF]), Verdict::WrapUp);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,547 @@
|
||||
//! The server-wide Chat settings (`POST /settings`), the run config's `sampling` block, and how
|
||||
//! both are merged under a request. Port of `serve/server.py` `clean_shared_defaults`,
|
||||
//! `sampling_defaults_from_config`, `Service.with_shared`, `Service.run`'s default merge and
|
||||
//! the `defaults` part of `GET /props`.
|
||||
//!
|
||||
//! Differences from the Original, all on the safe side:
|
||||
//!
|
||||
//! * integers wider than `u64` (a `seed`/`max_tokens`/`top_k` Python would keep as a big int)
|
||||
//! are rejected;
|
||||
//! * config `temperature` above 2 is rejected here (the Original accepts any `>= 0` in the
|
||||
//! config but the request boundary of this port caps `temperature` at 2, so a larger default
|
||||
//! could never be applied);
|
||||
//! * error text mirrors the Original's for the common cases and is golden-tested.
|
||||
|
||||
use leleka_sampler_ref::RequestSampling;
|
||||
use leleka_sampler_ref::params::py_float_repr;
|
||||
use serde_json::{Map, Number, Value};
|
||||
|
||||
/// The keys `POST /settings` accepts (`SHARED_KEYS`).
|
||||
pub const SHARED_KEYS: [&str; 7] = [
|
||||
"reasoning_effort",
|
||||
"temperature",
|
||||
"top_p",
|
||||
"top_k",
|
||||
"seed",
|
||||
"max_tokens",
|
||||
"experimental_speed_projection",
|
||||
];
|
||||
|
||||
/// `clean_shared_defaults` output: only the keys a client set.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct SharedDefaults {
|
||||
pub reasoning_effort: Option<String>,
|
||||
pub temperature: Option<f64>,
|
||||
pub top_p: Option<f64>,
|
||||
pub top_k: Option<i64>,
|
||||
pub seed: Option<u64>,
|
||||
pub max_tokens: Option<u64>,
|
||||
pub experimental_speed_projection: Option<bool>,
|
||||
}
|
||||
|
||||
impl SharedDefaults {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
*self == Self::default()
|
||||
}
|
||||
|
||||
/// The JSON object `/settings` answers with and persists (`defaults`).
|
||||
pub fn to_json(&self) -> Value {
|
||||
let mut out = Map::new();
|
||||
if let Some(v) = &self.reasoning_effort {
|
||||
out.insert("reasoning_effort".into(), Value::String(v.clone()));
|
||||
}
|
||||
if let Some(v) = self.temperature {
|
||||
out.insert("temperature".into(), float_value(v));
|
||||
}
|
||||
if let Some(v) = self.top_p {
|
||||
out.insert("top_p".into(), float_value(v));
|
||||
}
|
||||
if let Some(v) = self.top_k {
|
||||
out.insert("top_k".into(), Value::from(v));
|
||||
}
|
||||
if let Some(v) = self.seed {
|
||||
out.insert("seed".into(), Value::from(v));
|
||||
}
|
||||
if let Some(v) = self.max_tokens {
|
||||
out.insert("max_tokens".into(), Value::from(v));
|
||||
}
|
||||
if let Some(v) = self.experimental_speed_projection {
|
||||
out.insert("experimental_speed_projection".into(), Value::Bool(v));
|
||||
}
|
||||
Value::Object(out)
|
||||
}
|
||||
|
||||
/// The sampling subset the shared settings carry.
|
||||
pub fn sampling(&self) -> RequestSampling {
|
||||
RequestSampling {
|
||||
temperature: self.temperature,
|
||||
top_p: self.top_p,
|
||||
top_k: self.top_k,
|
||||
seed: self.seed,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn float_value(v: f64) -> Value {
|
||||
Number::from_f64(v).map_or(Value::Null, Value::Number)
|
||||
}
|
||||
|
||||
/// Python's `repr()` of a JSON-ish value, for the Original's error text.
|
||||
pub fn py_repr(value: &Value) -> String {
|
||||
match value {
|
||||
Value::Null => "None".into(),
|
||||
Value::Bool(true) => "True".into(),
|
||||
Value::Bool(false) => "False".into(),
|
||||
Value::Number(n) => match n.as_i64() {
|
||||
Some(i) => i.to_string(),
|
||||
None => match n.as_u64() {
|
||||
Some(u) => u.to_string(),
|
||||
None => py_float_repr(n.as_f64().unwrap_or(f64::NAN)),
|
||||
},
|
||||
},
|
||||
Value::String(s) => py_str_repr(s),
|
||||
Value::Array(items) => format!(
|
||||
"[{}]",
|
||||
items.iter().map(py_repr).collect::<Vec<_>>().join(", ")
|
||||
),
|
||||
Value::Object(map) => format!(
|
||||
"{{{}}}",
|
||||
map.iter()
|
||||
.map(|(k, v)| format!("{}: {}", py_str_repr(k), py_repr(v)))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Python's `repr(str)`: single quotes unless the text has a single and no double quote.
|
||||
pub fn py_str_repr(s: &str) -> String {
|
||||
let quote = if s.contains('\'') && !s.contains('"') {
|
||||
'"'
|
||||
} else {
|
||||
'\''
|
||||
};
|
||||
let mut out = String::new();
|
||||
out.push(quote);
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
c if c == quote => {
|
||||
out.push('\\');
|
||||
out.push(c);
|
||||
}
|
||||
c if (c as u32) < 0x20 || c as u32 == 0x7f => {
|
||||
out.push_str(&format!("\\x{:02x}", c as u32));
|
||||
}
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push(quote);
|
||||
out
|
||||
}
|
||||
|
||||
fn is_number(v: &Value) -> bool {
|
||||
v.is_number()
|
||||
}
|
||||
|
||||
fn as_f64(v: &Value) -> Option<f64> {
|
||||
v.as_f64()
|
||||
}
|
||||
|
||||
/// An integral number as `i128`, or `None`.
|
||||
fn integral(v: &Value) -> Option<i128> {
|
||||
if let Some(i) = v.as_i64() {
|
||||
return Some(i128::from(i));
|
||||
}
|
||||
if let Some(u) = v.as_u64() {
|
||||
return Some(i128::from(u));
|
||||
}
|
||||
let f = v.as_f64()?;
|
||||
(f.is_finite() && f.fract() == 0.0 && f.abs() < 1e18).then_some(f as i128)
|
||||
}
|
||||
|
||||
/// `clean_shared_defaults`: `Ok` with only the known, valid keys; `Err` names the first bad one
|
||||
/// (the message the Original's `ValueError` carries).
|
||||
pub fn clean_shared_defaults(defaults: &Value) -> Result<SharedDefaults, String> {
|
||||
let map = match defaults {
|
||||
Value::Null => return Ok(SharedDefaults::default()),
|
||||
Value::Object(map) => map,
|
||||
_ => return Err("defaults must be an object".into()),
|
||||
};
|
||||
let mut out = SharedDefaults::default();
|
||||
for (key, value) in map {
|
||||
if value.is_null() || value.as_str() == Some("") {
|
||||
continue;
|
||||
}
|
||||
match key.as_str() {
|
||||
"reasoning_effort" => match value.as_str() {
|
||||
Some(e @ ("none" | "low" | "medium" | "high")) => {
|
||||
out.reasoning_effort = Some(e.to_owned());
|
||||
}
|
||||
_ => return Err("reasoning_effort: none, low, medium or high".into()),
|
||||
},
|
||||
"temperature" => match as_f64(value) {
|
||||
Some(t) if is_number(value) && (0.0..=2.0).contains(&t) => {
|
||||
out.temperature = Some(t)
|
||||
}
|
||||
_ => return Err("temperature: 0..2".into()),
|
||||
},
|
||||
"top_p" => match as_f64(value) {
|
||||
Some(p) if is_number(value) && p > 0.0 && p <= 1.0 => out.top_p = Some(p),
|
||||
_ => return Err("top_p: 0 < top_p <= 1".into()),
|
||||
},
|
||||
"top_k" => match integral(value) {
|
||||
Some(k) if is_number(value) && (1..=64).contains(&k) => out.top_k = Some(k as i64),
|
||||
_ => return Err("top_k: an integer 1..64".into()),
|
||||
},
|
||||
"seed" => match integral(value) {
|
||||
Some(s) if is_number(value) && s > 0 && s <= i128::from(u64::MAX) => {
|
||||
out.seed = Some(s as u64);
|
||||
}
|
||||
_ => return Err("seed: a positive integer".into()),
|
||||
},
|
||||
"max_tokens" => match integral(value) {
|
||||
Some(s) if is_number(value) && s > 0 && s <= i128::from(u64::MAX) => {
|
||||
out.max_tokens = Some(s as u64);
|
||||
}
|
||||
_ => return Err("max_tokens: a positive integer".into()),
|
||||
},
|
||||
"experimental_speed_projection" => match value.as_bool() {
|
||||
Some(b) => out.experimental_speed_projection = Some(b),
|
||||
None => return Err("experimental_speed_projection: true or false".into()),
|
||||
},
|
||||
other => return Err(format!("unknown setting {}", py_str_repr(other))),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The run config's `sampling` block (`sampling_defaults_from_config`).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ConfigSampling {
|
||||
pub sampling: RequestSampling,
|
||||
pub experimental_speed_projection: Option<bool>,
|
||||
/// Keys the Original names at startup and ignores.
|
||||
pub ignored: Vec<String>,
|
||||
}
|
||||
|
||||
fn config_error(key: &str, value: &Value, expected: &str) -> String {
|
||||
format!(
|
||||
"[strata] config sampling.{key}={}: {expected}",
|
||||
py_repr(value)
|
||||
)
|
||||
}
|
||||
|
||||
/// Parse the config's `sampling` object. A bad value is an error (the Original stops the start).
|
||||
pub fn sampling_defaults_from_config(block: &Value) -> Result<ConfigSampling, String> {
|
||||
let map = match block {
|
||||
Value::Null => return Ok(ConfigSampling::default()),
|
||||
Value::Object(map) => map,
|
||||
_ => return Err("[strata] config sampling: expected an object".into()),
|
||||
};
|
||||
let mut out = ConfigSampling::default();
|
||||
for (key, value) in map {
|
||||
if value.is_null() {
|
||||
continue;
|
||||
}
|
||||
let number = is_number(value);
|
||||
let f = as_f64(value).filter(|_| number);
|
||||
match key.as_str() {
|
||||
"temperature" => match f {
|
||||
Some(v) if v >= 0.0 => out.sampling.temperature = Some(v),
|
||||
_ => {
|
||||
return Err(config_error(
|
||||
key,
|
||||
value,
|
||||
"expected a number >= 0 (0 = greedy)",
|
||||
));
|
||||
}
|
||||
},
|
||||
"top_p" => match f {
|
||||
Some(v) if v > 0.0 && v <= 1.0 => out.sampling.top_p = Some(v),
|
||||
_ => return Err(config_error(key, value, "expected 0 < top_p <= 1")),
|
||||
},
|
||||
"min_p" => match f {
|
||||
Some(v) if (0.0..=1.0).contains(&v) => out.sampling.min_p = Some(v),
|
||||
_ => return Err(config_error(key, value, "expected 0 <= min_p <= 1")),
|
||||
},
|
||||
"top_k" => match integral(value) {
|
||||
Some(k) if number && (1..=64).contains(&k) => out.sampling.top_k = Some(k as i64),
|
||||
_ => {
|
||||
return Err(config_error(
|
||||
key,
|
||||
value,
|
||||
"the sampled path takes an integer 1..64",
|
||||
));
|
||||
}
|
||||
},
|
||||
"presence_penalty" => match f {
|
||||
Some(v) if v >= 0.0 => out.sampling.presence_penalty = Some(v),
|
||||
_ => return Err(config_error(key, value, "expected a number >= 0")),
|
||||
},
|
||||
"frequency_penalty" => match f {
|
||||
Some(v) if v >= 0.0 => out.sampling.frequency_penalty = Some(v),
|
||||
_ => return Err(config_error(key, value, "expected a number >= 0")),
|
||||
},
|
||||
"repetition_penalty" => match f {
|
||||
Some(v) if v > 0.0 => out.sampling.repetition_penalty = Some(v),
|
||||
_ => return Err(config_error(key, value, "expected a number > 0 (1 = off)")),
|
||||
},
|
||||
"penalty_last_n" => match integral(value) {
|
||||
Some(n) if number && (0..=i128::from(i32::MAX)).contains(&n) => {
|
||||
out.sampling.penalty_last_n = Some(n as i64);
|
||||
}
|
||||
_ => {
|
||||
return Err(config_error(key, value, "expected a non-negative integer"));
|
||||
}
|
||||
},
|
||||
"seed" => match integral(value) {
|
||||
Some(s) if number && s > 0 && s <= i128::from(u64::MAX) => {
|
||||
out.sampling.seed = Some(s as u64);
|
||||
}
|
||||
_ => return Err(config_error(key, value, "expected a positive integer")),
|
||||
},
|
||||
"experimental_speed_projection" => match value.as_bool() {
|
||||
Some(b) => out.experimental_speed_projection = Some(b),
|
||||
None => {
|
||||
return Err(config_error(
|
||||
key,
|
||||
value,
|
||||
"expected true or false (the default for requests that leave it out, when the engine has the vector)",
|
||||
));
|
||||
}
|
||||
},
|
||||
other => out.ignored.push(other.to_owned()),
|
||||
}
|
||||
}
|
||||
// The request boundary of this port refuses temperatures above 2; a default must be usable.
|
||||
out.sampling
|
||||
.validate_config_defaults()
|
||||
.map_err(|e| format!("[strata] config sampling.{}: {}", e.field, e.expected))?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `Service.set_aliases`: the config's `aliases` - a list of names (or one comma-separated string), like
|
||||
/// llama-server's `--alias`. Names are trimmed; empty names, the model's own name and duplicates are
|
||||
/// dropped. `Err` for anything else.
|
||||
pub fn normalize_aliases(value: &Value, model: &str) -> Result<Vec<String>, String> {
|
||||
let names: Vec<String> = match value {
|
||||
Value::Null => Vec::new(),
|
||||
Value::String(text) => text.split(',').map(str::to_owned).collect(),
|
||||
Value::Array(items) if items.iter().all(Value::is_string) => items
|
||||
.iter()
|
||||
.filter_map(|v| v.as_str().map(str::to_owned))
|
||||
.collect(),
|
||||
other => {
|
||||
return Err(format!(
|
||||
"aliases={}: expected a list of model names",
|
||||
py_repr(other)
|
||||
));
|
||||
}
|
||||
};
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for name in names {
|
||||
let name = name.trim().to_owned();
|
||||
if !name.is_empty() && name != model && !out.contains(&name) {
|
||||
out.push(name);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The defaults a request starts from: the config block, then the shared settings on top
|
||||
/// (`{**sampling_defaults, **shared}`). The speed-projection default comes the same way.
|
||||
pub fn merged_defaults(config: &ConfigSampling, shared: &SharedDefaults) -> MergedDefaults {
|
||||
MergedDefaults {
|
||||
sampling: RequestSampling::overlay(&config.sampling, &shared.sampling()),
|
||||
experimental_speed_projection: shared
|
||||
.experimental_speed_projection
|
||||
.or(config.experimental_speed_projection),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct MergedDefaults {
|
||||
pub sampling: RequestSampling,
|
||||
pub experimental_speed_projection: Option<bool>,
|
||||
}
|
||||
|
||||
impl MergedDefaults {
|
||||
/// `default_generation_settings.params` of `GET /props` (llama-server names).
|
||||
pub fn props_params(&self, shared: &SharedDefaults) -> Value {
|
||||
let mut params = Map::new();
|
||||
let s = &self.sampling;
|
||||
let mut put = |name: &str, value: Option<Value>| {
|
||||
if let Some(v) = value {
|
||||
params.insert(name.to_owned(), v);
|
||||
}
|
||||
};
|
||||
put("temperature", s.temperature.map(float_value));
|
||||
put("top_p", s.top_p.map(float_value));
|
||||
put("top_k", s.top_k.map(Value::from));
|
||||
put("min_p", s.min_p.map(float_value));
|
||||
put("seed", s.seed.map(Value::from));
|
||||
put("repeat_penalty", s.repetition_penalty.map(float_value));
|
||||
put("presence_penalty", s.presence_penalty.map(float_value));
|
||||
put("frequency_penalty", s.frequency_penalty.map(float_value));
|
||||
put("repeat_last_n", s.penalty_last_n.map(Value::from));
|
||||
params.insert(
|
||||
"n_predict".into(),
|
||||
shared.max_tokens.map_or(Value::from(-1), Value::from),
|
||||
);
|
||||
Value::Object(params)
|
||||
}
|
||||
}
|
||||
|
||||
/// `with_shared`, `max_tokens` half: the shared limit when the request has none of its own.
|
||||
pub fn shared_max_tokens(request_max: Option<u64>, shared: &SharedDefaults) -> Option<u64> {
|
||||
match request_max {
|
||||
Some(n) if n > 0 => Some(n),
|
||||
_ => shared.max_tokens.or(request_max),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn unknown_keys_are_refused_unless_their_value_is_empty() {
|
||||
let d = clean_shared_defaults(&json!({"top_p": null, "x": null, "min_p": ""})).unwrap();
|
||||
assert!(d.is_empty());
|
||||
assert_eq!(
|
||||
clean_shared_defaults(&json!({"min_p": 0.1})),
|
||||
Err("unknown setting 'min_p'".to_owned())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_and_null_values_are_dropped() {
|
||||
let d = clean_shared_defaults(&json!({"temperature": "", "top_p": null})).unwrap();
|
||||
assert!(d.is_empty());
|
||||
assert!(clean_shared_defaults(&Value::Null).unwrap().is_empty());
|
||||
assert!(clean_shared_defaults(&json!([1])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_values_are_normalised_like_the_original() {
|
||||
let d = clean_shared_defaults(&json!({"temperature": 1, "top_k": 40.0, "seed": 7,
|
||||
"reasoning_effort": "high", "max_tokens": 100, "top_p": 1}))
|
||||
.unwrap();
|
||||
assert_eq!(d.temperature, Some(1.0));
|
||||
assert_eq!(d.top_k, Some(40));
|
||||
assert_eq!(d.seed, Some(7));
|
||||
assert_eq!(d.max_tokens, Some(100));
|
||||
assert_eq!(d.top_p, Some(1.0));
|
||||
assert_eq!(
|
||||
d.to_json(),
|
||||
json!({"reasoning_effort": "high", "temperature": 1.0, "top_p": 1.0, "top_k": 40,
|
||||
"seed": 7, "max_tokens": 100})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_block_checks_the_originals_ranges() {
|
||||
let c = sampling_defaults_from_config(&json!({"temperature": 0.7, "top_p": 0.9,
|
||||
"top_k": 40, "min_p": 0.05, "presence_penalty": 0.5, "repetition_penalty": 1.1,
|
||||
"frequency_penalty": 0.0, "penalty_last_n": 128, "seed": 5,
|
||||
"experimental_speed_projection": true, "nonsense": 1}))
|
||||
.unwrap();
|
||||
assert_eq!(c.sampling.top_k, Some(40));
|
||||
assert_eq!(c.ignored, vec!["nonsense".to_owned()]);
|
||||
assert_eq!(c.experimental_speed_projection, Some(true));
|
||||
for (key, bad) in [
|
||||
("temperature", json!(-1)),
|
||||
("top_p", json!(0)),
|
||||
("min_p", json!(1.5)),
|
||||
("top_k", json!(0)),
|
||||
("top_k", json!(65)),
|
||||
("top_k", json!(1.5)),
|
||||
("presence_penalty", json!(-0.1)),
|
||||
("repetition_penalty", json!(0)),
|
||||
("penalty_last_n", json!(-1)),
|
||||
("seed", json!(0)),
|
||||
("seed", json!(true)),
|
||||
("experimental_speed_projection", json!(1)),
|
||||
] {
|
||||
assert!(
|
||||
sampling_defaults_from_config(&json!({ key: bad.clone() })).is_err(),
|
||||
"{key}={bad}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_wins_over_config_and_the_request_wins_over_both() {
|
||||
let config =
|
||||
sampling_defaults_from_config(&json!({"temperature": 0.3, "min_p": 0.1})).unwrap();
|
||||
let shared = clean_shared_defaults(&json!({"temperature": 0.9, "seed": 4})).unwrap();
|
||||
let merged = merged_defaults(&config, &shared);
|
||||
assert_eq!(merged.sampling.temperature, Some(0.9));
|
||||
assert_eq!(merged.sampling.min_p, Some(0.1));
|
||||
assert_eq!(merged.sampling.seed, Some(4));
|
||||
let request = RequestSampling {
|
||||
temperature: Some(0.0),
|
||||
..Default::default()
|
||||
};
|
||||
let effective = RequestSampling::overlay(&merged.sampling, &request);
|
||||
assert_eq!(effective.temperature, Some(0.0), "explicit 0 stays greedy");
|
||||
assert_eq!(effective.min_p, Some(0.1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn props_params_use_llama_server_names() {
|
||||
let config = sampling_defaults_from_config(
|
||||
&json!({"repetition_penalty": 1.1, "penalty_last_n": 64}),
|
||||
)
|
||||
.unwrap();
|
||||
let shared = clean_shared_defaults(&json!({"max_tokens": 512})).unwrap();
|
||||
let params = merged_defaults(&config, &shared).props_params(&shared);
|
||||
assert_eq!(
|
||||
params,
|
||||
json!({"repeat_penalty": 1.1, "repeat_last_n": 64, "n_predict": 512})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aliases_are_trimmed_deduplicated_and_never_the_model() {
|
||||
assert_eq!(
|
||||
normalize_aliases(&json!([" gpt ", "gpt", "", "m", "claude"]), "m"),
|
||||
Ok(vec!["gpt".to_owned(), "claude".to_owned()])
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_aliases(&json!("a, b ,a,,m"), "m"),
|
||||
Ok(vec!["a".to_owned(), "b".to_owned()])
|
||||
);
|
||||
assert_eq!(normalize_aliases(&Value::Null, "m"), Ok(vec![]));
|
||||
assert_eq!(
|
||||
normalize_aliases(&json!([1]), "m").unwrap_err(),
|
||||
"aliases=[1]: expected a list of model names"
|
||||
);
|
||||
assert!(normalize_aliases(&json!({"a": 1}), "m").is_err());
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//! Logits-selection stride (`include/strata/program/logits_selection.hpp`): which prompt positions
|
||||
//! keep their logits rows when a diagnostic dump asks for every `stride`-th row.
|
||||
//!
|
||||
//! "Storage selection only: callers must still condition on every input token." The functions are
|
||||
//! integer-exact transcriptions, golden-tested against the Original's header compiled on the host.
|
||||
|
||||
/// Positive decimal `int64`, with no sign, whitespace, suffix or overflow (`parse_stride`).
|
||||
pub fn parse_stride(text: &str) -> Option<i64> {
|
||||
let bytes = text.as_bytes();
|
||||
if bytes.first().is_none_or(|b| !b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
if !bytes.iter().all(u8::is_ascii_digit) {
|
||||
return None;
|
||||
}
|
||||
text.parse::<i64>().ok().filter(|v| *v > 0)
|
||||
}
|
||||
|
||||
/// Zero-based multiples of `stride`, followed by the final input position once.
|
||||
pub fn selected(position: i64, total: i64, stride: i64) -> bool {
|
||||
total > 0
|
||||
&& stride > 0
|
||||
&& position >= 0
|
||||
&& position < total
|
||||
&& (position % stride == 0 || position == total - 1)
|
||||
}
|
||||
|
||||
/// How many positions [`selected`] keeps.
|
||||
pub fn row_count(total: i64, stride: i64) -> i64 {
|
||||
if total > 0 && stride > 0 {
|
||||
(total - 1) / stride + 1 + i64::from((total - 1) % stride != 0)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_is_strict() {
|
||||
assert_eq!(parse_stride("1"), Some(1));
|
||||
assert_eq!(parse_stride("128"), Some(128));
|
||||
assert_eq!(parse_stride("9223372036854775807"), Some(i64::MAX));
|
||||
for bad in [
|
||||
"",
|
||||
"0",
|
||||
"00",
|
||||
"-1",
|
||||
"+1",
|
||||
" 1",
|
||||
"1 ",
|
||||
"1x",
|
||||
"x",
|
||||
"9223372036854775808",
|
||||
"1",
|
||||
] {
|
||||
assert_eq!(parse_stride(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_is_multiples_plus_the_last_position() {
|
||||
let kept: Vec<i64> = (0..10).filter(|p| selected(*p, 10, 4)).collect();
|
||||
assert_eq!(kept, vec![0, 4, 8, 9]);
|
||||
assert_eq!(row_count(10, 4), 4);
|
||||
assert_eq!(row_count(9, 4), 3);
|
||||
assert_eq!(row_count(1, 5), 1);
|
||||
assert_eq!(row_count(0, 5), 0);
|
||||
assert_eq!(row_count(5, 0), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn row_count_equals_the_number_of_selected_positions() {
|
||||
for total in 0..60 {
|
||||
for stride in 0..13 {
|
||||
let n = (-1..=total).filter(|p| selected(*p, total, stride)).count() as i64;
|
||||
assert_eq!(n, row_count(total, stride), "total {total} stride {stride}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
//! One request's `timings` in llama.cpp's names (what its clients show as speed), from the engine's
|
||||
//! own clock: `request_timings` of `serve/server.py`.
|
||||
//!
|
||||
//! `prompt_n` is what was read, `cache_n` what the conversation cache already held. Rounding is
|
||||
//! Python's `round(x, n)`: the exactly rounded decimal of the binary value, ties to even.
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
/// The engine's `DONE` figures for one request (`StrataEngine.last`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct Last {
|
||||
pub prompt_tokens: u64,
|
||||
/// The engine's own count of generated tokens (0 = not reported).
|
||||
pub generated: u64,
|
||||
pub prompt_ms: f64,
|
||||
pub decode_ms: f64,
|
||||
pub reused: Option<u64>,
|
||||
pub drafts_offered: Option<u64>,
|
||||
pub drafts_accepted: Option<u64>,
|
||||
}
|
||||
|
||||
/// Python's `round(x, digits)` for finite `x`.
|
||||
pub fn py_round(x: f64, digits: usize) -> f64 {
|
||||
format!("{x:.digits$}").parse().unwrap_or(x)
|
||||
}
|
||||
|
||||
fn rounded(x: f64, digits: usize) -> Value {
|
||||
Value::from(py_round(x, digits))
|
||||
}
|
||||
|
||||
/// `request_timings(prompt_tokens, generated, last)`. `generated` is the client-visible completion
|
||||
/// token count.
|
||||
pub fn request_timings(last: &Last, generated: u64) -> Value {
|
||||
let cache_n = last.reused.unwrap_or(0);
|
||||
let prompt_n = last.prompt_tokens.saturating_sub(cache_n);
|
||||
let (prompt_ms, decode_ms) = (last.prompt_ms, last.decode_ms);
|
||||
let decoded = if last.generated > 0 {
|
||||
last.generated
|
||||
} else {
|
||||
generated
|
||||
};
|
||||
let mut out = Map::new();
|
||||
out.insert("cache_n".into(), cache_n.into());
|
||||
out.insert("prompt_n".into(), prompt_n.into());
|
||||
out.insert("prompt_ms".into(), rounded(prompt_ms, 1));
|
||||
out.insert(
|
||||
"prompt_per_token_ms".into(),
|
||||
if prompt_n > 0 {
|
||||
rounded(prompt_ms / prompt_n as f64, 3)
|
||||
} else {
|
||||
Value::Null
|
||||
},
|
||||
);
|
||||
out.insert(
|
||||
"prompt_per_second".into(),
|
||||
if prompt_n > 0 && prompt_ms > 0.0 {
|
||||
rounded(prompt_n as f64 / (prompt_ms / 1000.0), 1)
|
||||
} else {
|
||||
Value::Null
|
||||
},
|
||||
);
|
||||
out.insert("predicted_n".into(), generated.into());
|
||||
out.insert("predicted_ms".into(), rounded(decode_ms, 1));
|
||||
out.insert(
|
||||
"predicted_per_token_ms".into(),
|
||||
if decoded > 0 {
|
||||
rounded(decode_ms / decoded as f64, 3)
|
||||
} else {
|
||||
Value::Null
|
||||
},
|
||||
);
|
||||
out.insert(
|
||||
"predicted_per_second".into(),
|
||||
if decoded > 0 && decode_ms > 0.0 {
|
||||
rounded(decoded as f64 / (decode_ms / 1000.0), 1)
|
||||
} else {
|
||||
Value::Null
|
||||
},
|
||||
);
|
||||
if let Some(offered) = last.drafts_offered {
|
||||
out.insert("draft_n".into(), offered.into());
|
||||
out.insert(
|
||||
"draft_n_accepted".into(),
|
||||
last.drafts_accepted.unwrap_or(0).into(),
|
||||
);
|
||||
}
|
||||
Value::Object(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn python_rounding_is_exact_and_ties_to_even() {
|
||||
assert_eq!(py_round(2.675, 2), 2.67); // the binary value is below the tie
|
||||
assert_eq!(py_round(0.25, 1), 0.2); // an exact tie goes to even
|
||||
assert_eq!(py_round(0.35, 1), 0.3); // 0.35 is below the tie in binary
|
||||
assert_eq!(py_round(1234.5678, 1), 1234.6);
|
||||
assert_eq!(py_round(0.0, 3), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timings_use_llama_cpp_names() {
|
||||
let t = request_timings(
|
||||
&Last {
|
||||
prompt_tokens: 100,
|
||||
generated: 50,
|
||||
prompt_ms: 250.0,
|
||||
decode_ms: 1000.0,
|
||||
reused: Some(60),
|
||||
drafts_offered: Some(10),
|
||||
drafts_accepted: Some(7),
|
||||
},
|
||||
50,
|
||||
);
|
||||
assert_eq!(t["cache_n"], 60);
|
||||
assert_eq!(t["prompt_n"], 40);
|
||||
assert_eq!(t["prompt_per_token_ms"], 6.25);
|
||||
assert_eq!(t["prompt_per_second"], 160.0);
|
||||
assert_eq!(t["predicted_per_second"], 50.0);
|
||||
assert_eq!(t["draft_n"], 10);
|
||||
assert_eq!(t["draft_n_accepted"], 7);
|
||||
let none = request_timings(&Last::default(), 0);
|
||||
assert!(none["prompt_per_token_ms"].is_null());
|
||||
assert!(none.get("draft_n").is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,500 @@
|
||||
//! The image path of the Original, host side: SVE1 embedding files, the M-RoPE position table, image
|
||||
//! sources, and the `<|image_pad|>` expansion of a prompt (`Service.prepare` in `serve/server.py`,
|
||||
//! `GENI` handling in `src/program/generate.cpp`, `serve/frontend.py` `_image_source`/`images_of`).
|
||||
//!
|
||||
//! * [`parse_embeddings`] and [`build_positions`] are transcriptions of the verbatim block of
|
||||
//! `generate.cpp` (`if (geni || !mrope_identity)`), golden-tested against that block compiled on
|
||||
//! the host (`oracle/gen_vision_fixtures.cpp`).
|
||||
//! * Qwen's interleaved M-RoPE gives each rotated pair a position from one of three streams (time
|
||||
//! `t`, height `h`, width `w`): text has `t = h = w`, an image's tokens share `t = p` and differ in
|
||||
//! `h = p + y`, `w = p + x`, and the text after it continues at `p + max(nx, ny)`.
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// `'SVE1'` little-endian: the magic of a strata-vision record.
|
||||
pub const SVE1_MAGIC: i32 = 0x3145_5653;
|
||||
|
||||
/// Token id of `<|image_pad|>` (`qwen4exp.ple.image_token_id`).
|
||||
pub const IMAGE_PAD_ID: i64 = 248_056;
|
||||
|
||||
/// One image of an embeddings file: `n` rows of `n_embd` floats laid out on an `nx` x `ny` grid.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Image {
|
||||
pub n: i64,
|
||||
pub nx: i64,
|
||||
pub ny: i64,
|
||||
/// Offset of its first float in [`Embeddings::rows`].
|
||||
pub offset: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Embeddings {
|
||||
pub images: Vec<Image>,
|
||||
pub rows: Vec<f32>,
|
||||
}
|
||||
|
||||
/// Parse one or more strata-vision records: `int32 'SVE1', n, nx, ny, n_embd`, then `n x n_embd`
|
||||
/// `f32`s. Records are in prompt order. Error text is the engine's.
|
||||
pub fn parse_embeddings(bytes: &[u8], n_embd: i64) -> Result<Embeddings, String> {
|
||||
let bad = || format!("bad embeddings file (expected strata-vision records of width {n_embd})");
|
||||
let mut out = Embeddings::default();
|
||||
let mut at = 0usize;
|
||||
while at < bytes.len() {
|
||||
let Some(header) = bytes.get(at..at + 20) else {
|
||||
return Err(bad());
|
||||
};
|
||||
let word =
|
||||
|i: usize| i32::from_le_bytes(header[4 * i..4 * i + 4].try_into().expect("4 bytes"));
|
||||
let (magic, n, nx, ny, width) = (word(0), word(1), word(2), word(3), word(4));
|
||||
if magic != SVE1_MAGIC
|
||||
|| n < 1
|
||||
|| nx < 1
|
||||
|| ny < 1
|
||||
|| i64::from(nx) * i64::from(ny) != i64::from(n)
|
||||
|| i64::from(width) != n_embd
|
||||
{
|
||||
return Err(bad());
|
||||
}
|
||||
at += 20;
|
||||
let count = usize::try_from(i64::from(n) * i64::from(width)).map_err(|_| bad())?;
|
||||
let Some(data) = bytes.get(at..at + count * 4) else {
|
||||
return Err("short embeddings file".to_owned());
|
||||
};
|
||||
let offset = out.rows.len();
|
||||
out.rows.extend(
|
||||
data.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|c| f32::from_le_bytes(*c)),
|
||||
);
|
||||
at += count * 4;
|
||||
out.images.push(Image {
|
||||
n: i64::from(n),
|
||||
nx: i64::from(nx),
|
||||
ny: i64::from(ny),
|
||||
offset,
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// FNV-1a (`fnv1a` in generate.cpp), continuing from `h`.
|
||||
pub fn fnv1a(data: &[u8], mut h: u64) -> u64 {
|
||||
for byte in data {
|
||||
h ^= u64::from(*byte);
|
||||
h = h.wrapping_mul(1_099_511_628_211);
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
const FNV_OFFSET: u64 = 1_469_598_103_934_665_603;
|
||||
|
||||
/// What the request's pictures look like to the conversation cache: where each starts and a hash of
|
||||
/// its grid and embeddings.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ImageKey {
|
||||
pub start: i64,
|
||||
pub hash: u64,
|
||||
}
|
||||
|
||||
/// The `[cells][3]` `(t, h, w)` rotary position table, the embedding row each prompt token takes
|
||||
/// (`None` for ordinary tokens) and the picture keys.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Positions {
|
||||
pub table: Vec<[i32; 3]>,
|
||||
/// Offset into [`Embeddings::rows`] of the row that replaces the token's embedding.
|
||||
pub row_offset: Vec<Option<usize>>,
|
||||
pub images: Vec<ImageKey>,
|
||||
}
|
||||
|
||||
/// The identity table of a text request: every stream is the cell index.
|
||||
pub fn identity_table(cells: usize) -> Vec<[i32; 3]> {
|
||||
(0..cells)
|
||||
.map(|c| {
|
||||
let c = c as i32;
|
||||
[c, c, c]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Positions for every cell a request can reach. `ids` are the prompt token ids with one
|
||||
/// `image_pad` per image row; `cells` is the table length (`max_context + 64`).
|
||||
pub fn build_positions(
|
||||
ids: &[i64],
|
||||
cells: usize,
|
||||
embeddings: &Embeddings,
|
||||
n_embd: i64,
|
||||
image_pad: i64,
|
||||
) -> Result<Positions, String> {
|
||||
let n = ids.len() as i64;
|
||||
let mut table = identity_table(cells);
|
||||
let mut row_offset: Vec<Option<usize>> = vec![None; ids.len()];
|
||||
let mut keys = Vec::new();
|
||||
let put = |table: &mut Vec<[i32; 3]>, c: i64, t: i64, h: i64, w: i64| -> Result<(), String> {
|
||||
let slot = usize::try_from(c)
|
||||
.ok()
|
||||
.and_then(|c| table.get_mut(c))
|
||||
.ok_or_else(|| "the prompt is longer than the position table".to_owned())?;
|
||||
*slot = [t as i32, h as i32, w as i32];
|
||||
Ok(())
|
||||
};
|
||||
let (mut p, mut i, mut k) = (0i64, 0i64, 0usize);
|
||||
while i < n {
|
||||
if ids[i as usize] != image_pad {
|
||||
put(&mut table, i, p, p, p)?;
|
||||
p += 1;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let Some(image) = embeddings.images.get(k) else {
|
||||
return Err("the prompt has more images than the embeddings file".into());
|
||||
};
|
||||
k += 1;
|
||||
let float_bytes = |from: usize, count: usize| -> Vec<u8> {
|
||||
embeddings.rows[from..from + count]
|
||||
.iter()
|
||||
.flat_map(|f| f.to_le_bytes())
|
||||
.collect()
|
||||
};
|
||||
let grid: Vec<u8> = [image.n, image.nx, image.ny]
|
||||
.iter()
|
||||
.flat_map(|v| v.to_le_bytes())
|
||||
.collect();
|
||||
let mut hash = fnv1a(&grid, FNV_OFFSET);
|
||||
let count = usize::try_from(image.n * n_embd).map_err(|_| "bad image size".to_owned())?;
|
||||
hash = fnv1a(&float_bytes(image.offset, count), hash);
|
||||
keys.push(ImageKey { start: i, hash });
|
||||
for j in 0..image.n {
|
||||
if i + j >= n || ids[(i + j) as usize] != image_pad {
|
||||
return Err(format!(
|
||||
"image {k} has {} rows but fewer <|image_pad|> tokens",
|
||||
image.n
|
||||
));
|
||||
}
|
||||
}
|
||||
for j in 0..image.n {
|
||||
let (y, x) = (j / image.nx, j % image.nx);
|
||||
put(&mut table, i + j, p, p + y, p + x)?;
|
||||
row_offset[(i + j) as usize] = Some(image.offset + (j * n_embd) as usize);
|
||||
}
|
||||
i += image.n;
|
||||
p += image.nx.max(image.ny);
|
||||
}
|
||||
if k != embeddings.images.len() {
|
||||
return Err("the embeddings file has more images than the prompt".into());
|
||||
}
|
||||
if n > 0 && ids[(n - 1) as usize] == image_pad {
|
||||
return Err("the prompt cannot end in an image".into());
|
||||
}
|
||||
for c in n..cells as i64 {
|
||||
put(&mut table, c, p + (c - n), p + (c - n), p + (c - n))?;
|
||||
}
|
||||
Ok(Positions {
|
||||
table,
|
||||
row_offset,
|
||||
images: keys,
|
||||
})
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ sources
|
||||
|
||||
/// Content-part types that carry an image (`IMAGE_PARTS`).
|
||||
pub const IMAGE_PARTS: [&str; 3] = ["image_url", "input_image", "image"];
|
||||
|
||||
pub fn is_image_part(part: &Value) -> bool {
|
||||
part.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|kind| IMAGE_PARTS.contains(&kind))
|
||||
}
|
||||
|
||||
/// `_image_source`: an image part's source as one string - a `data:` URL, an http(s) URL or a local
|
||||
/// path. OpenAI `{"type": "image_url", "image_url": {"url": ...}}` (or `"image_url": "..."`),
|
||||
/// Responses `{"type": "input_image", "image_url": ...}`, Anthropic `{"type": "image", "source":
|
||||
/// {"type": "base64", ...}}` or `{"source": {"type": "url", "url": ...}}`.
|
||||
pub fn image_source(part: &Value) -> String {
|
||||
let text = |value: Option<&Value>| value.and_then(Value::as_str).unwrap_or("").to_owned();
|
||||
if part.get("type").and_then(Value::as_str) == Some("image") {
|
||||
let source = part.get("source").filter(|v| v.is_object());
|
||||
let get = |key: &str| source.and_then(|s| s.get(key));
|
||||
if get("type").and_then(Value::as_str) == Some("base64") {
|
||||
let media = get("media_type")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("image/png");
|
||||
return format!("data:{media};base64,{}", text(get("data")));
|
||||
}
|
||||
let url = text(get("url"));
|
||||
return if url.is_empty() {
|
||||
text(get("path"))
|
||||
} else {
|
||||
url
|
||||
};
|
||||
}
|
||||
match part.get("image_url") {
|
||||
Some(Value::Object(object)) => text(object.get("url")),
|
||||
other => text(other),
|
||||
}
|
||||
}
|
||||
|
||||
/// Python's `base64.b64decode(s)` (non-strict `binascii.a2b_base64`): characters outside the alphabet
|
||||
/// (and `\r`, `\n`, space) are skipped; a complete pad sequence ends the data; what is left over
|
||||
/// is an error with CPython's wording.
|
||||
pub fn b64decode(text: &str) -> Result<Vec<u8>, String> {
|
||||
let value = |c: u8| -> Option<u8> {
|
||||
match c {
|
||||
b'A'..=b'Z' => Some(c - b'A'),
|
||||
b'a'..=b'z' => Some(c - b'a' + 26),
|
||||
b'0'..=b'9' => Some(c - b'0' + 52),
|
||||
b'+' => Some(62),
|
||||
b'/' => Some(63),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
let mut out = Vec::with_capacity(text.len() / 4 * 3);
|
||||
let (mut quad, mut left, mut pads) = (0u8, 0u8, 0u8);
|
||||
for byte in text.bytes() {
|
||||
if byte > 0x7f || matches!(byte, b'\r' | b'\n' | b' ') {
|
||||
continue;
|
||||
}
|
||||
if byte == b'=' {
|
||||
pads += 1;
|
||||
if quad >= 2 && quad + pads >= 4 {
|
||||
return Ok(out); // a complete pad sequence: no more input is read
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some(v) = value(byte) else { continue };
|
||||
pads = 0;
|
||||
match quad {
|
||||
0 => {
|
||||
quad = 1;
|
||||
left = v;
|
||||
}
|
||||
1 => {
|
||||
quad = 2;
|
||||
out.push((left << 2) | (v >> 4));
|
||||
left = v & 0x0f;
|
||||
}
|
||||
2 => {
|
||||
quad = 3;
|
||||
out.push((left << 4) | (v >> 2));
|
||||
left = v & 0x03;
|
||||
}
|
||||
_ => {
|
||||
quad = 0;
|
||||
out.push((left << 6) | v);
|
||||
left = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
match quad {
|
||||
0 => Ok(out),
|
||||
1 => Err(format!(
|
||||
"Invalid base64-encoded string: number of data characters ({}) cannot be 1 more than a multiple of 4",
|
||||
out.len() / 3 * 4 + 1
|
||||
)),
|
||||
_ => Err("Incorrect padding".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `Vision.normalize` for the formats `strata-vision`'s decoder reads directly (JPEG, PNG, BMP,
|
||||
/// GIF). Anything else needs an image library to convert it to PNG first.
|
||||
pub fn is_native_image_format(data: &[u8]) -> bool {
|
||||
data.starts_with(&[0xFF, 0xD8, 0xFF])
|
||||
|| data.starts_with(b"\x89PNG\r\n\x1a\n")
|
||||
|| data.starts_with(b"BM")
|
||||
|| data.starts_with(b"GIF87a")
|
||||
|| data.starts_with(b"GIF89a")
|
||||
}
|
||||
|
||||
/// `Service.prepare`'s pad expansion: one `<|image_pad|>` per image becomes `counts[k]` of them. Only
|
||||
/// the markers the template writes for an image (right after `<|vision_start|>`) are images; the
|
||||
/// same text inside a message is kept as `literal` plain text (the ids of the pad text tokenized
|
||||
/// without special parsing).
|
||||
pub fn expand_image_pads(
|
||||
ids: &[u32],
|
||||
pad: u32,
|
||||
start: u32,
|
||||
literal: &[u32],
|
||||
counts: &[usize],
|
||||
) -> Result<Vec<u32>, String> {
|
||||
let mut out = Vec::with_capacity(ids.len());
|
||||
let mut k = 0usize;
|
||||
for (j, id) in ids.iter().enumerate() {
|
||||
if *id == pad && j > 0 && ids[j - 1] == start && k < counts.len() {
|
||||
out.extend(std::iter::repeat_n(pad, counts[k]));
|
||||
k += 1;
|
||||
} else if *id == pad {
|
||||
out.extend_from_slice(literal);
|
||||
} else {
|
||||
out.push(*id);
|
||||
}
|
||||
}
|
||||
if k != counts.len() {
|
||||
return Err("the prompt and its images do not match".into());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn record(n: i32, nx: i32, ny: i32, width: i32, seed: f32) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
for v in [SVE1_MAGIC, n, nx, ny, width] {
|
||||
out.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
for i in 0..n * width {
|
||||
out.extend_from_slice(&(seed + i as f32 * 0.5).to_le_bytes());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_positions_for_text() {
|
||||
let ids: Vec<i64> = vec![5, 6, 7];
|
||||
let positions = build_positions(&ids, 8, &Embeddings::default(), 4, IMAGE_PAD_ID).unwrap();
|
||||
assert_eq!(positions.table, identity_table(8));
|
||||
assert!(positions.images.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_shares_t_and_text_continues_after_its_larger_side() {
|
||||
let file = record(6, 3, 2, 4, 1.0);
|
||||
let embeddings = parse_embeddings(&file, 4).unwrap();
|
||||
let p = IMAGE_PAD_ID;
|
||||
let ids = vec![1, p, p, p, p, p, p, 9];
|
||||
let positions = build_positions(&ids, 12, &embeddings, 4, p).unwrap();
|
||||
assert_eq!(positions.table[0], [0, 0, 0]);
|
||||
assert_eq!(positions.table[1], [1, 1, 1]);
|
||||
assert_eq!(positions.table[3], [1, 1, 3]);
|
||||
assert_eq!(positions.table[4], [1, 2, 1]);
|
||||
assert_eq!(positions.table[6], [1, 2, 3]);
|
||||
// the text after the image: p = 1 + max(3, 2) = 4
|
||||
assert_eq!(positions.table[7], [4, 4, 4]);
|
||||
assert_eq!(positions.table[8], [5, 5, 5]);
|
||||
assert_eq!(positions.row_offset[1], Some(0));
|
||||
assert_eq!(positions.row_offset[2], Some(4));
|
||||
assert_eq!(positions.row_offset[0], None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_failure_has_the_engines_words() {
|
||||
let one = record(1, 1, 1, 4, 1.0);
|
||||
let p = IMAGE_PAD_ID;
|
||||
let embed = |bytes: &[u8]| parse_embeddings(bytes, 4);
|
||||
assert_eq!(
|
||||
embed(&one[..12]).unwrap_err(),
|
||||
"bad embeddings file (expected strata-vision records of width 4)"
|
||||
);
|
||||
assert_eq!(
|
||||
embed(&one[..one.len() - 3]).unwrap_err(),
|
||||
"short embeddings file"
|
||||
);
|
||||
assert!(embed(&record(1, 1, 1, 8, 1.0)).is_err());
|
||||
assert!(embed(&record(6, 3, 3, 4, 1.0)).is_err());
|
||||
let embeddings = embed(&one).unwrap();
|
||||
assert_eq!(
|
||||
build_positions(&[1, p, 2, p, 3], 16, &embeddings, 4, p).unwrap_err(),
|
||||
"the prompt has more images than the embeddings file"
|
||||
);
|
||||
assert_eq!(
|
||||
build_positions(&[1, 2], 16, &embeddings, 4, p).unwrap_err(),
|
||||
"the embeddings file has more images than the prompt"
|
||||
);
|
||||
assert_eq!(
|
||||
build_positions(&[1, p], 16, &embeddings, 4, p).unwrap_err(),
|
||||
"the prompt cannot end in an image"
|
||||
);
|
||||
let six = embed(&record(6, 3, 2, 4, 0.0)).unwrap();
|
||||
assert_eq!(
|
||||
build_positions(&[1, p, p, 2, 3], 16, &six, 4, p).unwrap_err(),
|
||||
"image 1 has 6 rows but fewer <|image_pad|> tokens"
|
||||
);
|
||||
assert_eq!(
|
||||
build_positions(&[1, 2, 3, 4, 5], 3, &Embeddings::default(), 4, p).unwrap_err(),
|
||||
"the prompt is longer than the position table"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sources_follow_the_frontends() {
|
||||
assert_eq!(
|
||||
image_source(&json!({"type": "image_url", "image_url": {"url": "https://x/y.png"}})),
|
||||
"https://x/y.png"
|
||||
);
|
||||
assert_eq!(
|
||||
image_source(&json!({"type": "image_url", "image_url": "data:abc"})),
|
||||
"data:abc"
|
||||
);
|
||||
assert_eq!(
|
||||
image_source(&json!({"type": "input_image", "image_url": "file:///a.png"})),
|
||||
"file:///a.png"
|
||||
);
|
||||
assert_eq!(
|
||||
image_source(
|
||||
&json!({"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "QQ=="}})
|
||||
),
|
||||
"data:image/jpeg;base64,QQ=="
|
||||
);
|
||||
assert_eq!(
|
||||
image_source(&json!({"type": "image", "source": {"type": "base64", "data": "QQ=="}})),
|
||||
"data:image/png;base64,QQ=="
|
||||
);
|
||||
assert_eq!(
|
||||
image_source(&json!({"type": "image", "source": {"type": "url", "url": "http://u"}})),
|
||||
"http://u"
|
||||
);
|
||||
assert_eq!(
|
||||
image_source(&json!({"type": "image", "source": {"path": "/p.png"}})),
|
||||
"/p.png"
|
||||
);
|
||||
assert_eq!(image_source(&json!({"type": "image"})), "");
|
||||
assert!(is_image_part(&json!({"type": "input_image"})));
|
||||
assert!(!is_image_part(&json!({"type": "text"})));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_markers_after_vision_start_are_images() {
|
||||
let (pad, start) = (9, 8);
|
||||
let ids = [1, start, pad, 7, pad, 2, start, pad, 3];
|
||||
let out = expand_image_pads(&ids, pad, start, &[50, 51], &[3, 2]).unwrap();
|
||||
assert_eq!(out, vec![1, 8, 9, 9, 9, 7, 50, 51, 2, 8, 9, 9, 3]);
|
||||
// More markers than images: the surplus marker stays plain text (as in the Original).
|
||||
assert_eq!(
|
||||
expand_image_pads(&ids, pad, start, &[50], &[3]).unwrap(),
|
||||
vec![1, 8, 9, 9, 9, 7, 50, 2, 8, 50, 3]
|
||||
);
|
||||
// More images than markers is the error.
|
||||
assert_eq!(
|
||||
expand_image_pads(&ids, pad, start, &[50], &[1, 1, 1]).unwrap_err(),
|
||||
"the prompt and its images do not match"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_formats_pass_through() {
|
||||
assert!(is_native_image_format(&[0xFF, 0xD8, 0xFF, 0xE0]));
|
||||
assert!(is_native_image_format(b"\x89PNG\r\n\x1a\nrest"));
|
||||
assert!(is_native_image_format(b"BM...."));
|
||||
assert!(is_native_image_format(b"GIF89a.."));
|
||||
assert!(!is_native_image_format(b"RIFF....WEBP"));
|
||||
assert!(!is_native_image_format(b""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base64_matches_pythons_lenient_decoder() {
|
||||
assert_eq!(b64decode("QQ==").unwrap(), b"A");
|
||||
assert_eq!(b64decode("QUI=").unwrap(), b"AB");
|
||||
assert_eq!(b64decode("QUJD").unwrap(), b"ABC");
|
||||
assert_eq!(b64decode("QU\nJD").unwrap(), b"ABC");
|
||||
assert_eq!(b64decode("").unwrap(), b"");
|
||||
assert_eq!(b64decode("QQ").unwrap_err(), "Incorrect padding");
|
||||
assert!(
|
||||
b64decode("Q")
|
||||
.unwrap_err()
|
||||
.contains("1 more than a multiple of 4")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
//! The stall watchdog (issue #29 of the Original): `include/strata/core/progress.hpp` and the
|
||||
//! watchdog thread in `src/program/generate.cpp` (`--serve`).
|
||||
//!
|
||||
//! The engine's host loop and the GPU wait on each other through flags; a protocol bug there does
|
||||
//! not crash, it spins. A request whose heartbeat stops for `STRATA_WATCHDOG_S` seconds (default 60,
|
||||
//! `0` = off) ends the engine with the stage it was stuck in, so the server starts it again instead
|
||||
//! of hanging. Tokens, prompt chunks and verify windows *beat*; `ticks` (layers served) tells a slow
|
||||
//! step from a stopped one in the report.
|
||||
//!
|
||||
//! [`StallWatchdog`] is the thread's decision logic with injected time: poll it once a second with
|
||||
//! a snapshot of the progress counters. [`Stage`] formats the stage text of the report.
|
||||
|
||||
/// `STRATA_WATCHDOG_S` default: one step (a prompt layer, a verify window) takes seconds.
|
||||
pub const DEFAULT_LIMIT_S: i64 = 60;
|
||||
|
||||
/// C `atoi`: optional whitespace and sign, then digits; anything else is `0`.
|
||||
pub fn atoi(text: &str) -> i64 {
|
||||
let trimmed = text.trim_start();
|
||||
let (negative, digits) = match trimmed.as_bytes().first() {
|
||||
Some(b'-') => (true, &trimmed[1..]),
|
||||
Some(b'+') => (false, &trimmed[1..]),
|
||||
_ => (false, trimmed),
|
||||
};
|
||||
let mut value: i64 = 0;
|
||||
for byte in digits.bytes() {
|
||||
if !byte.is_ascii_digit() {
|
||||
break;
|
||||
}
|
||||
value = value
|
||||
.saturating_mul(10)
|
||||
.saturating_add(i64::from(byte - b'0'));
|
||||
}
|
||||
if negative { -value } else { value }
|
||||
}
|
||||
|
||||
/// The limit in seconds from the environment variable's value (`None` = unset); `<= 0` disables.
|
||||
pub fn limit_from_env(value: Option<&str>) -> i64 {
|
||||
value.map_or(DEFAULT_LIMIT_S, atoi)
|
||||
}
|
||||
|
||||
/// The counters the engine publishes (`core::Progress`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Counters {
|
||||
/// Heartbeats: tokens, prompt chunks, verify windows.
|
||||
pub beats: u64,
|
||||
/// A request is running.
|
||||
pub busy: bool,
|
||||
/// Layers served.
|
||||
pub ticks: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Verdict {
|
||||
Healthy,
|
||||
/// No heartbeat for the limit during a request: stop the engine. `layers_since` is the number
|
||||
/// of layers served since the last beat (0 = stopped, more = slow).
|
||||
Stalled {
|
||||
quiet_ms: u64,
|
||||
layers_since: u64,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct StallWatchdog {
|
||||
limit_ms: Option<u64>,
|
||||
last_beats: u64,
|
||||
ticks_at: u64,
|
||||
since_ms: u64,
|
||||
}
|
||||
|
||||
impl StallWatchdog {
|
||||
/// `limit_s <= 0` builds a watchdog that never fires (the Original starts no thread then).
|
||||
pub fn new(limit_s: i64, now_ms: u64, counters: Counters) -> Self {
|
||||
Self {
|
||||
limit_ms: u64::try_from(limit_s)
|
||||
.ok()
|
||||
.filter(|s| *s > 0)
|
||||
.map(|s| s.saturating_mul(1000)),
|
||||
last_beats: counters.beats,
|
||||
ticks_at: counters.ticks,
|
||||
since_ms: now_ms,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn enabled(&self) -> bool {
|
||||
self.limit_ms.is_some()
|
||||
}
|
||||
|
||||
/// One poll (the Original sleeps one second between polls).
|
||||
pub fn poll(&mut self, now_ms: u64, counters: Counters) -> Verdict {
|
||||
let Some(limit) = self.limit_ms else {
|
||||
return Verdict::Healthy;
|
||||
};
|
||||
if !counters.busy || counters.beats != self.last_beats {
|
||||
self.last_beats = counters.beats;
|
||||
self.ticks_at = counters.ticks;
|
||||
self.since_ms = now_ms;
|
||||
return Verdict::Healthy;
|
||||
}
|
||||
let quiet = now_ms.saturating_sub(self.since_ms);
|
||||
if quiet < limit {
|
||||
return Verdict::Healthy;
|
||||
}
|
||||
Verdict::Stalled {
|
||||
quiet_ms: quiet,
|
||||
layers_since: counters.ticks.wrapping_sub(self.ticks_at),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `stage_text()`: `"<where> <detail>"`, plus the prompt chunk a batched read is in (#251).
|
||||
pub fn stage_text(location: &str, detail: i64, chunk: i64) -> String {
|
||||
let mut text = format!("{location} {detail}");
|
||||
if chunk >= 0 {
|
||||
text.push_str(&format!(" of the prompt chunk from token {chunk}"));
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// The line the watchdog prints before it stops the engine.
|
||||
pub fn stall_message(limit_s: i64, stage: &str) -> String {
|
||||
format!(
|
||||
"strata serve: no progress for {limit_s} s during a request ({stage}) - stopping the engine so the server starts it again (issue #29)"
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn busy(beats: u64, ticks: u64) -> Counters {
|
||||
Counters {
|
||||
beats,
|
||||
busy: true,
|
||||
ticks,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn atoi_follows_c() {
|
||||
for (text, want) in [
|
||||
("60", 60),
|
||||
(" 12abc", 12),
|
||||
("-5", -5),
|
||||
("+7", 7),
|
||||
("abc", 0),
|
||||
("", 0),
|
||||
("0", 0),
|
||||
("3.9", 3),
|
||||
("99999999999999999999999", i64::MAX),
|
||||
] {
|
||||
assert_eq!(atoi(text), want, "{text:?}");
|
||||
}
|
||||
assert_eq!(limit_from_env(None), 60);
|
||||
assert_eq!(limit_from_env(Some("0")), 0);
|
||||
assert_eq!(limit_from_env(Some("x")), 0);
|
||||
assert_eq!(limit_from_env(Some("5")), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fires_only_after_the_limit_of_silence_during_a_request() {
|
||||
let mut dog = StallWatchdog::new(3, 0, busy(0, 0));
|
||||
assert_eq!(dog.poll(1000, busy(0, 0)), Verdict::Healthy);
|
||||
assert_eq!(dog.poll(2000, busy(0, 5)), Verdict::Healthy);
|
||||
assert_eq!(dog.poll(2999, busy(0, 9)), Verdict::Healthy);
|
||||
assert_eq!(
|
||||
dog.poll(3000, busy(0, 9)),
|
||||
Verdict::Stalled {
|
||||
quiet_ms: 3000,
|
||||
layers_since: 9
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_beat_restarts_the_clock_and_the_layer_baseline() {
|
||||
let mut dog = StallWatchdog::new(2, 0, busy(0, 0));
|
||||
assert_eq!(dog.poll(1900, busy(1, 40)), Verdict::Healthy);
|
||||
assert_eq!(dog.poll(3800, busy(1, 40)), Verdict::Healthy);
|
||||
assert_eq!(
|
||||
dog.poll(3900, busy(1, 40)),
|
||||
Verdict::Stalled {
|
||||
quiet_ms: 2000,
|
||||
layers_since: 0
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idle_engine_never_stalls_and_resets_the_baseline() {
|
||||
let mut dog = StallWatchdog::new(2, 0, Counters::default());
|
||||
for second in 1..100 {
|
||||
let idle = Counters {
|
||||
beats: 0,
|
||||
busy: false,
|
||||
ticks: second,
|
||||
};
|
||||
assert_eq!(dog.poll(second * 1000, idle), Verdict::Healthy);
|
||||
}
|
||||
// The clock restarts at the last idle poll (99 s), not at the request's start: the Original polls once a
|
||||
// second, so a request can be flagged up to one poll early.
|
||||
assert_eq!(dog.poll(100_000, busy(0, 100)), Verdict::Healthy);
|
||||
assert_eq!(dog.poll(100_999, busy(0, 100)), Verdict::Healthy);
|
||||
assert!(matches!(
|
||||
dog.poll(101_000, busy(0, 100)),
|
||||
Verdict::Stalled { .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_disabled_watchdog_never_fires() {
|
||||
for limit in [0, -1] {
|
||||
let mut dog = StallWatchdog::new(limit, 0, busy(0, 0));
|
||||
assert!(!dog.enabled());
|
||||
assert_eq!(dog.poll(10_000_000, busy(0, 0)), Verdict::Healthy);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stage_text_names_the_prompt_chunk() {
|
||||
assert_eq!(stage_text("layer", 12, -1), "layer 12");
|
||||
assert_eq!(
|
||||
stage_text("prefill", 3, 8192),
|
||||
"prefill 3 of the prompt chunk from token 8192"
|
||||
);
|
||||
assert_eq!(
|
||||
stall_message(60, "layer 12"),
|
||||
"strata serve: no progress for 60 s during a request (layer 12) - stopping the engine so the server starts it again (issue #29)"
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,172 @@
|
||||
{
|
||||
"source": "include/strata/program/logits_selection.hpp + core/progress.hpp + the watchdog thread of src/program/generate.cpp (host build)",
|
||||
"parse": [
|
||||
{"text": "1", "ok": true, "value": 1},
|
||||
{"text": "2", "ok": true, "value": 2},
|
||||
{"text": "128", "ok": true, "value": 128},
|
||||
{"text": "9223372036854775807", "ok": true, "value": 9223372036854775807},
|
||||
{"text": "9223372036854775808", "ok": false, "value": -777},
|
||||
{"text": "0", "ok": false, "value": -777},
|
||||
{"text": "00", "ok": false, "value": -777},
|
||||
{"text": "007", "ok": true, "value": 7},
|
||||
{"text": "-1", "ok": false, "value": -777},
|
||||
{"text": "+1", "ok": false, "value": -777},
|
||||
{"text": " 1", "ok": false, "value": -777},
|
||||
{"text": "1 ", "ok": false, "value": -777},
|
||||
{"text": "1x", "ok": false, "value": -777},
|
||||
{"text": "x", "ok": false, "value": -777},
|
||||
{"text": "", "ok": false, "value": -777},
|
||||
{"text": "1.5", "ok": false, "value": -777},
|
||||
{"text": "99999999999999999999", "ok": false, "value": -777},
|
||||
{"text": "12345678901234567890", "ok": false, "value": -777}
|
||||
],
|
||||
"selected": [
|
||||
{"total": -1, "stride": -1, "rows": 0, "kept": []},
|
||||
{"total": -1, "stride": 0, "rows": 0, "kept": []},
|
||||
{"total": -1, "stride": 1, "rows": 0, "kept": []},
|
||||
{"total": -1, "stride": 2, "rows": 0, "kept": []},
|
||||
{"total": -1, "stride": 3, "rows": 0, "kept": []},
|
||||
{"total": -1, "stride": 4, "rows": 0, "kept": []},
|
||||
{"total": -1, "stride": 7, "rows": 0, "kept": []},
|
||||
{"total": -1, "stride": 10, "rows": 0, "kept": []},
|
||||
{"total": -1, "stride": 64, "rows": 0, "kept": []},
|
||||
{"total": -1, "stride": 1000, "rows": 0, "kept": []},
|
||||
{"total": 0, "stride": -1, "rows": 0, "kept": []},
|
||||
{"total": 0, "stride": 0, "rows": 0, "kept": []},
|
||||
{"total": 0, "stride": 1, "rows": 0, "kept": []},
|
||||
{"total": 0, "stride": 2, "rows": 0, "kept": []},
|
||||
{"total": 0, "stride": 3, "rows": 0, "kept": []},
|
||||
{"total": 0, "stride": 4, "rows": 0, "kept": []},
|
||||
{"total": 0, "stride": 7, "rows": 0, "kept": []},
|
||||
{"total": 0, "stride": 10, "rows": 0, "kept": []},
|
||||
{"total": 0, "stride": 64, "rows": 0, "kept": []},
|
||||
{"total": 0, "stride": 1000, "rows": 0, "kept": []},
|
||||
{"total": 1, "stride": -1, "rows": 0, "kept": []},
|
||||
{"total": 1, "stride": 0, "rows": 0, "kept": []},
|
||||
{"total": 1, "stride": 1, "rows": 1, "kept": [0]},
|
||||
{"total": 1, "stride": 2, "rows": 1, "kept": [0]},
|
||||
{"total": 1, "stride": 3, "rows": 1, "kept": [0]},
|
||||
{"total": 1, "stride": 4, "rows": 1, "kept": [0]},
|
||||
{"total": 1, "stride": 7, "rows": 1, "kept": [0]},
|
||||
{"total": 1, "stride": 10, "rows": 1, "kept": [0]},
|
||||
{"total": 1, "stride": 64, "rows": 1, "kept": [0]},
|
||||
{"total": 1, "stride": 1000, "rows": 1, "kept": [0]},
|
||||
{"total": 2, "stride": -1, "rows": 0, "kept": []},
|
||||
{"total": 2, "stride": 0, "rows": 0, "kept": []},
|
||||
{"total": 2, "stride": 1, "rows": 2, "kept": [0,1]},
|
||||
{"total": 2, "stride": 2, "rows": 2, "kept": [0,1]},
|
||||
{"total": 2, "stride": 3, "rows": 2, "kept": [0,1]},
|
||||
{"total": 2, "stride": 4, "rows": 2, "kept": [0,1]},
|
||||
{"total": 2, "stride": 7, "rows": 2, "kept": [0,1]},
|
||||
{"total": 2, "stride": 10, "rows": 2, "kept": [0,1]},
|
||||
{"total": 2, "stride": 64, "rows": 2, "kept": [0,1]},
|
||||
{"total": 2, "stride": 1000, "rows": 2, "kept": [0,1]},
|
||||
{"total": 5, "stride": -1, "rows": 0, "kept": []},
|
||||
{"total": 5, "stride": 0, "rows": 0, "kept": []},
|
||||
{"total": 5, "stride": 1, "rows": 5, "kept": [0,1,2,3,4]},
|
||||
{"total": 5, "stride": 2, "rows": 3, "kept": [0,2,4]},
|
||||
{"total": 5, "stride": 3, "rows": 3, "kept": [0,3,4]},
|
||||
{"total": 5, "stride": 4, "rows": 2, "kept": [0,4]},
|
||||
{"total": 5, "stride": 7, "rows": 2, "kept": [0,4]},
|
||||
{"total": 5, "stride": 10, "rows": 2, "kept": [0,4]},
|
||||
{"total": 5, "stride": 64, "rows": 2, "kept": [0,4]},
|
||||
{"total": 5, "stride": 1000, "rows": 2, "kept": [0,4]},
|
||||
{"total": 9, "stride": -1, "rows": 0, "kept": []},
|
||||
{"total": 9, "stride": 0, "rows": 0, "kept": []},
|
||||
{"total": 9, "stride": 1, "rows": 9, "kept": [0,1,2,3,4,5,6,7,8]},
|
||||
{"total": 9, "stride": 2, "rows": 5, "kept": [0,2,4,6,8]},
|
||||
{"total": 9, "stride": 3, "rows": 4, "kept": [0,3,6,8]},
|
||||
{"total": 9, "stride": 4, "rows": 3, "kept": [0,4,8]},
|
||||
{"total": 9, "stride": 7, "rows": 3, "kept": [0,7,8]},
|
||||
{"total": 9, "stride": 10, "rows": 2, "kept": [0,8]},
|
||||
{"total": 9, "stride": 64, "rows": 2, "kept": [0,8]},
|
||||
{"total": 9, "stride": 1000, "rows": 2, "kept": [0,8]},
|
||||
{"total": 10, "stride": -1, "rows": 0, "kept": []},
|
||||
{"total": 10, "stride": 0, "rows": 0, "kept": []},
|
||||
{"total": 10, "stride": 1, "rows": 10, "kept": [0,1,2,3,4,5,6,7,8,9]},
|
||||
{"total": 10, "stride": 2, "rows": 6, "kept": [0,2,4,6,8,9]},
|
||||
{"total": 10, "stride": 3, "rows": 4, "kept": [0,3,6,9]},
|
||||
{"total": 10, "stride": 4, "rows": 4, "kept": [0,4,8,9]},
|
||||
{"total": 10, "stride": 7, "rows": 3, "kept": [0,7,9]},
|
||||
{"total": 10, "stride": 10, "rows": 2, "kept": [0,9]},
|
||||
{"total": 10, "stride": 64, "rows": 2, "kept": [0,9]},
|
||||
{"total": 10, "stride": 1000, "rows": 2, "kept": [0,9]},
|
||||
{"total": 11, "stride": -1, "rows": 0, "kept": []},
|
||||
{"total": 11, "stride": 0, "rows": 0, "kept": []},
|
||||
{"total": 11, "stride": 1, "rows": 11, "kept": [0,1,2,3,4,5,6,7,8,9,10]},
|
||||
{"total": 11, "stride": 2, "rows": 6, "kept": [0,2,4,6,8,10]},
|
||||
{"total": 11, "stride": 3, "rows": 5, "kept": [0,3,6,9,10]},
|
||||
{"total": 11, "stride": 4, "rows": 4, "kept": [0,4,8,10]},
|
||||
{"total": 11, "stride": 7, "rows": 3, "kept": [0,7,10]},
|
||||
{"total": 11, "stride": 10, "rows": 2, "kept": [0,10]},
|
||||
{"total": 11, "stride": 64, "rows": 2, "kept": [0,10]},
|
||||
{"total": 11, "stride": 1000, "rows": 2, "kept": [0,10]},
|
||||
{"total": 64, "stride": -1, "rows": 0, "kept": []},
|
||||
{"total": 64, "stride": 0, "rows": 0, "kept": []},
|
||||
{"total": 64, "stride": 1, "rows": 64, "kept": [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63]},
|
||||
{"total": 64, "stride": 2, "rows": 33, "kept": [0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,63]},
|
||||
{"total": 64, "stride": 3, "rows": 22, "kept": [0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63]},
|
||||
{"total": 64, "stride": 4, "rows": 17, "kept": [0,4,8,12,16,20,24,28,32,36,40,44,48,52,56,60,63]},
|
||||
{"total": 64, "stride": 7, "rows": 10, "kept": [0,7,14,21,28,35,42,49,56,63]},
|
||||
{"total": 64, "stride": 10, "rows": 8, "kept": [0,10,20,30,40,50,60,63]},
|
||||
{"total": 64, "stride": 64, "rows": 2, "kept": [0,63]},
|
||||
{"total": 64, "stride": 1000, "rows": 2, "kept": [0,63]},
|
||||
{"total": 100, "stride": -1, "rows": 0, "kept": []},
|
||||
{"total": 100, "stride": 0, "rows": 0, "kept": []},
|
||||
{"total": 100, "stride": 1, "rows": 100, "kept": [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99]},
|
||||
{"total": 100, "stride": 2, "rows": 51, "kept": [0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,99]},
|
||||
{"total": 100, "stride": 3, "rows": 34, "kept": [0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99]},
|
||||
{"total": 100, "stride": 4, "rows": 26, "kept": [0,4,8,12,16,20,24,28,32,36,40,44,48,52,56,60,64,68,72,76,80,84,88,92,96,99]},
|
||||
{"total": 100, "stride": 7, "rows": 16, "kept": [0,7,14,21,28,35,42,49,56,63,70,77,84,91,98,99]},
|
||||
{"total": 100, "stride": 10, "rows": 11, "kept": [0,10,20,30,40,50,60,70,80,90,99]},
|
||||
{"total": 100, "stride": 64, "rows": 3, "kept": [0,64,99]},
|
||||
{"total": 100, "stride": 1000, "rows": 2, "kept": [0,99]}
|
||||
],
|
||||
"watchdog": [
|
||||
{"limit_s": 3, "steps": [
|
||||
{"at_ms": 1000, "beats": 0, "busy": true, "ticks": 0, "layers_since": -1},
|
||||
{"at_ms": 2000, "beats": 0, "busy": true, "ticks": 5, "layers_since": -1},
|
||||
{"at_ms": 2999, "beats": 0, "busy": true, "ticks": 9, "layers_since": -1},
|
||||
{"at_ms": 3000, "beats": 0, "busy": true, "ticks": 9, "layers_since": 9},
|
||||
{"at_ms": 4000, "beats": 0, "busy": true, "ticks": 9, "layers_since": 9}
|
||||
]},
|
||||
{"limit_s": 2, "steps": [
|
||||
{"at_ms": 1900, "beats": 1, "busy": true, "ticks": 40, "layers_since": -1},
|
||||
{"at_ms": 3800, "beats": 1, "busy": true, "ticks": 40, "layers_since": -1},
|
||||
{"at_ms": 3900, "beats": 1, "busy": true, "ticks": 40, "layers_since": 0},
|
||||
{"at_ms": 4000, "beats": 2, "busy": true, "ticks": 41, "layers_since": -1},
|
||||
{"at_ms": 5999, "beats": 2, "busy": true, "ticks": 41, "layers_since": -1},
|
||||
{"at_ms": 6000, "beats": 2, "busy": true, "ticks": 80, "layers_since": 39}
|
||||
]},
|
||||
{"limit_s": 2, "steps": [
|
||||
{"at_ms": 1000, "beats": 0, "busy": false, "ticks": 1, "layers_since": -1},
|
||||
{"at_ms": 2000, "beats": 0, "busy": false, "ticks": 2, "layers_since": -1},
|
||||
{"at_ms": 3000, "beats": 0, "busy": false, "ticks": 3, "layers_since": -1},
|
||||
{"at_ms": 100000, "beats": 0, "busy": true, "ticks": 100, "layers_since": 97},
|
||||
{"at_ms": 101999, "beats": 0, "busy": true, "ticks": 100, "layers_since": 97},
|
||||
{"at_ms": 102000, "beats": 0, "busy": true, "ticks": 100, "layers_since": 97}
|
||||
]},
|
||||
{"limit_s": 0, "steps": [
|
||||
{"at_ms": 1000, "beats": 0, "busy": true, "ticks": 0, "layers_since": -1},
|
||||
{"at_ms": 10000000, "beats": 0, "busy": true, "ticks": 0, "layers_since": -1}
|
||||
]},
|
||||
{"limit_s": -5, "steps": [
|
||||
{"at_ms": 1000, "beats": 0, "busy": true, "ticks": 0, "layers_since": -1},
|
||||
{"at_ms": 10000000, "beats": 0, "busy": true, "ticks": 0, "layers_since": -1}
|
||||
]},
|
||||
{"limit_s": 1, "steps": [
|
||||
{"at_ms": 1000, "beats": 0, "busy": true, "ticks": 3, "layers_since": 3},
|
||||
{"at_ms": 2000, "beats": 0, "busy": true, "ticks": 3, "layers_since": 3},
|
||||
{"at_ms": 3000, "beats": 1, "busy": true, "ticks": 3, "layers_since": -1},
|
||||
{"at_ms": 3999, "beats": 1, "busy": true, "ticks": 7, "layers_since": -1},
|
||||
{"at_ms": 4000, "beats": 1, "busy": true, "ticks": 7, "layers_since": 4}
|
||||
]},
|
||||
{"limit_s": 60, "steps": [
|
||||
{"at_ms": 59000, "beats": 0, "busy": true, "ticks": 0, "layers_since": -1},
|
||||
{"at_ms": 59999, "beats": 0, "busy": true, "ticks": 0, "layers_since": -1},
|
||||
{"at_ms": 60000, "beats": 0, "busy": true, "ticks": 12, "layers_since": 12},
|
||||
{"at_ms": 61000, "beats": 5, "busy": false, "ticks": 12, "layers_since": -1},
|
||||
{"at_ms": 200000, "beats": 5, "busy": true, "ticks": 12, "layers_since": 0}
|
||||
]}
|
||||
]
|
||||
}
|
||||
+2476
File diff suppressed because it is too large
Load Diff
+631
@@ -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": []
|
||||
}
|
||||
]
|
||||
}
|
||||
+776
@@ -0,0 +1,776 @@
|
||||
{
|
||||
"source": "serve/server.py request_timings + Service.set_aliases (real code)",
|
||||
"timings": [
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 250.0,
|
||||
"decode_ms": 1000.0,
|
||||
"generated": 50,
|
||||
"reused": 60
|
||||
},
|
||||
"prompt_tokens": 300,
|
||||
"generated": 50,
|
||||
"timings": {
|
||||
"cache_n": 60,
|
||||
"prompt_n": 240,
|
||||
"prompt_ms": 250.0,
|
||||
"prompt_per_token_ms": 1.042,
|
||||
"prompt_per_second": 960.0,
|
||||
"predicted_n": 50,
|
||||
"predicted_ms": 1000.0,
|
||||
"predicted_per_token_ms": 20.0,
|
||||
"predicted_per_second": 50.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 250.0,
|
||||
"decode_ms": 1000.0,
|
||||
"generated": 50,
|
||||
"reused": 60
|
||||
},
|
||||
"prompt_tokens": 10,
|
||||
"generated": 10,
|
||||
"timings": {
|
||||
"cache_n": 60,
|
||||
"prompt_n": 0,
|
||||
"prompt_ms": 250.0,
|
||||
"prompt_per_token_ms": null,
|
||||
"prompt_per_second": null,
|
||||
"predicted_n": 10,
|
||||
"predicted_ms": 1000.0,
|
||||
"predicted_per_token_ms": 20.0,
|
||||
"predicted_per_second": 50.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 250.0,
|
||||
"decode_ms": 1000.0,
|
||||
"generated": 50,
|
||||
"reused": 60
|
||||
},
|
||||
"prompt_tokens": 0,
|
||||
"generated": 0,
|
||||
"timings": {
|
||||
"cache_n": 60,
|
||||
"prompt_n": 0,
|
||||
"prompt_ms": 250.0,
|
||||
"prompt_per_token_ms": null,
|
||||
"prompt_per_second": null,
|
||||
"predicted_n": 0,
|
||||
"predicted_ms": 1000.0,
|
||||
"predicted_per_token_ms": 20.0,
|
||||
"predicted_per_second": 50.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 250.0,
|
||||
"decode_ms": 1000.0,
|
||||
"generated": 50,
|
||||
"reused": 60
|
||||
},
|
||||
"prompt_tokens": 50,
|
||||
"generated": 7,
|
||||
"timings": {
|
||||
"cache_n": 60,
|
||||
"prompt_n": 0,
|
||||
"prompt_ms": 250.0,
|
||||
"prompt_per_token_ms": null,
|
||||
"prompt_per_second": null,
|
||||
"predicted_n": 7,
|
||||
"predicted_ms": 1000.0,
|
||||
"predicted_per_token_ms": 20.0,
|
||||
"predicted_per_second": 50.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 0.0,
|
||||
"decode_ms": 0.0,
|
||||
"generated": 0,
|
||||
"reused": 0
|
||||
},
|
||||
"prompt_tokens": 300,
|
||||
"generated": 5,
|
||||
"timings": {
|
||||
"cache_n": 0,
|
||||
"prompt_n": 300,
|
||||
"prompt_ms": 0.0,
|
||||
"prompt_per_token_ms": 0.0,
|
||||
"prompt_per_second": null,
|
||||
"predicted_n": 5,
|
||||
"predicted_ms": 0.0,
|
||||
"predicted_per_token_ms": 0.0,
|
||||
"predicted_per_second": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 0.0,
|
||||
"decode_ms": 0.0,
|
||||
"generated": 0,
|
||||
"reused": 0
|
||||
},
|
||||
"prompt_tokens": 10,
|
||||
"generated": 10,
|
||||
"timings": {
|
||||
"cache_n": 0,
|
||||
"prompt_n": 10,
|
||||
"prompt_ms": 0.0,
|
||||
"prompt_per_token_ms": 0.0,
|
||||
"prompt_per_second": null,
|
||||
"predicted_n": 10,
|
||||
"predicted_ms": 0.0,
|
||||
"predicted_per_token_ms": 0.0,
|
||||
"predicted_per_second": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 0.0,
|
||||
"decode_ms": 0.0,
|
||||
"generated": 0,
|
||||
"reused": 0
|
||||
},
|
||||
"prompt_tokens": 0,
|
||||
"generated": 0,
|
||||
"timings": {
|
||||
"cache_n": 0,
|
||||
"prompt_n": 0,
|
||||
"prompt_ms": 0.0,
|
||||
"prompt_per_token_ms": null,
|
||||
"prompt_per_second": null,
|
||||
"predicted_n": 0,
|
||||
"predicted_ms": 0.0,
|
||||
"predicted_per_token_ms": null,
|
||||
"predicted_per_second": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 0.0,
|
||||
"decode_ms": 0.0,
|
||||
"generated": 0,
|
||||
"reused": 0
|
||||
},
|
||||
"prompt_tokens": 50,
|
||||
"generated": 7,
|
||||
"timings": {
|
||||
"cache_n": 0,
|
||||
"prompt_n": 50,
|
||||
"prompt_ms": 0.0,
|
||||
"prompt_per_token_ms": 0.0,
|
||||
"prompt_per_second": null,
|
||||
"predicted_n": 7,
|
||||
"predicted_ms": 0.0,
|
||||
"predicted_per_token_ms": 0.0,
|
||||
"predicted_per_second": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 12.34567,
|
||||
"decode_ms": 98.7654,
|
||||
"generated": 7,
|
||||
"reused": null
|
||||
},
|
||||
"prompt_tokens": 300,
|
||||
"generated": 7,
|
||||
"timings": {
|
||||
"cache_n": 0,
|
||||
"prompt_n": 300,
|
||||
"prompt_ms": 12.3,
|
||||
"prompt_per_token_ms": 0.041,
|
||||
"prompt_per_second": 24300.0,
|
||||
"predicted_n": 7,
|
||||
"predicted_ms": 98.8,
|
||||
"predicted_per_token_ms": 14.109,
|
||||
"predicted_per_second": 70.9
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 12.34567,
|
||||
"decode_ms": 98.7654,
|
||||
"generated": 7,
|
||||
"reused": null
|
||||
},
|
||||
"prompt_tokens": 10,
|
||||
"generated": 10,
|
||||
"timings": {
|
||||
"cache_n": 0,
|
||||
"prompt_n": 10,
|
||||
"prompt_ms": 12.3,
|
||||
"prompt_per_token_ms": 1.235,
|
||||
"prompt_per_second": 810.0,
|
||||
"predicted_n": 10,
|
||||
"predicted_ms": 98.8,
|
||||
"predicted_per_token_ms": 14.109,
|
||||
"predicted_per_second": 70.9
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 12.34567,
|
||||
"decode_ms": 98.7654,
|
||||
"generated": 7,
|
||||
"reused": null
|
||||
},
|
||||
"prompt_tokens": 0,
|
||||
"generated": 0,
|
||||
"timings": {
|
||||
"cache_n": 0,
|
||||
"prompt_n": 0,
|
||||
"prompt_ms": 12.3,
|
||||
"prompt_per_token_ms": null,
|
||||
"prompt_per_second": null,
|
||||
"predicted_n": 0,
|
||||
"predicted_ms": 98.8,
|
||||
"predicted_per_token_ms": 14.109,
|
||||
"predicted_per_second": 70.9
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 12.34567,
|
||||
"decode_ms": 98.7654,
|
||||
"generated": 7,
|
||||
"reused": null
|
||||
},
|
||||
"prompt_tokens": 50,
|
||||
"generated": 7,
|
||||
"timings": {
|
||||
"cache_n": 0,
|
||||
"prompt_n": 50,
|
||||
"prompt_ms": 12.3,
|
||||
"prompt_per_token_ms": 0.247,
|
||||
"prompt_per_second": 4050.0,
|
||||
"predicted_n": 7,
|
||||
"predicted_ms": 98.8,
|
||||
"predicted_per_token_ms": 14.109,
|
||||
"predicted_per_second": 70.9
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 0.25,
|
||||
"decode_ms": 0.05,
|
||||
"generated": 3
|
||||
},
|
||||
"prompt_tokens": 300,
|
||||
"generated": 3,
|
||||
"timings": {
|
||||
"cache_n": 0,
|
||||
"prompt_n": 300,
|
||||
"prompt_ms": 0.2,
|
||||
"prompt_per_token_ms": 0.001,
|
||||
"prompt_per_second": 1200000.0,
|
||||
"predicted_n": 3,
|
||||
"predicted_ms": 0.1,
|
||||
"predicted_per_token_ms": 0.017,
|
||||
"predicted_per_second": 60000.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 0.25,
|
||||
"decode_ms": 0.05,
|
||||
"generated": 3
|
||||
},
|
||||
"prompt_tokens": 10,
|
||||
"generated": 10,
|
||||
"timings": {
|
||||
"cache_n": 0,
|
||||
"prompt_n": 10,
|
||||
"prompt_ms": 0.2,
|
||||
"prompt_per_token_ms": 0.025,
|
||||
"prompt_per_second": 40000.0,
|
||||
"predicted_n": 10,
|
||||
"predicted_ms": 0.1,
|
||||
"predicted_per_token_ms": 0.017,
|
||||
"predicted_per_second": 60000.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 0.25,
|
||||
"decode_ms": 0.05,
|
||||
"generated": 3
|
||||
},
|
||||
"prompt_tokens": 0,
|
||||
"generated": 0,
|
||||
"timings": {
|
||||
"cache_n": 0,
|
||||
"prompt_n": 0,
|
||||
"prompt_ms": 0.2,
|
||||
"prompt_per_token_ms": null,
|
||||
"prompt_per_second": null,
|
||||
"predicted_n": 0,
|
||||
"predicted_ms": 0.1,
|
||||
"predicted_per_token_ms": 0.017,
|
||||
"predicted_per_second": 60000.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 0.25,
|
||||
"decode_ms": 0.05,
|
||||
"generated": 3
|
||||
},
|
||||
"prompt_tokens": 50,
|
||||
"generated": 7,
|
||||
"timings": {
|
||||
"cache_n": 0,
|
||||
"prompt_n": 50,
|
||||
"prompt_ms": 0.2,
|
||||
"prompt_per_token_ms": 0.005,
|
||||
"prompt_per_second": 200000.0,
|
||||
"predicted_n": 7,
|
||||
"predicted_ms": 0.1,
|
||||
"predicted_per_token_ms": 0.017,
|
||||
"predicted_per_second": 60000.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 2.675,
|
||||
"decode_ms": 1234.55,
|
||||
"generated": 11,
|
||||
"reused": 5,
|
||||
"drafts_offered": 20,
|
||||
"drafts_accepted": 15
|
||||
},
|
||||
"prompt_tokens": 300,
|
||||
"generated": 11,
|
||||
"timings": {
|
||||
"cache_n": 5,
|
||||
"prompt_n": 295,
|
||||
"prompt_ms": 2.7,
|
||||
"prompt_per_token_ms": 0.009,
|
||||
"prompt_per_second": 110280.4,
|
||||
"predicted_n": 11,
|
||||
"predicted_ms": 1234.5,
|
||||
"predicted_per_token_ms": 112.232,
|
||||
"predicted_per_second": 8.9,
|
||||
"draft_n": 20,
|
||||
"draft_n_accepted": 15
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 2.675,
|
||||
"decode_ms": 1234.55,
|
||||
"generated": 11,
|
||||
"reused": 5,
|
||||
"drafts_offered": 20,
|
||||
"drafts_accepted": 15
|
||||
},
|
||||
"prompt_tokens": 10,
|
||||
"generated": 10,
|
||||
"timings": {
|
||||
"cache_n": 5,
|
||||
"prompt_n": 5,
|
||||
"prompt_ms": 2.7,
|
||||
"prompt_per_token_ms": 0.535,
|
||||
"prompt_per_second": 1869.2,
|
||||
"predicted_n": 10,
|
||||
"predicted_ms": 1234.5,
|
||||
"predicted_per_token_ms": 112.232,
|
||||
"predicted_per_second": 8.9,
|
||||
"draft_n": 20,
|
||||
"draft_n_accepted": 15
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 2.675,
|
||||
"decode_ms": 1234.55,
|
||||
"generated": 11,
|
||||
"reused": 5,
|
||||
"drafts_offered": 20,
|
||||
"drafts_accepted": 15
|
||||
},
|
||||
"prompt_tokens": 0,
|
||||
"generated": 0,
|
||||
"timings": {
|
||||
"cache_n": 5,
|
||||
"prompt_n": 0,
|
||||
"prompt_ms": 2.7,
|
||||
"prompt_per_token_ms": null,
|
||||
"prompt_per_second": null,
|
||||
"predicted_n": 0,
|
||||
"predicted_ms": 1234.5,
|
||||
"predicted_per_token_ms": 112.232,
|
||||
"predicted_per_second": 8.9,
|
||||
"draft_n": 20,
|
||||
"draft_n_accepted": 15
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 2.675,
|
||||
"decode_ms": 1234.55,
|
||||
"generated": 11,
|
||||
"reused": 5,
|
||||
"drafts_offered": 20,
|
||||
"drafts_accepted": 15
|
||||
},
|
||||
"prompt_tokens": 50,
|
||||
"generated": 7,
|
||||
"timings": {
|
||||
"cache_n": 5,
|
||||
"prompt_n": 45,
|
||||
"prompt_ms": 2.7,
|
||||
"prompt_per_token_ms": 0.059,
|
||||
"prompt_per_second": 16822.4,
|
||||
"predicted_n": 7,
|
||||
"predicted_ms": 1234.5,
|
||||
"predicted_per_token_ms": 112.232,
|
||||
"predicted_per_second": 8.9,
|
||||
"draft_n": 20,
|
||||
"draft_n_accepted": 15
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 100.0,
|
||||
"decode_ms": 333.3333,
|
||||
"generated": 0,
|
||||
"reused": 200
|
||||
},
|
||||
"prompt_tokens": 300,
|
||||
"generated": 5,
|
||||
"timings": {
|
||||
"cache_n": 200,
|
||||
"prompt_n": 100,
|
||||
"prompt_ms": 100.0,
|
||||
"prompt_per_token_ms": 1.0,
|
||||
"prompt_per_second": 1000.0,
|
||||
"predicted_n": 5,
|
||||
"predicted_ms": 333.3,
|
||||
"predicted_per_token_ms": 66.667,
|
||||
"predicted_per_second": 15.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 100.0,
|
||||
"decode_ms": 333.3333,
|
||||
"generated": 0,
|
||||
"reused": 200
|
||||
},
|
||||
"prompt_tokens": 10,
|
||||
"generated": 10,
|
||||
"timings": {
|
||||
"cache_n": 200,
|
||||
"prompt_n": 0,
|
||||
"prompt_ms": 100.0,
|
||||
"prompt_per_token_ms": null,
|
||||
"prompt_per_second": null,
|
||||
"predicted_n": 10,
|
||||
"predicted_ms": 333.3,
|
||||
"predicted_per_token_ms": 33.333,
|
||||
"predicted_per_second": 30.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 100.0,
|
||||
"decode_ms": 333.3333,
|
||||
"generated": 0,
|
||||
"reused": 200
|
||||
},
|
||||
"prompt_tokens": 0,
|
||||
"generated": 0,
|
||||
"timings": {
|
||||
"cache_n": 200,
|
||||
"prompt_n": 0,
|
||||
"prompt_ms": 100.0,
|
||||
"prompt_per_token_ms": null,
|
||||
"prompt_per_second": null,
|
||||
"predicted_n": 0,
|
||||
"predicted_ms": 333.3,
|
||||
"predicted_per_token_ms": null,
|
||||
"predicted_per_second": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 100.0,
|
||||
"decode_ms": 333.3333,
|
||||
"generated": 0,
|
||||
"reused": 200
|
||||
},
|
||||
"prompt_tokens": 50,
|
||||
"generated": 7,
|
||||
"timings": {
|
||||
"cache_n": 200,
|
||||
"prompt_n": 0,
|
||||
"prompt_ms": 100.0,
|
||||
"prompt_per_token_ms": null,
|
||||
"prompt_per_second": null,
|
||||
"predicted_n": 7,
|
||||
"predicted_ms": 333.3,
|
||||
"predicted_per_token_ms": 47.619,
|
||||
"predicted_per_second": 21.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 1e-09,
|
||||
"decode_ms": 5e-05,
|
||||
"generated": 9,
|
||||
"reused": 0,
|
||||
"drafts_offered": 0,
|
||||
"drafts_accepted": 0
|
||||
},
|
||||
"prompt_tokens": 300,
|
||||
"generated": 9,
|
||||
"timings": {
|
||||
"cache_n": 0,
|
||||
"prompt_n": 300,
|
||||
"prompt_ms": 0.0,
|
||||
"prompt_per_token_ms": 0.0,
|
||||
"prompt_per_second": 300000000000000.0,
|
||||
"predicted_n": 9,
|
||||
"predicted_ms": 0.0,
|
||||
"predicted_per_token_ms": 0.0,
|
||||
"predicted_per_second": 180000000.0,
|
||||
"draft_n": 0,
|
||||
"draft_n_accepted": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 1e-09,
|
||||
"decode_ms": 5e-05,
|
||||
"generated": 9,
|
||||
"reused": 0,
|
||||
"drafts_offered": 0,
|
||||
"drafts_accepted": 0
|
||||
},
|
||||
"prompt_tokens": 10,
|
||||
"generated": 10,
|
||||
"timings": {
|
||||
"cache_n": 0,
|
||||
"prompt_n": 10,
|
||||
"prompt_ms": 0.0,
|
||||
"prompt_per_token_ms": 0.0,
|
||||
"prompt_per_second": 10000000000000.0,
|
||||
"predicted_n": 10,
|
||||
"predicted_ms": 0.0,
|
||||
"predicted_per_token_ms": 0.0,
|
||||
"predicted_per_second": 180000000.0,
|
||||
"draft_n": 0,
|
||||
"draft_n_accepted": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 1e-09,
|
||||
"decode_ms": 5e-05,
|
||||
"generated": 9,
|
||||
"reused": 0,
|
||||
"drafts_offered": 0,
|
||||
"drafts_accepted": 0
|
||||
},
|
||||
"prompt_tokens": 0,
|
||||
"generated": 0,
|
||||
"timings": {
|
||||
"cache_n": 0,
|
||||
"prompt_n": 0,
|
||||
"prompt_ms": 0.0,
|
||||
"prompt_per_token_ms": null,
|
||||
"prompt_per_second": null,
|
||||
"predicted_n": 0,
|
||||
"predicted_ms": 0.0,
|
||||
"predicted_per_token_ms": 0.0,
|
||||
"predicted_per_second": 180000000.0,
|
||||
"draft_n": 0,
|
||||
"draft_n_accepted": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 1e-09,
|
||||
"decode_ms": 5e-05,
|
||||
"generated": 9,
|
||||
"reused": 0,
|
||||
"drafts_offered": 0,
|
||||
"drafts_accepted": 0
|
||||
},
|
||||
"prompt_tokens": 50,
|
||||
"generated": 7,
|
||||
"timings": {
|
||||
"cache_n": 0,
|
||||
"prompt_n": 50,
|
||||
"prompt_ms": 0.0,
|
||||
"prompt_per_token_ms": 0.0,
|
||||
"prompt_per_second": 50000000000000.0,
|
||||
"predicted_n": 7,
|
||||
"predicted_ms": 0.0,
|
||||
"predicted_per_token_ms": 0.0,
|
||||
"predicted_per_second": 180000000.0,
|
||||
"draft_n": 0,
|
||||
"draft_n_accepted": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 12345.678,
|
||||
"decode_ms": 87654.321,
|
||||
"generated": 4096,
|
||||
"reused": 1
|
||||
},
|
||||
"prompt_tokens": 300,
|
||||
"generated": 4096,
|
||||
"timings": {
|
||||
"cache_n": 1,
|
||||
"prompt_n": 299,
|
||||
"prompt_ms": 12345.7,
|
||||
"prompt_per_token_ms": 41.29,
|
||||
"prompt_per_second": 24.2,
|
||||
"predicted_n": 4096,
|
||||
"predicted_ms": 87654.3,
|
||||
"predicted_per_token_ms": 21.4,
|
||||
"predicted_per_second": 46.7
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 12345.678,
|
||||
"decode_ms": 87654.321,
|
||||
"generated": 4096,
|
||||
"reused": 1
|
||||
},
|
||||
"prompt_tokens": 10,
|
||||
"generated": 10,
|
||||
"timings": {
|
||||
"cache_n": 1,
|
||||
"prompt_n": 9,
|
||||
"prompt_ms": 12345.7,
|
||||
"prompt_per_token_ms": 1371.742,
|
||||
"prompt_per_second": 0.7,
|
||||
"predicted_n": 10,
|
||||
"predicted_ms": 87654.3,
|
||||
"predicted_per_token_ms": 21.4,
|
||||
"predicted_per_second": 46.7
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 12345.678,
|
||||
"decode_ms": 87654.321,
|
||||
"generated": 4096,
|
||||
"reused": 1
|
||||
},
|
||||
"prompt_tokens": 0,
|
||||
"generated": 0,
|
||||
"timings": {
|
||||
"cache_n": 1,
|
||||
"prompt_n": 0,
|
||||
"prompt_ms": 12345.7,
|
||||
"prompt_per_token_ms": null,
|
||||
"prompt_per_second": null,
|
||||
"predicted_n": 0,
|
||||
"predicted_ms": 87654.3,
|
||||
"predicted_per_token_ms": 21.4,
|
||||
"predicted_per_second": 46.7
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {
|
||||
"prompt_ms": 12345.678,
|
||||
"decode_ms": 87654.321,
|
||||
"generated": 4096,
|
||||
"reused": 1
|
||||
},
|
||||
"prompt_tokens": 50,
|
||||
"generated": 7,
|
||||
"timings": {
|
||||
"cache_n": 1,
|
||||
"prompt_n": 49,
|
||||
"prompt_ms": 12345.7,
|
||||
"prompt_per_token_ms": 251.953,
|
||||
"prompt_per_second": 4.0,
|
||||
"predicted_n": 7,
|
||||
"predicted_ms": 87654.3,
|
||||
"predicted_per_token_ms": 21.4,
|
||||
"predicted_per_second": 46.7
|
||||
}
|
||||
},
|
||||
{
|
||||
"last": {},
|
||||
"prompt_tokens": 5,
|
||||
"generated": 5,
|
||||
"timings": null
|
||||
}
|
||||
],
|
||||
"aliases": [
|
||||
{
|
||||
"input": null,
|
||||
"ok": []
|
||||
},
|
||||
{
|
||||
"input": [],
|
||||
"ok": []
|
||||
},
|
||||
{
|
||||
"input": [
|
||||
"a"
|
||||
],
|
||||
"ok": [
|
||||
"a"
|
||||
]
|
||||
},
|
||||
{
|
||||
"input": [
|
||||
" a ",
|
||||
"a",
|
||||
"",
|
||||
"m",
|
||||
"b"
|
||||
],
|
||||
"ok": [
|
||||
"a",
|
||||
"b"
|
||||
]
|
||||
},
|
||||
{
|
||||
"input": "a, b ,a,,m",
|
||||
"ok": [
|
||||
"a",
|
||||
"b"
|
||||
]
|
||||
},
|
||||
{
|
||||
"input": [
|
||||
"a",
|
||||
1
|
||||
],
|
||||
"error": "aliases=['a', 1]: expected a list of model names"
|
||||
},
|
||||
{
|
||||
"input": 5,
|
||||
"error": "aliases=5: expected a list of model names"
|
||||
},
|
||||
{
|
||||
"input": {
|
||||
"a": 1
|
||||
},
|
||||
"error": "aliases={'a': 1}: expected a list of model names"
|
||||
},
|
||||
{
|
||||
"input": "",
|
||||
"ok": []
|
||||
},
|
||||
{
|
||||
"input": [
|
||||
""
|
||||
],
|
||||
"ok": []
|
||||
}
|
||||
]
|
||||
}
|
||||
+4222
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"source": "src/program/generate.cpp GENI embeddings block + fnv1a (verbatim, host build)",
|
||||
"cases": [
|
||||
{"name": "text identity after an image request", "geni": false, "mrope_identity": false, "n_embd": 4, "cells": 32, "file_hex": "", "ids": [5,6,7], "ve": "", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,-1,-1], "imgs": []},
|
||||
{"name": "text only with no file", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "", "ids": [5,6,7,8], "ve": "cannot open /nonexistent/embeddings.sve", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,-1,-1,-1], "imgs": []},
|
||||
{"name": "one 1x1 image", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "53564531010000000100000001000000040000000000803f0000c03f0000004000002040", "ids": [1,2,248056,3,4], "ve": "", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,-1,0,-1,-1], "imgs": [[2,"3ccab5f5c275a7f2"]]},
|
||||
{"name": "one 3x2 image", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 40, "file_hex": "535645310600000003000000020000000400000000002041000028410000304100003841000040410000484100005041000058410000604100006841000070410000784100008041000084410000884100008c4100009041000094410000984100009c410000a0410000a4410000a8410000ac41", "ids": [1,248056,248056,248056,248056,248056,248056,9,10], "ve": "", "table": [0,0,0,1,1,1,1,1,2,1,1,3,1,2,1,1,2,2,1,2,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31,32,32,32,33,33,33,34,34,34,35,35,35,36,36,36], "row_offset": [-1,0,4,8,12,16,20,-1,-1], "imgs": [[1,"b98ae886c8b44c94"]]},
|
||||
{"name": "one 2x4 image (tall: ny > nx)", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 40, "file_hex": "53564531080000000200000004000000040000000000a0410000a4410000a8410000ac410000b0410000b4410000b8410000bc410000c0410000c4410000c8410000cc410000d0410000d4410000d8410000dc410000e0410000e4410000e8410000ec410000f0410000f4410000f8410000fc41000000420000024200000442000006420000084200000a4200000c4200000e42", "ids": [7,248056,248056,248056,248056,248056,248056,248056,248056,8], "ve": "", "table": [0,0,0,1,1,1,1,1,2,1,2,1,1,2,2,1,3,1,1,3,2,1,4,1,1,4,2,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31,32,32,32,33,33,33,34,34,34,35,35,35], "row_offset": [-1,0,4,8,12,16,20,24,28,-1], "imgs": [[1,"cbe485118dfba78d"]]},
|
||||
{"name": "two images in order", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 64, "file_hex": "535645310600000003000000020000000400000000002041000028410000304100003841000040410000484100005041000058410000604100006841000070410000784100008041000084410000884100008c4100009041000094410000984100009c410000a0410000a4410000a8410000ac4153564531080000000200000004000000040000000000a0410000a4410000a8410000ac410000b0410000b4410000b8410000bc410000c0410000c4410000c8410000cc410000d0410000d4410000d8410000dc410000e0410000e4410000e8410000ec410000f0410000f4410000f8410000fc41000000420000024200000442000006420000084200000a4200000c4200000e42", "ids": [1,248056,248056,248056,248056,248056,248056,2,248056,248056,248056,248056,248056,248056,248056,248056,3], "ve": "", "table": [0,0,0,1,1,1,1,1,2,1,1,3,1,2,1,1,2,2,1,2,3,4,4,4,5,5,5,5,5,6,5,6,5,5,6,6,5,7,5,5,7,6,5,8,5,5,8,6,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31,32,32,32,33,33,33,34,34,34,35,35,35,36,36,36,37,37,37,38,38,38,39,39,39,40,40,40,41,41,41,42,42,42,43,43,43,44,44,44,45,45,45,46,46,46,47,47,47,48,48,48,49,49,49,50,50,50,51,51,51,52,52,52,53,53,53,54,54,54,55,55,55,56,56,56], "row_offset": [-1,0,4,8,12,16,20,-1,24,28,32,36,40,44,48,52,-1], "imgs": [[1,"b98ae886c8b44c94"],[8,"cbe485118dfba78d"]]},
|
||||
{"name": "5x5 image then text", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 64, "file_hex": "53564531190000000500000005000000040000000000f0410000f4410000f8410000fc41000000420000024200000442000006420000084200000a4200000c4200000e42000010420000124200001442000016420000184200001a4200001c4200001e42000020420000224200002442000026420000284200002a4200002c4200002e42000030420000324200003442000036420000384200003a4200003c4200003e42000040420000424200004442000046420000484200004a4200004c4200004e42000050420000524200005442000056420000584200005a4200005c4200005e42000060420000624200006442000066420000684200006a4200006c4200006e42000070420000724200007442000076420000784200007a4200007c4200007e420000804200008142000082420000834200008442000085420000864200008742000088420000894200008a4200008b4200008c4200008d4200008e4200008f420000904200009142000092420000934200009442000095420000964200009742000098420000994200009a4200009b4200009c4200009d4200009e4200009f42", "ids": [1,2,3,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,4,5], "ve": "", "table": [0,0,0,1,1,1,2,2,2,3,3,3,3,3,4,3,3,5,3,3,6,3,3,7,3,4,3,3,4,4,3,4,5,3,4,6,3,4,7,3,5,3,3,5,4,3,5,5,3,5,6,3,5,7,3,6,3,3,6,4,3,6,5,3,6,6,3,6,7,3,7,3,3,7,4,3,7,5,3,7,6,3,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31,32,32,32,33,33,33,34,34,34,35,35,35,36,36,36,37,37,37,38,38,38,39,39,39,40,40,40,41,41,41,42,42,42,43,43,43], "row_offset": [-1,-1,-1,0,4,8,12,16,20,24,28,32,36,40,44,48,52,56,60,64,68,72,76,80,84,88,92,96,-1,-1], "imgs": [[3,"2c0ab68485332f9a"]]},
|
||||
{"name": "adjacent images", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 40, "file_hex": "535645310600000003000000020000000400000000002041000028410000304100003841000040410000484100005041000058410000604100006841000070410000784100008041000084410000884100008c4100009041000094410000984100009c410000a0410000a4410000a8410000ac4153564531080000000200000004000000040000000000a0410000a4410000a8410000ac410000b0410000b4410000b8410000bc410000c0410000c4410000c8410000cc410000d0410000d4410000d8410000dc410000e0410000e4410000e8410000ec410000f0410000f4410000f8410000fc41000000420000024200000442000006420000084200000a4200000c4200000e42", "ids": [248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,248056,1], "ve": "", "table": [0,0,0,0,0,1,0,0,2,0,1,0,0,1,1,0,1,2,3,3,3,3,3,4,3,4,3,3,4,4,3,5,3,3,5,4,3,6,3,3,6,4,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31,32,32,32], "row_offset": [0,4,8,12,16,20,24,28,32,36,40,44,48,52,-1], "imgs": [[0,"b98ae886c8b44c94"],[6,"cbe485118dfba78d"]]},
|
||||
{"name": "image at the start", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 16, "file_hex": "53564531010000000100000001000000040000000000803f0000c03f0000004000002040", "ids": [248056,4], "ve": "", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15], "row_offset": [0,-1], "imgs": [[0,"3ccab5f5c275a7f2"]]},
|
||||
{"name": "identity request after (not geni, not identity)", "geni": false, "mrope_identity": false, "n_embd": 4, "cells": 16, "file_hex": "", "ids": [1,2], "ve": "", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15], "row_offset": [-1,-1], "imgs": []},
|
||||
{"name": "prompt ends in an image", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "535645310600000003000000020000000400000000002041000028410000304100003841000040410000484100005041000058410000604100006841000070410000784100008041000084410000884100008c4100009041000094410000984100009c410000a0410000a4410000a8410000ac41", "ids": [1,248056,248056,248056,248056,248056,248056], "ve": "the prompt cannot end in an image", "table": [0,0,0,1,1,1,1,1,2,1,1,3,1,2,1,1,2,2,1,2,3,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,0,4,8,12,16,20], "imgs": [[1,"b98ae886c8b44c94"]]},
|
||||
{"name": "more images in the prompt than the file", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "53564531010000000100000001000000040000000000803f0000c03f0000004000002040", "ids": [1,248056,2,248056,3], "ve": "the prompt has more images than the embeddings file", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,0,-1,-1,-1], "imgs": [[1,"3ccab5f5c275a7f2"]]},
|
||||
{"name": "more images in the file than the prompt", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "53564531010000000100000001000000040000000000803f0000c03f000000400000204053564531010000000100000001000000040000000000803f0000c03f0000004000002040", "ids": [1,248056,2,3], "ve": "the embeddings file has more images than the prompt", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,0,-1,-1], "imgs": [[1,"3ccab5f5c275a7f2"]]},
|
||||
{"name": "fewer image_pad tokens than rows", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "535645310600000003000000020000000400000000002041000028410000304100003841000040410000484100005041000058410000604100006841000070410000784100008041000084410000884100008c4100009041000094410000984100009c410000a0410000a4410000a8410000ac41", "ids": [1,248056,248056,2,3,4,5,6,7], "ve": "image 1 has 6 rows but fewer <|image_pad|> tokens", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,-1,-1,-1,-1,-1,-1,-1,-1], "imgs": [[1,"b98ae886c8b44c94"]]},
|
||||
{"name": "bad magic", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "78563412010000000100000001000000040000000000803f0000c03f0000004000002040", "ids": [1,248056,2], "ve": "bad embeddings file (expected strata-vision records of width 4)", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,-1,-1], "imgs": []},
|
||||
{"name": "wrong width", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "53564531010000000100000001000000080000000000803f0000c03f000000400000204000004040000060400000804000009040", "ids": [1,248056,2], "ve": "bad embeddings file (expected strata-vision records of width 4)", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,-1,-1], "imgs": []},
|
||||
{"name": "grid does not multiply", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "53564531060000000300000003000000040000000000803f0000c03f0000004000002040000040400000604000008040000090400000a0400000b0400000c0400000d0400000e0400000f04000000041000008410000104100001841000020410000284100003041000038410000404100004841", "ids": [1,248056,2], "ve": "bad embeddings file (expected strata-vision records of width 4)", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,-1,-1], "imgs": []},
|
||||
{"name": "zero rows", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "5356453100000000000000000000000004000000", "ids": [1,248056,2], "ve": "bad embeddings file (expected strata-vision records of width 4)", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,-1,-1], "imgs": []},
|
||||
{"name": "short header", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "535645310100000001000000", "ids": [1,248056,2], "ve": "bad embeddings file (expected strata-vision records of width 4)", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,-1,-1], "imgs": []},
|
||||
{"name": "short data", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "53564531010000000100000001000000040000000000803f0000c03f0000004000", "ids": [1,248056,2], "ve": "short embeddings file", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,-1,-1], "imgs": []},
|
||||
{"name": "second record truncated", "geni": true, "mrope_identity": true, "n_embd": 4, "cells": 32, "file_hex": "53564531010000000100000001000000040000000000803f0000c03f000000400000204053564531010000000100000001000000040000000000803f00", "ids": [1,248056,2,248056,3], "ve": "short embeddings file", "table": [0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16,16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29,30,30,30,31,31,31], "row_offset": [-1,-1,-1,-1,-1], "imgs": []}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
//! The control-vector loader against the Original's `load_control_vectors` compiled verbatim on the host
|
||||
//! (fixture from `oracle/build_oracle.sh`): same tables bit for bit, same error text.
|
||||
|
||||
use leleka_serving_policy::cvec::{Mode, Options, build_tables, parse_gguf};
|
||||
use serde_json::Value;
|
||||
|
||||
fn unhex(text: &str) -> Vec<u8> {
|
||||
(0..text.len() / 2)
|
||||
.map(|i| u8::from_str_radix(&text[2 * i..2 * i + 2], 16).unwrap())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tables_and_errors_equal_the_engines_loader() {
|
||||
let fixture: Value = serde_json::from_str(include_str!("fixtures/cvec_oracle.json")).unwrap();
|
||||
let layers = fixture["n_layers"].as_u64().unwrap() as usize;
|
||||
let width = fixture["n_embd"].as_u64().unwrap() as usize;
|
||||
let blobs: Vec<Vec<u8>> = fixture["blobs"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|b| unhex(b.as_str().unwrap()))
|
||||
.collect();
|
||||
let (mut loaded, mut refused) = (0, 0);
|
||||
for case in fixture["cases"].as_array().unwrap() {
|
||||
let name = case["name"].as_str().unwrap();
|
||||
let mut files = Vec::new();
|
||||
for entry in case["files"].as_array().unwrap() {
|
||||
let blob = entry[0].as_u64().unwrap() as usize;
|
||||
let scale = f32::from_bits(entry[1].as_u64().unwrap() as u32);
|
||||
files.push((
|
||||
format!("FILE{blob}"),
|
||||
parse_gguf(&blobs[blob]).unwrap_or_else(|e| panic!("{name}: {e}")),
|
||||
scale,
|
||||
));
|
||||
}
|
||||
let options = Options {
|
||||
first: case["first"].as_i64().unwrap() as i32,
|
||||
last: case["last"].as_i64().unwrap() as i32,
|
||||
mode: if case["mode"] == "project" {
|
||||
Mode::Project
|
||||
} else {
|
||||
Mode::Add
|
||||
},
|
||||
single: case["single"].as_i64().unwrap() as i32,
|
||||
};
|
||||
let got = build_tables(&files, layers, width, options);
|
||||
if case["ok"].as_bool().unwrap() {
|
||||
let tables = got.unwrap_or_else(|e| panic!("{name}: unexpected error {e}"));
|
||||
let bits = |values: &[f32]| -> Vec<u64> {
|
||||
values.iter().map(|v| u64::from(v.to_bits())).collect()
|
||||
};
|
||||
let want = |key: &str| -> Vec<u64> {
|
||||
case["up"][key]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|v| v.as_u64().unwrap())
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(bits(&tables.dir), want("dir_bits"), "{name}: dir");
|
||||
assert_eq!(bits(&tables.s), want("s_bits"), "{name}: s");
|
||||
assert_eq!(
|
||||
tables.first as i64,
|
||||
case["up"]["first"].as_i64().unwrap(),
|
||||
"{name}"
|
||||
);
|
||||
assert_eq!(
|
||||
tables.last as i64,
|
||||
case["up"]["last"].as_i64().unwrap(),
|
||||
"{name}"
|
||||
);
|
||||
assert_eq!(
|
||||
tables.mode == Mode::Project,
|
||||
case["up"]["mode"].as_i64().unwrap() == 0,
|
||||
"{name}"
|
||||
);
|
||||
assert_eq!(tables.summary, case["summary"].as_str().unwrap(), "{name}");
|
||||
loaded += 1;
|
||||
} else {
|
||||
assert_eq!(got.unwrap_err(), case["err"].as_str().unwrap(), "{name}");
|
||||
refused += 1;
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
loaded >= 14 && refused >= 8,
|
||||
"{loaded} loaded, {refused} refused"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! Stride selection and the stall watchdog against the Original's C++ host build
|
||||
//! (fixture from `oracle/build_oracle.sh`: `logits_selection.hpp` unmodified, the watchdog loop driven
|
||||
//! by an injected clock).
|
||||
|
||||
use leleka_serving_policy::stride::{parse_stride, row_count, selected};
|
||||
use leleka_serving_policy::watchdog::{Counters, StallWatchdog, Verdict};
|
||||
use serde_json::Value;
|
||||
|
||||
fn fixture() -> Value {
|
||||
serde_json::from_str(include_str!("fixtures/host_oracle.json")).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stride_parsing_equals_the_header() {
|
||||
for case in fixture()["parse"].as_array().unwrap() {
|
||||
let text = case["text"].as_str().unwrap();
|
||||
let got = parse_stride(text);
|
||||
if case["ok"].as_bool().unwrap() {
|
||||
assert_eq!(got, case["value"].as_i64(), "{text:?}");
|
||||
} else {
|
||||
assert_eq!(got, None, "{text:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stride_selection_and_row_counts_equal_the_header() {
|
||||
let fixture = fixture();
|
||||
let cases = fixture["selected"].as_array().unwrap();
|
||||
assert_eq!(cases.len(), 100);
|
||||
for case in cases {
|
||||
let total = case["total"].as_i64().unwrap();
|
||||
let stride = case["stride"].as_i64().unwrap();
|
||||
assert_eq!(row_count(total, stride), case["rows"].as_i64().unwrap());
|
||||
let want: Vec<i64> = case["kept"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|v| v.as_i64().unwrap())
|
||||
.collect();
|
||||
let got: Vec<i64> = (-2..total + 2)
|
||||
.filter(|p| selected(*p, total, stride))
|
||||
.collect();
|
||||
assert_eq!(got, want, "total {total} stride {stride}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn watchdog_scenarios_equal_the_engine_loop() {
|
||||
let fixture = fixture();
|
||||
let mut fired = 0;
|
||||
for scenario in fixture["watchdog"].as_array().unwrap() {
|
||||
let limit = scenario["limit_s"].as_i64().unwrap();
|
||||
let mut dog = StallWatchdog::new(limit, 0, Counters::default());
|
||||
for step in scenario["steps"].as_array().unwrap() {
|
||||
let counters = Counters {
|
||||
beats: step["beats"].as_u64().unwrap(),
|
||||
busy: step["busy"].as_bool().unwrap(),
|
||||
ticks: step["ticks"].as_u64().unwrap(),
|
||||
};
|
||||
let verdict = dog.poll(step["at_ms"].as_u64().unwrap(), counters);
|
||||
let want = step["layers_since"].as_i64().unwrap();
|
||||
match verdict {
|
||||
Verdict::Healthy => assert_eq!(want, -1, "limit {limit} step {step}"),
|
||||
Verdict::Stalled { layers_since, .. } => {
|
||||
assert_eq!(layers_since as i64, want, "limit {limit} step {step}");
|
||||
fired += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(fired >= 6, "{fired}");
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
//! `BudgetTracker` and `parse_budget` against the Original's real `Detokenizer` + `OutputParser` loop and
|
||||
//! `Service.reasoning_budget` (fixture from `control-plane/tests/golden/gen_goldens.py reasoning`).
|
||||
|
||||
use leleka_serving_policy::reasoning::{BudgetTracker, Verdict, WRAP_UP, parse_budget};
|
||||
use serde_json::Value;
|
||||
|
||||
fn fixture() -> Value {
|
||||
serde_json::from_str(include_str!("fixtures/reasoning.json")).unwrap()
|
||||
}
|
||||
|
||||
fn unhex(text: &str) -> Vec<u8> {
|
||||
(0..text.len() / 2)
|
||||
.map(|i| u8::from_str_radix(&text[2 * i..2 * i + 2], 16).unwrap())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrap_up_text_is_the_originals() {
|
||||
assert_eq!(fixture()["wrap_up"].as_str().unwrap(), WRAP_UP);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrap_up_points_equal_python_for_every_sequence_and_budget() {
|
||||
let fixture = fixture();
|
||||
let mut wrapped = 0;
|
||||
let mut unwrapped = 0;
|
||||
for case in fixture["cases"].as_array().unwrap() {
|
||||
let pieces: Vec<Vec<u8>> = case["pieces_hex"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|v| unhex(v.as_str().unwrap()))
|
||||
.collect();
|
||||
for (budget, want) in case["wrap_at"].as_object().unwrap() {
|
||||
let mut tracker = BudgetTracker::new(budget.parse().unwrap());
|
||||
let mut got = None;
|
||||
for (index, piece) in pieces.iter().enumerate() {
|
||||
if tracker.push(piece) == Verdict::WrapUp {
|
||||
got = Some(index as u64);
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
got,
|
||||
want.as_u64(),
|
||||
"budget {budget} pieces {:?}",
|
||||
case["pieces_hex"]
|
||||
);
|
||||
if got.is_some() {
|
||||
wrapped += 1;
|
||||
} else {
|
||||
unwrapped += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(wrapped > 100 && unwrapped > 50, "{wrapped} {unwrapped}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn budget_parsing_equals_python() {
|
||||
for case in fixture()["parse"].as_array().unwrap() {
|
||||
let request = case["request"].get("reasoning_budget_tokens");
|
||||
let default = case["default"].clone();
|
||||
let got = parse_budget(request, Some(&default));
|
||||
match (case.get("ok"), case.get("error")) {
|
||||
(Some(ok), None) => assert_eq!(
|
||||
got.unwrap().map(Value::from).unwrap_or(Value::Null),
|
||||
*ok,
|
||||
"{case}"
|
||||
),
|
||||
(None, Some(error)) => assert_eq!(got.unwrap_err(), error.as_str().unwrap(), "{case}"),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
//! `clean_shared_defaults` / `sampling_defaults_from_config` against the Original's real Python output
|
||||
//! (fixture from `control-plane/tests/golden/gen_goldens.py shared`).
|
||||
|
||||
use leleka_serving_policy::shared::{clean_shared_defaults, sampling_defaults_from_config};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn fixture() -> Value {
|
||||
serde_json::from_str(include_str!("fixtures/shared.json")).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_cleaning_equals_python() {
|
||||
let fixture = fixture();
|
||||
let mut agreed_errors = 0;
|
||||
for case in fixture["clean"].as_array().unwrap() {
|
||||
let input = &case["input"];
|
||||
let got = clean_shared_defaults(input);
|
||||
match (case.get("ok"), case.get("error")) {
|
||||
(Some(ok), None) => {
|
||||
let got = got.unwrap_or_else(|e| panic!("{input}: unexpected error {e}"));
|
||||
assert_eq!(&got.to_json(), ok, "{input}");
|
||||
}
|
||||
(None, Some(error)) => {
|
||||
assert_eq!(got.unwrap_err(), error.as_str().unwrap(), "{input}");
|
||||
agreed_errors += 1;
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
assert!(agreed_errors >= 20);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_sampling_block_equals_python() {
|
||||
let fixture = fixture();
|
||||
let mut agreed_errors = 0;
|
||||
for case in fixture["config"].as_array().unwrap() {
|
||||
let input = case["input"].clone();
|
||||
let got = sampling_defaults_from_config(&input);
|
||||
match (case.get("ok"), case.get("error")) {
|
||||
(Some(ok), None) => {
|
||||
let got = got.unwrap_or_else(|e| panic!("{input}: unexpected error {e}"));
|
||||
// Python returns the dict of accepted keys: compare through the same names.
|
||||
let s = &got.sampling;
|
||||
let mut mine = serde_json::Map::new();
|
||||
let mut put = |k: &str, v: Option<Value>| {
|
||||
if let Some(v) = v {
|
||||
mine.insert(k.into(), v);
|
||||
}
|
||||
};
|
||||
put("temperature", s.temperature.map(|v| json!(v)));
|
||||
put("top_p", s.top_p.map(|v| json!(v)));
|
||||
put("min_p", s.min_p.map(|v| json!(v)));
|
||||
put("top_k", s.top_k.map(|v| json!(v)));
|
||||
put("presence_penalty", s.presence_penalty.map(|v| json!(v)));
|
||||
put("frequency_penalty", s.frequency_penalty.map(|v| json!(v)));
|
||||
put("repetition_penalty", s.repetition_penalty.map(|v| json!(v)));
|
||||
put("penalty_last_n", s.penalty_last_n.map(|v| json!(v)));
|
||||
put("seed", s.seed.map(|v| json!(v)));
|
||||
put(
|
||||
"experimental_speed_projection",
|
||||
got.experimental_speed_projection.map(|v| json!(v)),
|
||||
);
|
||||
assert_eq!(&Value::Object(mine), ok, "{input}");
|
||||
assert_eq!(
|
||||
got.ignored.len(),
|
||||
case["ignored"].as_array().unwrap().len(),
|
||||
"{input}"
|
||||
);
|
||||
}
|
||||
(None, Some(error)) => {
|
||||
assert_eq!(got.unwrap_err(), error.as_str().unwrap(), "{input}");
|
||||
agreed_errors += 1;
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
assert!(agreed_errors >= 14);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//! `request_timings` and `Service.set_aliases` against the Original's real Python
|
||||
//! (fixture from `control-plane/tests/golden/gen_goldens.py timings`).
|
||||
|
||||
use leleka_serving_policy::shared::normalize_aliases;
|
||||
use leleka_serving_policy::timings::{Last, request_timings};
|
||||
use serde_json::Value;
|
||||
|
||||
fn fixture() -> Value {
|
||||
serde_json::from_str(include_str!("fixtures/timings.json")).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timings_equal_python() {
|
||||
let fixture = fixture();
|
||||
let cases = fixture["timings"].as_array().unwrap();
|
||||
assert!(cases.len() > 30);
|
||||
for case in cases {
|
||||
let last = &case["last"];
|
||||
let prompt_tokens = case["prompt_tokens"].as_u64().unwrap();
|
||||
let generated = case["generated"].as_u64().unwrap();
|
||||
if last.as_object().is_some_and(|o| o.is_empty()) {
|
||||
continue; // MockEngine keeps no clock: Python answers None and the caller shows null
|
||||
}
|
||||
let got = request_timings(
|
||||
&Last {
|
||||
prompt_tokens,
|
||||
generated: last["generated"].as_u64().unwrap_or(0),
|
||||
prompt_ms: last["prompt_ms"].as_f64().unwrap(),
|
||||
decode_ms: last["decode_ms"].as_f64().unwrap_or(0.0),
|
||||
reused: last["reused"].as_u64(),
|
||||
drafts_offered: last["drafts_offered"].as_u64(),
|
||||
drafts_accepted: last["drafts_accepted"].as_u64(),
|
||||
},
|
||||
generated,
|
||||
);
|
||||
assert_eq!(got, case["timings"], "{case}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aliases_equal_python() {
|
||||
for case in fixture()["aliases"].as_array().unwrap() {
|
||||
let got = normalize_aliases(&case["input"], "m");
|
||||
match (case.get("ok"), case.get("error")) {
|
||||
(Some(ok), None) => assert_eq!(serde_json::json!(got.unwrap()), *ok, "{case}"),
|
||||
(None, Some(error)) => assert_eq!(got.unwrap_err(), error.as_str().unwrap(), "{case}"),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
//! The image path against the Original: the SVE1 reader and M-RoPE table against the verbatim C++ block
|
||||
//! (`oracle/build_oracle.sh`), image sources, base64 and the pad expansion against the real Python
|
||||
//! (`control-plane/tests/golden/gen_goldens.py vision`).
|
||||
|
||||
use leleka_serving_policy::vision::{
|
||||
IMAGE_PAD_ID, ImageKey, b64decode, build_positions, expand_image_pads, identity_table,
|
||||
image_source, parse_embeddings,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
fn unhex(text: &str) -> Vec<u8> {
|
||||
(0..text.len() / 2)
|
||||
.map(|i| u8::from_str_radix(&text[2 * i..2 * i + 2], 16).unwrap())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embeddings_and_positions_equal_the_engine_block() {
|
||||
let fixture: Value = serde_json::from_str(include_str!("fixtures/vision_oracle.json")).unwrap();
|
||||
let cases = fixture["cases"].as_array().unwrap();
|
||||
assert!(cases.len() >= 20);
|
||||
let (mut errors, mut ok) = (0, 0);
|
||||
for case in cases {
|
||||
let name = case["name"].as_str().unwrap();
|
||||
let n_embd = case["n_embd"].as_i64().unwrap();
|
||||
let cells = case["cells"].as_u64().unwrap() as usize;
|
||||
let geni = case["geni"].as_bool().unwrap();
|
||||
let identity = case["mrope_identity"].as_bool().unwrap();
|
||||
let ids: Vec<i64> = case["ids"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|v| v.as_i64().unwrap())
|
||||
.collect();
|
||||
let file = unhex(case["file_hex"].as_str().unwrap());
|
||||
let want_error = case["ve"].as_str().unwrap();
|
||||
let want_table: Vec<[i32; 3]> = case["table"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.chunks(3)
|
||||
.map(|c| [0, 1, 2].map(|i| c[i].as_i64().unwrap() as i32))
|
||||
.collect();
|
||||
|
||||
// A text request (or a leftover identity) runs the block only to reset the table.
|
||||
if !geni {
|
||||
assert_eq!(want_table, identity_table(cells), "{name}");
|
||||
assert_eq!(want_error, "", "{name}");
|
||||
let _ = identity;
|
||||
ok += 1;
|
||||
continue;
|
||||
}
|
||||
let result = if file.is_empty() {
|
||||
// The engine could not open the file at all.
|
||||
Err("cannot open /nonexistent/embeddings.sve".to_owned())
|
||||
} else {
|
||||
parse_embeddings(&file, n_embd).and_then(|embeddings| {
|
||||
build_positions(&ids, cells, &embeddings, n_embd, IMAGE_PAD_ID)
|
||||
.map(|positions| (embeddings, positions))
|
||||
})
|
||||
};
|
||||
match result {
|
||||
Err(message) => {
|
||||
assert_eq!(message, want_error, "{name}");
|
||||
errors += 1;
|
||||
}
|
||||
Ok((_, positions)) => {
|
||||
assert_eq!(want_error, "", "{name}");
|
||||
assert_eq!(positions.table, want_table, "{name}");
|
||||
let want_rows: Vec<Option<usize>> = case["row_offset"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|v| usize::try_from(v.as_i64().unwrap()).ok())
|
||||
.collect();
|
||||
assert_eq!(positions.row_offset, want_rows, "{name}");
|
||||
let want_keys: Vec<ImageKey> = case["imgs"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|v| ImageKey {
|
||||
start: v[0].as_i64().unwrap(),
|
||||
hash: u64::from_str_radix(v[1].as_str().unwrap(), 16).unwrap(),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(positions.images, want_keys, "{name}");
|
||||
ok += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(ok >= 9 && errors >= 10, "ok {ok}, errors {errors}");
|
||||
}
|
||||
|
||||
fn python() -> Value {
|
||||
serde_json::from_str(include_str!("fixtures/vision.json")).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base64_equals_pythons_decoder() {
|
||||
for case in python()["base64"].as_array().unwrap() {
|
||||
let text = case["text"].as_str().unwrap();
|
||||
match (case.get("ok"), case.get("error")) {
|
||||
(Some(ok), None) => assert_eq!(
|
||||
b64decode(text).unwrap_or_else(|e| panic!("{text:?}: {e}")),
|
||||
unhex(ok.as_str().unwrap()),
|
||||
"{text:?}"
|
||||
),
|
||||
(None, Some(error)) => {
|
||||
let want = error.as_str().unwrap().trim_start_matches("Error: ");
|
||||
assert_eq!(b64decode(text).unwrap_err(), want, "{text:?}");
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_sources_equal_the_frontend() {
|
||||
for case in python()["sources"].as_array().unwrap() {
|
||||
assert_eq!(
|
||||
image_source(&case["part"]),
|
||||
case["source"].as_str().unwrap(),
|
||||
"{}",
|
||||
case["part"]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pad_expansion_equals_service_prepare() {
|
||||
let fixture = python();
|
||||
let mut expanded = 0;
|
||||
for case in fixture["prepare"].as_array().unwrap() {
|
||||
let to_u32 = |v: &Value| -> Vec<u32> {
|
||||
v.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|x| x.as_u64().unwrap() as u32)
|
||||
.collect()
|
||||
};
|
||||
let ids = to_u32(&case["ids_before"]);
|
||||
if case["images"].as_array().unwrap().is_empty() {
|
||||
// No images: `prepare` leaves the prompt alone (a literal marker stays a special token).
|
||||
assert_eq!(to_u32(&case["ids_after"]), ids);
|
||||
continue;
|
||||
}
|
||||
let counts: Vec<usize> = case["images"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|source| case["counts"][source.as_str().unwrap()].as_u64().unwrap() as usize)
|
||||
.collect();
|
||||
let got = expand_image_pads(
|
||||
&ids,
|
||||
case["pad"].as_u64().unwrap() as u32,
|
||||
case["start"].as_u64().unwrap() as u32,
|
||||
&to_u32(&case["literal"]),
|
||||
&counts,
|
||||
);
|
||||
match (case.get("ids_after"), case.get("error")) {
|
||||
(Some(after), _) => {
|
||||
assert_eq!(got.unwrap(), to_u32(after), "{}", case["messages"]);
|
||||
expanded += 1;
|
||||
}
|
||||
(None, Some(error)) => assert_eq!(got.unwrap_err(), error.as_str().unwrap()),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
assert!(expanded >= 5);
|
||||
}
|
||||
@@ -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"] }
|
||||
|
||||
@@ -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; }
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -522,6 +522,7 @@ mod tests {
|
||||
prompt: String::new(),
|
||||
max_output_tokens: 1,
|
||||
temperature_milli: 0,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -13,6 +13,7 @@ use axum::{
|
||||
response::{IntoResponse, Response},
|
||||
routing::{get, post},
|
||||
};
|
||||
use leleka_sampler_ref::params::FixedPoint;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use std::{collections::HashSet, net::SocketAddr, sync::Arc, time::Duration};
|
||||
@@ -418,12 +419,12 @@ async fn status(State(r): State<Registry>, h: HeaderMap) -> Response {
|
||||
}
|
||||
Json(json!({"schema_version":1,"runtimes":states})).into_response()
|
||||
}
|
||||
fn render(v: &Value) -> Result<(String, u32), &'static str> {
|
||||
fn render(v: &Value) -> Result<(String, u32, FixedPoint), &'static str> {
|
||||
let o = v.as_object().ok_or("invalid_json")?;
|
||||
for (key, value) in o {
|
||||
match key.as_str() {
|
||||
"model" | "input" | "instructions" | "stream" | "max_output_tokens" => {}
|
||||
"temperature" if value.as_f64() == Some(0.0) => {}
|
||||
key if leleka_serving_policy::fixed::SAMPLING_KEYS.contains(&key) => {}
|
||||
"store" if value == &Value::Bool(false) => {}
|
||||
"tools" if value.as_array().is_some_and(Vec::is_empty) => {}
|
||||
"text" if value == &json!({"format":{"type":"text"}}) => {}
|
||||
@@ -433,6 +434,7 @@ fn render(v: &Value) -> Result<(String, u32), &'static str> {
|
||||
if o.get("stream").is_some_and(|v| !v.is_boolean()) {
|
||||
return Err("invalid_stream");
|
||||
}
|
||||
let sampling = crate::runtime_sampling::from_json(o)?;
|
||||
let cap = o
|
||||
.get("max_output_tokens")
|
||||
.map(|v| v.as_u64().ok_or("invalid_output_limit"))
|
||||
@@ -507,7 +509,7 @@ fn render(v: &Value) -> Result<(String, u32), &'static str> {
|
||||
if prompt.len() > 1024 * 1024 {
|
||||
return Err("prompt_limit");
|
||||
}
|
||||
Ok((prompt, cap as u32))
|
||||
Ok((prompt, cap as u32, sampling))
|
||||
}
|
||||
fn response_value(id: &str, model: &str, text: &str, status: &str, usage: &proto::Usage) -> Value {
|
||||
json!({"id":id,"object":"response","created_at":std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0,|v|v.as_secs()),"model":model,"status":status,"output":[{"id":format!("msg_{id}"),"type":"message","role":"assistant","status":status,"content":[{"type":"output_text","text":text,"annotations":[]}]}],"usage":{"input_tokens":usage.input_tokens,"output_tokens":usage.output_tokens,"total_tokens":usage.input_tokens.saturating_add(usage.output_tokens),"input_tokens_details":{"cached_tokens":usage.reused_input_tokens}},"error":null,"incomplete_details":if status=="incomplete"{json!({"reason":"max_output_tokens"})}else{Value::Null}})
|
||||
@@ -638,7 +640,7 @@ async fn responses(State(r): State<Registry>, h: HeaderMap, body: Bytes) -> Resp
|
||||
if r.0.experimental_native_tools && needs_tool_adapter(&v) {
|
||||
return tool_responses(r, index, v).await;
|
||||
}
|
||||
let (prompt, cap) = match render(&v) {
|
||||
let (prompt, cap, sampling) = match render(&v) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return error(StatusCode::BAD_REQUEST, e),
|
||||
};
|
||||
@@ -649,19 +651,16 @@ async fn responses(State(r): State<Registry>, h: HeaderMap, body: Bytes) -> Resp
|
||||
return error(StatusCode::SERVICE_UNAVAILABLE, "model_not_ready");
|
||||
};
|
||||
let request_id = uuid::Uuid::new_v4().to_string();
|
||||
let stream = match accepted(
|
||||
&mut client,
|
||||
proto::GenerateRequest {
|
||||
request_id: request_id.clone(),
|
||||
expected_epoch: snapshot.epoch,
|
||||
handle: loaded.handle,
|
||||
prompt,
|
||||
max_output_tokens: cap,
|
||||
temperature_milli: 0,
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
let mut generate = proto::GenerateRequest {
|
||||
request_id: request_id.clone(),
|
||||
expected_epoch: snapshot.epoch,
|
||||
handle: loaded.handle,
|
||||
prompt,
|
||||
max_output_tokens: cap,
|
||||
..Default::default()
|
||||
};
|
||||
crate::runtime_sampling::apply(&mut generate, &sampling);
|
||||
let stream = match accepted(&mut client, generate).await {
|
||||
Ok(s) => s,
|
||||
Err(_) => return error(StatusCode::BAD_GATEWAY, "runtime_dispatch_failed"),
|
||||
};
|
||||
@@ -869,14 +868,15 @@ async fn tool_responses(registry: Registry, index: usize, value: Value) -> Respo
|
||||
return error(StatusCode::SERVICE_UNAVAILABLE, "model_not_ready");
|
||||
};
|
||||
let request_id = uuid::Uuid::new_v4().to_string();
|
||||
let request = proto::GenerateRequest {
|
||||
let mut request = proto::GenerateRequest {
|
||||
request_id: request_id.clone(),
|
||||
expected_epoch: snapshot.epoch,
|
||||
handle: loaded.handle,
|
||||
prompt: plan.prompt.clone(),
|
||||
max_output_tokens: plan.max_output_tokens,
|
||||
temperature_milli: 0,
|
||||
..Default::default()
|
||||
};
|
||||
crate::runtime_sampling::apply(&mut request, &plan.sampling);
|
||||
let stream = match accepted(&mut client, request.clone()).await {
|
||||
Ok(stream) => stream,
|
||||
Err(_) => return error(StatusCode::BAD_GATEWAY, "runtime_dispatch_failed"),
|
||||
@@ -943,9 +943,15 @@ async fn tool_responses(registry: Registry, index: usize, value: Value) -> Respo
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn runtime_gateway_refuses_silent_sampling_tools_and_state() {
|
||||
fn runtime_gateway_refuses_tools_state_and_out_of_contract_sampling() {
|
||||
for extra in [
|
||||
json!({"temperature":0.5}),
|
||||
json!({"temperature":2.5}),
|
||||
json!({"temperature":0.1234}),
|
||||
json!({"top_p":1.5}),
|
||||
json!({"top_k":1.5}),
|
||||
json!({"seed":-1}),
|
||||
json!({"repetition_penalty":0}),
|
||||
json!({"stop":["x"]}),
|
||||
json!({"tools":[{"type":"function","name":"run"}]}),
|
||||
json!({"previous_response_id":"resp_x"}),
|
||||
json!({"store":true}),
|
||||
@@ -958,12 +964,38 @@ mod tests {
|
||||
.extend(extra.as_object().unwrap().clone());
|
||||
assert!(render(&value).is_err());
|
||||
}
|
||||
let (prompt, limit) =
|
||||
let (prompt, limit, greedy) =
|
||||
render(&json!({"model":"native","input":"hello","max_output_tokens":2,"store":false}))
|
||||
.unwrap();
|
||||
assert_eq!(limit, 2);
|
||||
assert_eq!(greedy, FixedPoint::default());
|
||||
assert!(prompt.ends_with("<|im_start|>assistant\n<think>\n\n</think>\n\n"));
|
||||
}
|
||||
#[test]
|
||||
fn runtime_gateway_forwards_the_full_sampling_contract_to_the_runtime_request() {
|
||||
let (_, _, fixed) = render(&json!({
|
||||
"model":"native","input":"hello","temperature":0.7,"top_p":0.9,"top_k":40,"min_p":0.05,
|
||||
"repetition_penalty":1.1,"frequency_penalty":0.25,"presence_penalty":-0.5,
|
||||
"penalty_last_n":128,"seed":42
|
||||
}))
|
||||
.unwrap();
|
||||
let mut request = proto::GenerateRequest::default();
|
||||
crate::runtime_sampling::apply(&mut request, &fixed);
|
||||
assert_eq!(request.temperature_milli, 700);
|
||||
assert_eq!(request.top_p_micro, Some(900_000));
|
||||
assert_eq!(request.top_k, Some(40));
|
||||
assert_eq!(request.min_p_micro, Some(50_000));
|
||||
assert_eq!(request.repetition_penalty_micro, Some(1_100_000));
|
||||
assert_eq!(request.frequency_penalty_micro, Some(250_000));
|
||||
assert_eq!(request.presence_penalty_micro, Some(-500_000));
|
||||
assert_eq!(request.penalty_last_n, Some(128));
|
||||
assert_eq!(request.seed, Some(42));
|
||||
let backend = crate::runtime_sampling::to_backend(&request).unwrap();
|
||||
assert_eq!(backend.top_p_micro, Some(900_000));
|
||||
assert_eq!(backend.seed, Some(42));
|
||||
request.top_p_micro = Some(1_000_001);
|
||||
assert!(crate::runtime_sampling::to_backend(&request).is_err());
|
||||
}
|
||||
fn trace() -> Trace {
|
||||
Trace {
|
||||
id: "resp_test".into(),
|
||||
|
||||
@@ -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")]
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
//! Sampling controls on the runtime gRPC contract: JSON request fields <-> fixed point <->
|
||||
//! `runtime.proto` `GenerateRequest` <-> `backend-api` `SamplingOptions`. The arithmetic and the
|
||||
//! Original's ranges live in `leleka-serving-policy` (tested on every host); this file is the thin
|
||||
//! field-by-field mapping.
|
||||
|
||||
use leleka_backend_api::SamplingOptions;
|
||||
use leleka_sampler_ref::params::FixedPoint;
|
||||
use leleka_serving_policy::fixed::{error_code, sampling_from_object, to_fixed_point};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::runtime_rpc::proto;
|
||||
|
||||
/// Read and validate the sampling fields of a Responses request object.
|
||||
pub(crate) fn from_json(object: &Map<String, Value>) -> Result<FixedPoint, &'static str> {
|
||||
let sampling = sampling_from_object(object).map_err(|e| error_code(&e))?;
|
||||
to_fixed_point(&sampling).map_err(|e| error_code(&e))
|
||||
}
|
||||
|
||||
/// Put the sampling controls on a runtime request.
|
||||
pub(crate) fn apply(request: &mut proto::GenerateRequest, fixed: &FixedPoint) {
|
||||
request.temperature_milli = fixed.temperature_milli;
|
||||
request.top_p_micro = fixed.top_p_micro;
|
||||
request.top_k = fixed.top_k;
|
||||
request.min_p_micro = fixed.min_p_micro;
|
||||
request.repetition_penalty_micro = fixed.repetition_penalty_micro;
|
||||
request.frequency_penalty_micro = fixed.frequency_penalty_micro;
|
||||
request.presence_penalty_micro = fixed.presence_penalty_micro;
|
||||
request.penalty_last_n = fixed.penalty_last_n;
|
||||
request.seed = fixed.seed;
|
||||
}
|
||||
|
||||
/// Validate a received request's controls at the RPC boundary (the backend validates again) and
|
||||
/// convert them for the backend.
|
||||
pub(crate) fn to_backend(command: &proto::GenerateRequest) -> Result<SamplingOptions, ()> {
|
||||
let fixed = FixedPoint {
|
||||
temperature_milli: command.temperature_milli,
|
||||
top_p_micro: command.top_p_micro,
|
||||
top_k: command.top_k,
|
||||
min_p_micro: command.min_p_micro,
|
||||
repetition_penalty_micro: command.repetition_penalty_micro,
|
||||
frequency_penalty_micro: command.frequency_penalty_micro,
|
||||
presence_penalty_micro: command.presence_penalty_micro,
|
||||
penalty_last_n: command.penalty_last_n,
|
||||
seed: command.seed,
|
||||
};
|
||||
// The same contract as the HTTP boundary: the ranges of `RequestSampling::validate`.
|
||||
leleka_sampler_ref::RequestSampling::from_fixed_point(&fixed)
|
||||
.validate()
|
||||
.map_err(|_| ())?;
|
||||
Ok(SamplingOptions {
|
||||
top_p_micro: fixed.top_p_micro,
|
||||
top_k: fixed.top_k,
|
||||
min_p_micro: fixed.min_p_micro,
|
||||
repetition_penalty_micro: fixed.repetition_penalty_micro,
|
||||
frequency_penalty_micro: fixed.frequency_penalty_micro,
|
||||
presence_penalty_micro: fixed.presence_penalty_micro,
|
||||
penalty_last_n: fixed.penalty_last_n,
|
||||
seed: fixed.seed,
|
||||
})
|
||||
}
|
||||
@@ -18,6 +18,7 @@ pub struct ToolPlan {
|
||||
pub prompt: String,
|
||||
pub max_output_tokens: u32,
|
||||
pub policy: ToolPolicy,
|
||||
pub sampling: leleka_sampler_ref::params::FixedPoint,
|
||||
}
|
||||
|
||||
pub enum ValidatedSegment {
|
||||
@@ -400,6 +401,14 @@ pub fn prepare(request: &Value) -> Result<ToolPlan, &'static str> {
|
||||
"stream",
|
||||
"max_output_tokens",
|
||||
"temperature",
|
||||
"top_p",
|
||||
"top_k",
|
||||
"min_p",
|
||||
"repetition_penalty",
|
||||
"frequency_penalty",
|
||||
"presence_penalty",
|
||||
"penalty_last_n",
|
||||
"seed",
|
||||
"store",
|
||||
"tools",
|
||||
"tool_choice",
|
||||
@@ -414,14 +423,12 @@ pub fn prepare(request: &Value) -> Result<ToolPlan, &'static str> {
|
||||
return Err("invalid_stream");
|
||||
}
|
||||
if object
|
||||
.get("temperature")
|
||||
.is_some_and(|v| v.as_f64() != Some(0.0))
|
||||
|| object
|
||||
.get("store")
|
||||
.is_some_and(|v| v != &Value::Bool(false))
|
||||
.get("store")
|
||||
.is_some_and(|v| v != &Value::Bool(false))
|
||||
{
|
||||
return Err("unsupported_sampling_or_store");
|
||||
}
|
||||
let sampling = crate::runtime_sampling::from_json(object)?;
|
||||
if object
|
||||
.get("text")
|
||||
.is_some_and(|v| v != &json!({"format":{"type":"text"}}))
|
||||
@@ -493,6 +500,7 @@ pub fn prepare(request: &Value) -> Result<ToolPlan, &'static str> {
|
||||
prompt,
|
||||
max_output_tokens: cap as u32,
|
||||
policy,
|
||||
sampling,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+80
-4
@@ -29,7 +29,9 @@ Supported inputs:
|
||||
- assistant `tool_calls` (`id`, `type: function`, `function.name/arguments`) and
|
||||
tool `tool_call_id`/text; complete returned assistant messages can be reused;
|
||||
- function tools, `auto`/`none`/`required` or a forced function name,
|
||||
`parallel_tool_calls`, temperature and top_p;
|
||||
`parallel_tool_calls`, temperature and top_p, and the sampling controls listed under
|
||||
"Sampling controls" below (`frequency_penalty`, `presence_penalty`, `seed`, `top_k`, `min_p`,
|
||||
`repetition_penalty`, `penalty_last_n`);
|
||||
- `max_completion_tokens` or the older `max_tokens` alias (not both), `n: 1`;
|
||||
- `response_format` text, json_object, or json_schema containing name/schema/strict
|
||||
under `json_schema`; the same native schema subset and final validation apply.
|
||||
@@ -40,7 +42,7 @@ Supported inputs:
|
||||
This first subset always uses `reasoning_effort: none` (also the default here)
|
||||
and `store: false`; no hidden reasoning is requested or returned. Other efforts,
|
||||
storage, multiple choices, multimodal input/output, custom/namespace tools,
|
||||
custom stop sequences, log probabilities, nonzero presence/frequency penalties,
|
||||
custom stop sequences, log probabilities,
|
||||
schema descriptions, non-null refusal text and unknown fields are rejected before
|
||||
worker generation. It does not implement the full upstream API or stored Chat
|
||||
retrieval. Omitted optional values use existing Responses defaults, including its
|
||||
@@ -74,7 +76,7 @@ Claude model or an Anthropic cloud service.
|
||||
Inputs are `model`, required positive `max_tokens`, optional `system` text/blocks,
|
||||
user/assistant `messages`, `tools` with name/description/input_schema, `tool_choice`
|
||||
(`auto`, `any`, `tool` with name, `none`) and `disable_parallel_tool_use`, `stream`,
|
||||
temperature (0..1) and top_p. Text parts join with newlines; consecutive turns of
|
||||
temperature (0..1), top_p and top_k (plus the extension controls under "Sampling controls"). Text parts join with newlines; consecutive turns of
|
||||
the same role combine. This initial subset requires first and last user messages;
|
||||
assistant prefill is rejected. Assistant `tool_use` carries an object `input` and
|
||||
ID; user `tool_result` returns the same `tool_use_id` and text or text blocks.
|
||||
@@ -90,7 +92,7 @@ Tool names, arguments, results and choice policies reuse native validation.
|
||||
|
||||
Thinking is disabled (omitted or `{"type":"disabled"}`); requests are stateless.
|
||||
Thinking/redacted signatures, images/documents, cache_control, nonempty
|
||||
stop_sequences, server tools, top_k, metadata, structured-output options,
|
||||
stop_sequences, server tools, metadata, structured-output options,
|
||||
beta headers and unknown fields are rejected before GEN. This does not implement all Messages features or certify a Claude SDK agent.
|
||||
|
||||
`POST /v1/messages/count_tokens` follows the [token count response shape](https://platform.claude.com/docs/en/api/messages/count_tokens)
|
||||
@@ -138,6 +140,80 @@ Unicode, system/combined turns, tools/continuation, usage, headers/errors,
|
||||
admission/drain and live disconnect→STOP→fresh generation. Existing Chat/auth
|
||||
regressions run alongside it; real-model/harness/GPU qualification remains open.
|
||||
|
||||
## Sampling controls
|
||||
|
||||
Every route that generates (Responses, Chat Completions, Messages) takes the Original server's
|
||||
sampling fields at the top level of the request body, with the Original's defaults (an absent field
|
||||
keeps the engine's greedy default) and ranges, and fails closed on a value outside them
|
||||
(`crates/sampler-ref` `RequestSampling`, `docs/sampler-reference.md`):
|
||||
|
||||
| Field | Range | Notes |
|
||||
| --- | --- | --- |
|
||||
| `temperature` | 0..2 | `0` is greedy (Messages: 0..1) |
|
||||
| `top_p` | 0..1 | `1` disables nucleus filtering |
|
||||
| `top_k` | integer >= 0 | the sampler keeps at most 64: `0` and values above 64 use 64 |
|
||||
| `min_p` | 0..1 | |
|
||||
| `repetition_penalty` | > 0 | `1` is off |
|
||||
| `frequency_penalty`, `presence_penalty` | -2..2 | |
|
||||
| `penalty_last_n` | 0..2147483647 | a penalty without a window uses the last 64 tokens; the kernel caps the history at 4096 |
|
||||
| `seed` | unsigned integer | `0` or absent draws a fresh clock seed per request |
|
||||
| `strata_tune` | `{pcie_frac, spec_min_p}` in 0..1 | engine settings for this request only |
|
||||
| `experimental_speed_projection` | boolean | switches a loaded control vector for this request (`cvec=0|1`) |
|
||||
| `reasoning_budget_tokens` | whole number, `0` = none | see "Reasoning budget" |
|
||||
|
||||
The worker `GEN` line is built by the same code the Python server's `StrataEngine.sampling_keys`
|
||||
is checked against (`control-plane/tests/fixtures/golden/gen_lines.json`, produced by running that
|
||||
code). The Chat route no longer refuses nonzero presence/frequency penalties.
|
||||
|
||||
Server-wide defaults fill what a request leaves out: the config `sampling` block, then the Chat
|
||||
settings shared through `POST /settings`; the request always wins and an explicit `temperature: 0`
|
||||
stays greedy. A shared `max_tokens` and `reasoning_effort` apply to Responses requests that carry none
|
||||
(Chat and Messages fix their own effort).
|
||||
|
||||
### Reasoning budget
|
||||
|
||||
With thinking on, a request's `reasoning_budget_tokens` (else the config's) caps how long the model
|
||||
may think. At the budget, on a clean token boundary (no `</think>` prefix held back, no UTF-8
|
||||
character split), the worker stops the pass, appends the Original's wrap-up text
|
||||
(`"I have thought about this long enough; time to give my answer.\n</think>\n\n"`) to the output
|
||||
and continues from `prompt + generated + wrap-up`, so the engine keeps its cached prefix. If the
|
||||
wrap-up leaves no room to answer the request ends as `length`. The client sees one token stream and
|
||||
one `DONE`: `generated` counts delivered tokens, `prompt_tokens`/`reused` are the first pass's,
|
||||
timings are summed.
|
||||
|
||||
## Operational surface
|
||||
|
||||
Ported from `engine/strata/serve/server.py` and replayed against the real Python handlers in
|
||||
`control-plane/tests/http_surface.rs`:
|
||||
|
||||
- `GET /props` (llama-server compatible: default generation settings from the config and shared
|
||||
settings, chat template, `models_autoload`, `is_sleeping`), `GET /slots`, `GET /v1/status`,
|
||||
`GET /api/health` (the Python `/health` body; `/health` keeps the minimal liveness body);
|
||||
- `GET|POST /settings` (shared Chat settings, persisted next to the config; JSON from the server's
|
||||
own page or a `trusted_origins` origin only);
|
||||
- `POST /load`, `POST /unload`, `POST /v1/load`, `POST /v1/unload` (own page, JSON object, `409
|
||||
model_busy` while a request runs or waits), lazy start (`engine.lazy_load`), idle unload
|
||||
(`engine.idle_unload_s`), reload gates (`engine.before_load`, `engine.min_free_vram_mib`); the next
|
||||
request after an unload loads the engine again;
|
||||
- CORS for `/v1/*` (`cors_origins`, `"*"` allowed) with the preflight answered before
|
||||
authentication; model `aliases`; unknown paths answer `{"error":{"message":"not found"}}`;
|
||||
- engine stall watchdog (`engine.stall_timeout_s`): no engine line for that long during a request
|
||||
ends the engine, fails the request with a clear error and uses the restart budget.
|
||||
- MCP hub (`control-plane/src/mcp.rs`, tested against `engine/strata/serve/mcp_fake_server.py` in
|
||||
`control-plane/tests/mcp_hub.rs`): `mcp_servers` / Claude Desktop's `mcpServers` / `mcp_config_file`
|
||||
and the `mcp` block (`timeout_s`, `max_result_chars`, `max_rounds`, `start_timeout_s`) are
|
||||
validated at start; stdio and Streamable HTTP servers start in the background, tools are listed
|
||||
(all pages) and namespaced `<server>__<tool>`, a server that stopped is started again by its next
|
||||
call, results are text capped at `max_result_chars`, failures become `error:` text, a cancelled call
|
||||
sends `notifications/cancelled`. `GET /mcp` (authenticated) reports servers, state and tools
|
||||
(`{"servers":[],"tools":0}` when none). Not ported on purpose: the server-side tool loop
|
||||
(`strata_mcp: true`, `run_with_mcp`) of the Python web page. Responses, Chat and Messages return
|
||||
tool calls to the client, so no endpoint executes MCP tools on a client's behalf.
|
||||
|
||||
Differences from the Python server: authentication is Bearer on every path except `/health` and
|
||||
`/api/health` (the Messages routes also take `x-api-key`), unknown paths need authentication too, and
|
||||
error bodies of the Rust authentication layer are its own.
|
||||
|
||||
## Model discovery
|
||||
|
||||
`GET /v1/models` returns the single configured `model` / `STRATA_MODEL_ID`, or
|
||||
|
||||
@@ -50,9 +50,10 @@ Requests without a seed take a clock seed (the Original's `seed = 0`).
|
||||
have never run. The serving path therefore samples on the host from the Q6 head's full logits. Switching it to the
|
||||
GPU sampler is a later step once the asset is pinned; the token contract is the same.
|
||||
* Sampling with MTP is refused (`sampling is unavailable with MTP`): coupled draft sampling is not wired into the actor.
|
||||
* The desktop gRPC protocol still carries only `temperature_milli`; top_p/top_k/min_p/penalties/seed need a proto bump.
|
||||
The control plane's C++ worker wire (`wire.rs`) still forwards only temperature and top_p; `RequestSampling::gen_keys`
|
||||
is the tested replacement.
|
||||
* ~~The desktop gRPC protocol still carries only `temperature_milli`~~ -- done: `runtime.proto` `GenerateRequest` carries
|
||||
top_p/top_k/min_p/penalties/penalty_last_n/seed (fixed point), `desktop-core` validates and forwards them, the
|
||||
gateway no longer refuses `temperature != 0`; the control plane's `wire.rs` builds `GEN`/`GENI` lines with
|
||||
`RequestSampling::gen_keys` (golden-tested against the Python server). See `docs/api-contract.md`.
|
||||
* Float caveat: `exp`/`ln` use the platform libm. Device `exp` (f64) and `logf` can differ by 1 ulp from the host and
|
||||
nvcc `--fmad=true` may contract `count*freq + flag*present`; these can change a pick only on cumulative-boundary
|
||||
or threshold ties. Compare GPU output with the fixtures and report disagreements; do not treat them as noise.
|
||||
|
||||
Reference in New Issue
Block a user