diff --git a/control-plane/src/app.rs b/control-plane/src/app.rs index 1e2e1704..03a90359 100644 --- a/control-plane/src/app.rs +++ b/control-plane/src/app.rs @@ -41,6 +41,8 @@ pub struct AppState { pub chat_template: Option>, /// The MCP servers configured for the operator (`GET /mcp`). pub mcp: Option>, + /// The resident image encoder (`vision` in the config); `None`: this server cannot read images. + pub vision: Option>, } impl Default for AppState { @@ -62,6 +64,7 @@ impl Default for AppState { started_at: std::time::SystemTime::now(), chat_template: None, mcp: None, + vision: None, } } } diff --git a/control-plane/src/chat.rs b/control-plane/src/chat.rs index 0f0122b6..260cb409 100644 --- a/control-plane/src/chat.rs +++ b/control-plane/src/chat.rs @@ -91,26 +91,105 @@ type Invalid = (&'static str, &'static str); fn invalid(param: &'static str, message: &'static str) -> Invalid { (param, message) } -fn content(value: Option) -> Result, Invalid> { +/// A message's content: plain text, or (user messages only) the list of text and picture parts in the Responses +/// shape (`input_text` / `input_image`), whose order the template keeps. +enum Content { + Text(String), + Parts(Vec), +} + +impl Content { + fn text(self) -> Option { + match self { + Self::Text(text) => Some(text), + Self::Parts(_) => None, + } + } + + fn into_value(self) -> Value { + match self { + Self::Text(text) => Value::String(text), + Self::Parts(parts) => Value::Array(parts), + } + } +} + +/// An `image_url` part (`serve/frontend.py` `_image_source`): `"image_url": {"url": ..., "detail": ...}` or the bare +/// string. The source itself is checked when it is read, so an empty one fails there with the Python server's words. +fn image_part(part: &serde_json::Map) -> Result { + let bad = || { + invalid( + "messages", + "image_url parts need an image_url of text or {url, detail}", + ) + }; + if part + .keys() + .any(|k| !matches!(k.as_str(), "type" | "image_url")) + { + return Err(bad()); + } + let url = match part.get("image_url") { + None | Some(Value::Null) => String::new(), + Some(Value::String(url)) => url.clone(), + Some(Value::Object(object)) => { + if object + .keys() + .any(|k| !matches!(k.as_str(), "url" | "detail")) + { + return Err(bad()); + } + match object.get("url") { + None | Some(Value::Null) => String::new(), + Some(Value::String(url)) => url.clone(), + _ => return Err(bad()), + } + } + _ => return Err(bad()), + }; + Ok(json!({"type": "input_image", "image_url": url})) +} + +fn content(value: Option, role: &str) -> Result, Invalid> { match value { None | Some(Value::Null) => Ok(None), - Some(Value::String(s)) => Ok(Some(s)), + Some(Value::String(s)) => Ok(Some(Content::Text(s))), Some(Value::Array(parts)) => { let mut text = String::new(); + let mut listed = Vec::new(); + let mut pictures = false; for part in parts { let object = part .as_object() .ok_or(invalid("messages", "content must contain text parts"))?; - if object.len() != 2 || part["type"] != "text" { - return Err(invalid("messages", "only text content parts are supported")); + if part["type"] == "image_url" { + if role != "user" { + return Err(invalid( + "messages", + "image content is only supported in user messages", + )); + } + pictures = true; + listed.push(image_part(object)?); + continue; } - text.push_str( - part["text"] - .as_str() - .ok_or(invalid("messages", "text part needs a string"))?, - ); + if object.len() != 2 || part["type"] != "text" { + return Err(invalid( + "messages", + "only text and image_url content parts are supported", + )); + } + let piece = part["text"] + .as_str() + .ok_or(invalid("messages", "text part needs a string"))?; + text.push_str(piece); + listed.push(json!({"type": "input_text", "text": piece})); } - Ok(Some(text)) + Ok(Some(if pictures { + Content::Parts(listed) + } else { + Content::Text(text) + })) } _ => Err(invalid("messages", "content must be text or text parts")), } @@ -173,7 +252,7 @@ impl Request { if message.refusal.is_some() { return Err(invalid("messages", "refusal content is not supported")); } - let text = content(message.content)?; + let text = content(message.content, &message.role)?; match message.role.as_str() { "system" | "developer" | "user" | "assistant" => { if message.tool_call_id.is_some() @@ -192,7 +271,7 @@ impl Request { )); } if let Some(text) = text { - input.push(json!({"role":message.role,"content":text})); + input.push(json!({"role":message.role,"content":text.into_value()})); } for call in calls { if call.kind != "function" { @@ -208,7 +287,7 @@ impl Request { if message.tool_calls.is_some() { return Err(invalid("messages", "tool result cannot declare tool calls")); } - input.push(json!({"type":"function_call_output", "call_id":message.tool_call_id.ok_or(invalid("messages", "tool result needs tool_call_id"))?, "output":text.ok_or(invalid("messages", "tool result needs text"))?})); + input.push(json!({"type":"function_call_output", "call_id":message.tool_call_id.ok_or(invalid("messages", "tool result needs tool_call_id"))?, "output":text.and_then(Content::text).ok_or(invalid("messages", "tool result needs text"))?})); } _ => return Err(invalid("messages", "unsupported message role")), } diff --git a/control-plane/src/config.rs b/control-plane/src/config.rs index 57570739..f5793841 100644 --- a/control-plane/src/config.rs +++ b/control-plane/src/config.rs @@ -46,6 +46,8 @@ pub struct Config { pub mcp_servers: std::collections::BTreeMap>, /// The `mcp` block: timeouts and caps. pub mcp_settings: crate::mcp::Settings, + /// The image encoder's configuration (started by `serve` before the engine). + pub vision: Option, } #[derive(Default, Deserialize)] @@ -78,6 +80,8 @@ struct FileConfig { mcp_servers_desktop: Option, mcp_config_file: Option, mcp: Option, + /// The image encoder (`strata-vision`): without it the server cannot read pictures. + vision: Option, } #[derive(Deserialize)] @@ -351,6 +355,7 @@ impl Config { min_free_vram_mib: engine_file .and_then(|engine| engine.min_free_vram_mib) .unwrap_or(0), + vision: None, }), Some(_) => return Err("engine executable cannot be empty".into()), None if !args.is_empty() => return Err("engine args require an executable".into()), @@ -516,7 +521,17 @@ impl Config { mcp_servers.extend(crate::mcp::servers_from(block, &location)?); } let mcp_settings = crate::mcp::settings_from(file.mcp.as_ref().unwrap_or(&null))?; + if let Some(vision) = &file.vision { + vision.validate()?; + if worker.is_none() { + return Err("vision requires an engine executable".into()); + } + if worker.as_ref().is_some_and(|worker| worker.lazy) { + return Err("lazy loading is text-only; disable vision in the config".into()); + } + } Ok(Self { + vision: file.vision, mcp_servers, mcp_settings, aliases, @@ -821,4 +836,47 @@ mod tests { ); let _ = fs::remove_dir_all(dir); } + + #[test] + fn vision_section_needs_an_engine_and_is_text_only_when_lazy() { + let dir = temp("vision"); + let vision = json!({"exe": "/v/strata-vision", "mmproj": "/v/mmproj.gguf", "model": "/v/model.gguf", + "gpu": true, "threads": 4, "max_tokens": 1024, "cuda_device": 1}); + let config = load( + &dir, + json!({"engine": {"executable": "/bin/true"}, "vision": vision}), + ) + .unwrap(); + let loaded = config.vision.unwrap(); + assert!(loaded.gpu); + assert_eq!(loaded.cuda_device, Some(1)); + assert_eq!(loaded.max_tokens, Some(1024)); + assert!( + config.worker.unwrap().vision.is_none(), + "serve hands the started encoder to the worker" + ); + assert!( + load(&dir, json!({"vision": vision})) + .err() + .unwrap() + .contains("requires an engine") + ); + assert!( + load( + &dir, + json!({"engine": {"executable": "/bin/true", "lazy_load": true}, "vision": vision}) + ) + .err() + .unwrap() + .contains("text-only") + ); + assert!( + load( + &dir, + json!({"engine": {"executable": "/bin/true"}, "vision": {"exe": "x"}}) + ) + .is_err() + ); + let _ = fs::remove_dir_all(dir); + } } diff --git a/control-plane/src/lib.rs b/control-plane/src/lib.rs index b5e4b31d..e58248b1 100644 --- a/control-plane/src/lib.rs +++ b/control-plane/src/lib.rs @@ -71,3 +71,4 @@ pub mod settings; pub mod mcp; pub mod reasoning_budget; +pub mod vision; diff --git a/control-plane/src/main.rs b/control-plane/src/main.rs index 84bed89b..efa555e2 100644 --- a/control-plane/src/main.rs +++ b/control-plane/src/main.rs @@ -946,8 +946,15 @@ async fn serve(config_path: Option<&Path>) -> Result<(), Box) -> Result<(), Box) -> Result<(), Box, }, } +/// A text block or a picture's source, in a user turn. +enum Piece { + Text(String), + Image(String), +} fn empty_tool_result() -> Value { Value::String(String::new()) } @@ -198,22 +207,49 @@ impl Request { } let mut input = Vec::new(); for (role, parts) in turns { - let mut text = Vec::new(); - let flush = |text: &mut Vec, input: &mut Vec| { - if !text.is_empty() { + // Text and pictures of the turn in the order they came; a picture-free run is one text message. + let mut run: Vec = Vec::new(); + let flush = |run: &mut Vec, input: &mut Vec| { + if run.is_empty() { + return; + } + if run.iter().any(|piece| matches!(piece, Piece::Image(_))) { + // serve/frontend.py `_parts_of`: the items in order, no separator. + let content: Vec = run + .drain(..) + .map(|piece| match piece { + Piece::Text(text) => json!({"type":"input_text","text":text}), + Piece::Image(source) => { + json!({"type":"input_image","image_url":source}) + } + }) + .collect(); + input.push(json!({"role":role,"content":content})); + } else { + let text: Vec = run + .drain(..) + .filter_map(|piece| match piece { + Piece::Text(text) => Some(text), + Piece::Image(_) => None, + }) + .collect(); input.push(json!({"role":role,"content":text.join("\n")})); - text.clear(); } }; for part in parts { match part { - Block::Text { text: t } => text.push(t), + Block::Text { text: t } => run.push(Piece::Text(t)), + Block::Image { source } if role == "user" => { + run.push(Piece::Image(leleka_serving_policy::vision::image_source( + &json!({"type":"image","source":source}), + ))); + } Block::ToolUse { id, name, input: arguments, } if role == "assistant" => { - flush(&mut text, &mut input); + flush(&mut run, &mut input); if !arguments.is_object() { return Err("tool_use.input must be an object".into()); } @@ -224,7 +260,7 @@ impl Request { content, is_error, } if role == "user" => { - flush(&mut text, &mut input); + flush(&mut run, &mut input); let text = text_only(content)?; // The local template has text tool outputs, not a separate error bit. // Keep the bit and exact normalized content together in the tool role. @@ -235,6 +271,9 @@ impl Request { }; input.push(json!({"type":"function_call_output","call_id":tool_use_id,"output":output})); } + Block::Image { .. } => { + return Err("images belong to user messages".into()); + } _ => { return Err( "tool_use belongs to assistant; tool_result belongs to user".into() @@ -242,7 +281,7 @@ impl Request { } } } - flush(&mut text, &mut input); + flush(&mut run, &mut input); } let tools: Vec<_> = self .tools diff --git a/control-plane/src/models_api.rs b/control-plane/src/models_api.rs index d6c33832..60e357c9 100644 --- a/control-plane/src/models_api.rs +++ b/control-plane/src/models_api.rs @@ -9,10 +9,16 @@ use serde_json::{Value, json}; use crate::app::AppState; -fn record(id: &str) -> Value { +fn record(id: &str, images: bool) -> Value { // No upstream creation/ownership metadata is supplied by the local config. // Zero is an explicit unknown timestamp sentinel; local names the deployment. - json!({"id":id,"object":"model","created":0,"owned_by":"local"}) + let mut value = json!({"id":id,"object":"model","created":0,"owned_by":"local"}); + if images { + // Only announced when the encoder runs: the text-only record keeps its documented shape. + value["architecture"] = + json!({"input_modalities": ["text", "image"], "output_modalities": ["text"]}); + } + value } /// The model and each configured alias (`alias_of` names the model), like the Original; an engine @@ -28,12 +34,13 @@ async fn records(state: &AppState) -> Vec { let Some(model) = state.model.as_deref() else { return Vec::new(); }; - let mut out = vec![mark(record(model))]; + let images = state.vision.is_some(); + let mut out = vec![mark(record(model, images))]; if !state.aliases.is_empty() { out[0]["aliases"] = json!(*state.aliases); } for alias in state.aliases.iter() { - let mut value = mark(record(alias)); + let mut value = mark(record(alias, images)); value["alias_of"] = json!(model); out.push(value); } diff --git a/control-plane/src/prompt.rs b/control-plane/src/prompt.rs index 4c25c224..123da95a 100644 --- a/control-plane/src/prompt.rs +++ b/control-plane/src/prompt.rs @@ -482,11 +482,33 @@ impl Role { } } +/// One item of a message that carries pictures (`serve/frontend.py` `_parts_of`): the template renders a text item +/// as its text and an image item as `<|vision_start|><|image_pad|><|vision_end|>`, in order. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Part { + Text(String), + /// The image's source: a `data:` URL, an http(s) URL or a local path. + Image(String), +} + #[derive(Clone, Copy, Debug)] pub struct Message<'a> { pub role: Role, pub content: &'a str, pub reasoning: Option<&'a str>, + /// When set, the message's content for the template is this list (and `content` is not used). + pub parts: Option<&'a [Part]>, +} + +impl<'a> Message<'a> { + pub fn text(role: Role, content: &'a str, reasoning: Option<&'a str>) -> Self { + Self { + role, + content, + reasoning, + parts: None, + } + } } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -544,6 +566,15 @@ pub fn render_with_tools( effort: Effort, tools: &[Plain], ) -> Result { + render_with_images(messages, effort, tools).map(|(prompt, _)| prompt) +} + +/// [`render_with_tools`] and the sources of the pictures the prompt contains, in prompt order (`images_of`). +pub fn render_with_images( + messages: &[Message<'_>], + effort: Effort, + tools: &[Plain], +) -> Result<(String, Vec), String> { if messages.is_empty() { return Err("prompt needs a message".into()); } @@ -567,9 +598,27 @@ pub fn render_with_tools( let chat: Vec = messages .iter() .map(|message| { + let content = match message.parts { + None => Json::str(message.content), + Some(parts) => Json::Array( + parts + .iter() + .map(|part| match part { + Part::Text(text) => Json::object([ + ("type", Json::str("text")), + ("text", Json::str(text)), + ]), + Part::Image(source) => Json::object([ + ("type", Json::str("image")), + ("source", Json::str(source)), + ]), + }) + .collect(), + ), + }; let mut fields = vec![ ("role".to_owned(), Json::str(message.role.name())), - ("content".to_owned(), Json::str(message.content)), + ("content".to_owned(), content), ]; if let Some(reasoning) = message.reasoning { fields.push(("reasoning_content".to_owned(), Json::str(reasoning))); @@ -577,13 +626,23 @@ pub fn render_with_tools( Json::Object(fields) }) .collect(); + let images = messages + .iter() + .flat_map(|message| message.parts.unwrap_or(&[])) + .filter_map(|part| match part { + Part::Image(source) => Some(source.clone()), + Part::Text(_) => None, + }) + .collect(); let tools = tools.iter().map(chat_tool).collect::, _>>()?; - pinned().render(&ChatInput { - messages: &chat, - tools: (!tools.is_empty()).then_some(&tools), - add_generation_prompt: true, - kwargs: effort.kwargs(), - }) + pinned() + .render(&ChatInput { + messages: &chat, + tools: (!tools.is_empty()).then_some(&tools), + add_generation_prompt: true, + kwargs: effort.kwargs(), + }) + .map(|prompt| (prompt, images)) } #[cfg(test)] @@ -673,6 +732,7 @@ mod tests { Some(Json::String(text)) => Some(text), _ => None, }, + parts: None, }) .collect::>(); let effort = if name == "thinking disabled" { @@ -701,6 +761,7 @@ mod tests { role: Role::User, content, reasoning: None, + parts: None, }; let messages = [ user("Weather in Oslo?"), @@ -708,6 +769,7 @@ mod tests { role: Role::Assistant, content: "\n\n\nOslo\n\n\n", reasoning: None, + parts: None, }, user("\n{\"temp\": 3}\n"), user("And in Bergen?"), @@ -724,11 +786,13 @@ mod tests { role: Role::System, content: "rules", reasoning: None, + parts: None, }; let user = Message { role: Role::User, content: "question", reasoning: None, + parts: None, }; assert!(render(&[user, system], Effort::XHigh).is_err()); assert!(render(&[system], Effort::XHigh).is_err()); @@ -741,6 +805,7 @@ mod tests { role: Role::User, content: "hi", reasoning: None, + parts: None, }]; let text = |effort| render(&user, effort).unwrap(); assert!(text(Effort::XHigh).contains("Reasoning effort is set to xhigh.")); diff --git a/control-plane/src/responses.rs b/control-plane/src/responses.rs index ad11c38f..4b699d78 100644 --- a/control-plane/src/responses.rs +++ b/control-plane/src/responses.rs @@ -25,7 +25,7 @@ use tokio::sync::{RwLock, mpsc, oneshot}; use crate::{ app::AppState, - prompt::{self, Effort, Message, Role}, + prompt::{self, Effort, Message, Part, Role}, response_tools::Catalog, tokenizer::Tokenizer, tool_output::{self, Incremental, Segment}, @@ -847,12 +847,115 @@ fn parse_request( Ok(request) } -// Both endpoints must encode the same expanded transcript and chat template. +/// A request's prompt as the engine reads it: token ids (every image already expanded to its rows) and, with +/// pictures, the embeddings file `GENI` takes. +struct Prepared { + token_ids: Vec, + embeddings: Option, + keep: crate::vision::Keep, +} + +const IMAGE_PAD: &str = "<|image_pad|>"; +const VISION_START: &str = "<|vision_start|>"; + +fn vision_error(error: crate::vision::VisionError) -> Box { + Box::new(match error { + crate::vision::VisionError::Invalid(message) => api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "invalid_image", + Some("input"), + &message, + ), + crate::vision::VisionError::Failed(message) => api_error( + StatusCode::SERVICE_UNAVAILABLE, + "server_error", + "vision_encoder_failed", + None, + &message, + ), + }) +} + +/// `Service.prepare`'s image branch: encode the pictures (in turn with the engine), then turn each +/// `<|image_pad|>` the template wrote for one into one pad per image token. +async fn expand_images( + state: &AppState, + tokenizer: &Tokenizer, + ids: Vec, + images: &[String], +) -> Result> { + let Some(vision) = &state.vision else { + return Err(Box::new(api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "images_unsupported", + Some("input"), + "this server was started without the vision encoder (run setup again and choose 'vision'), so it cannot read images", + ))); + }; + let first = |text: &str, special: bool| { + tokenizer + .encode(text, special) + .map_err(|e| e.to_string()) + .and_then(|ids| { + ids.first() + .copied() + .ok_or_else(|| format!("{text} has no token")) + }) + }; + let internal = |message: String| { + Box::new(api_error( + StatusCode::INTERNAL_SERVER_ERROR, + "server_error", + "tokenization_failed", + None, + &message, + )) + }; + let pad = first(IMAGE_PAD, true).map_err(internal)?; + let start = first(VISION_START, true).map_err(internal)?; + let literal = tokenizer + .encode(IMAGE_PAD, false) + .map_err(|e| internal(e.to_string()))?; + // Encode only while the engine is idle: the engine and the image encoder are separate processes that must + // not run on the GPU at the same time. + let encoded = { + let _turn = vision.gate.lock().await; + let mut encoded = Vec::with_capacity(images.len()); + for source in images { + encoded.push(vision.encode(source).await.map_err(vision_error)?); + } + encoded + }; + let counts: Vec = encoded.iter().map(|image| image.tokens).collect(); + let token_ids = + leleka_serving_policy::vision::expand_image_pads(&ids, pad, start, &literal, &counts) + .map_err(|message| { + Box::new(api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "invalid_prompt", + Some("input"), + &message, + )) + })?; + let (path, keep) = vision.combine(&encoded).await.map_err(vision_error)?; + Ok(Prepared { + token_ids, + embeddings: Some(path.to_string_lossy().into_owned()), + keep, + }) +} + +// Both endpoints must encode the same expanded transcript and chat template. `encode_images: false` (the token +// counters) leaves one pad per picture, as the Python server's count does: nothing is sent to the encoder. async fn prepare_input_tokens( state: &AppState, request: &mut CreateRequest, tokenizer: Arc, -) -> Result, Box> { + encode_images: bool, +) -> Result> { if let Some(previous) = &request.previous_response_id { let history = state.response_history.read().await; let Some(saved) = history.get(previous, &request.model) else { @@ -868,8 +971,8 @@ async fn prepare_input_tokens( append_input(&mut transcript, &request.input); request.input = Value::Array(transcript); } - let prompt = match render_request_prompt(request) { - Ok(prompt) => prompt, + let (prompt, images) = match render_request(request) { + Ok(rendered) => rendered, Err(message) => { return Err(Box::new(api_error( StatusCode::BAD_REQUEST, @@ -908,7 +1011,14 @@ async fn prepare_input_tokens( ))); } }; - Ok(token_ids) + if images.is_empty() || !encode_images { + return Ok(Prepared { + token_ids, + embeddings: None, + keep: Default::default(), + }); + } + expand_images(state, &tokenizer, token_ids, &images).await } pub async fn count_input_tokens( @@ -937,9 +1047,11 @@ pub async fn count_input_tokens( "configure tokenizer_dir to enable input token counting", ); }; - match prepare_input_tokens(&state, &mut request, tokenizer.clone()).await { - Ok(ids) => Json(json!({"object": "response.input_tokens", "input_tokens": ids.len()})) - .into_response(), + match prepare_input_tokens(&state, &mut request, tokenizer.clone(), false).await { + Ok(prepared) => Json( + json!({"object": "response.input_tokens", "input_tokens": prepared.token_ids.len()}), + ) + .into_response(), Err(error) => *error, } } @@ -1002,8 +1114,12 @@ pub async fn create( ); } request.apply_defaults(&state.settings); - let token_ids = match prepare_input_tokens(&state, &mut request, tokenizer.clone()).await { - Ok(ids) => ids, + let Prepared { + token_ids, + embeddings, + keep, + } = match prepare_input_tokens(&state, &mut request, tokenizer.clone(), true).await { + Ok(prepared) => prepared, Err(error) => return *error, }; let remaining = state @@ -1025,7 +1141,8 @@ pub async fn create( sampling: request.sampling(), tune: request.strata_tune.map(Into::into), cvec: request.experimental_speed_projection, - embeddings: None, + embeddings, + keep, reasoning: reasoning_plan(&request, &state, tokenizer), }; if request.stream { @@ -1433,10 +1550,37 @@ fn is_structured(request: &CreateRequest) -> bool { .is_some_and(|text| !matches!(text.format, TextFormat::Text)) } +/// The prompt text, for tests and callers that do not read pictures. +#[cfg(test)] fn render_request_prompt(request: &CreateRequest) -> Result { - let mut owned = Vec::<(Role, String, Option)>::new(); + render_request(request).map(|(prompt, _)| prompt) +} + +/// One message of the request while the prompt is assembled. +struct Owned { + role: Role, + content: String, + reasoning: Option, + /// Set for a user message that carries pictures. + parts: Option>, +} + +impl Owned { + fn new(role: Role, content: String, reasoning: Option) -> Self { + Self { + role, + content, + reasoning, + parts: None, + } + } +} + +/// The rendered prompt and the sources of its pictures, in prompt order. +fn render_request(request: &CreateRequest) -> Result<(String, Vec), String> { + let mut owned = Vec::::new(); if let Some(instructions) = &request.instructions { - owned.push((Role::System, instructions.clone(), None)); + owned.push(Owned::new(Role::System, instructions.clone(), None)); } if let Some(name) = request.forced_tool() { let kind = if request @@ -1448,7 +1592,7 @@ fn render_request_prompt(request: &CreateRequest) -> Result { } else { "function" }; - owned.push(( + owned.push(Owned::new( Role::System, format!( "Call exactly one {kind} in this response: {name}. Do not call any other tool." @@ -1456,14 +1600,14 @@ fn render_request_prompt(request: &CreateRequest) -> Result { None, )); } else if request.tools_required() { - owned.push(( + owned.push(Owned::new( Role::System, "Call at least one tool in this response.".to_owned(), None, )); } if let Some(allowed) = request.allowed_tools() { - owned.push((Role::System, if allowed.is_empty() { + owned.push(Owned::new(Role::System, if allowed.is_empty() { "Do not call any tools in this response.".to_owned() } else { format!("Only these tools may be called in this response: {}. Do not call any other tool.", serde_json::to_string(allowed).expect("selector serialization")) @@ -1473,7 +1617,7 @@ fn render_request_prompt(request: &CreateRequest) -> Result { && !request.tools_disabled() && !request.tools.is_empty() { - owned.push(( + owned.push(Owned::new( Role::System, "Use at most one tool call in this response.".to_owned(), None, @@ -1489,11 +1633,11 @@ fn render_request_prompt(request: &CreateRequest) -> Result { if !request.tools_disabled() && !request.tools.is_empty() { instruction.push_str(" Function calls still use the tool-call format; this JSON requirement applies to your final text answer after any necessary tool results."); } - owned.push((Role::System, instruction, None)); + owned.push(Owned::new(Role::System, instruction, None)); } } if let Some(input) = request.input.as_str() { - owned.push((Role::User, input.to_owned(), None)); + owned.push(Owned::new(Role::User, input.to_owned(), None)); } else { let items = request .input @@ -1549,22 +1693,47 @@ fn render_request_prompt(request: &CreateRequest) -> Result { Some("assistant") => Role::Assistant, _ => return Err("unsupported input message role".into()), }; + let mut pictures: Option> = None; let content = match item.get("content") { Some(Value::String(text)) => text.clone(), Some(Value::Array(parts)) => { let mut text = String::new(); + let mut listed = Vec::new(); for part in parts { - if !matches!( - part.get("type").and_then(Value::as_str), - Some("input_text" | "output_text") - ) { - return Err("only text content parts are supported".into()); + match part.get("type").and_then(Value::as_str) { + Some("input_text" | "output_text") => { + let piece = part + .get("text") + .and_then(Value::as_str) + .ok_or("text part needs text")?; + text.push_str(piece); + listed.push(Part::Text(piece.to_owned())); + } + Some("input_image") => { + listed.push(Part::Image( + leleka_serving_policy::vision::image_source(part), + )); + } + _ => { + return Err( + "only text and image content parts are supported" + .into(), + ); + } + } + } + if listed.iter().any(|part| matches!(part, Part::Image(_))) { + match role { + Role::User => pictures = Some(listed), + Role::System | Role::Developer => { + return Err("System message cannot contain images.".into()); + } + Role::Assistant => { + return Err( + "images are only supported in user messages".into() + ); + } } - text.push_str( - part.get("text") - .and_then(Value::as_str) - .ok_or("text part needs text")?, - ); } text } @@ -1573,10 +1742,15 @@ fn render_request_prompt(request: &CreateRequest) -> Result { if role != Role::Assistant && let Some(thought) = reasoning.take() { - owned.push((Role::Assistant, String::new(), Some(thought))); + owned.push(Owned::new(Role::Assistant, String::new(), Some(thought))); } if role == Role::Assistant - && let Some((Role::Assistant, previous, thought)) = owned.last_mut() + && let Some(Owned { + role: Role::Assistant, + content: previous, + reasoning: thought, + parts: None, + }) = owned.last_mut() { if !previous.is_empty() && !content.is_empty() { previous.push('\n'); @@ -1587,7 +1761,9 @@ fn render_request_prompt(request: &CreateRequest) -> Result { current.push_str(&next); } } else { - owned.push((role, content, reasoning.take())); + let mut message = Owned::new(role, content, reasoning.take()); + message.parts = pictures; + owned.push(message); } } "function_call" | "custom_tool_call" => { @@ -1710,7 +1886,13 @@ fn render_request_prompt(request: &CreateRequest) -> Result { }) .collect::>() .join("\n"); - if let Some((Role::Assistant, content, thought)) = owned.last_mut() { + if let Some(Owned { + role: Role::Assistant, + content, + reasoning: thought, + parts: None, + }) = owned.last_mut() + { content.truncate(content.trim_end().len()); if !content.is_empty() { content.push_str("\n\n"); @@ -1720,9 +1902,9 @@ fn render_request_prompt(request: &CreateRequest) -> Result { thought.get_or_insert_with(String::new).push_str(&next); } } else { - owned.push((Role::Assistant, call_text, reasoning.take())); + owned.push(Owned::new(Role::Assistant, call_text, reasoning.take())); } - owned.push((Role::User, output_text, None)); + owned.push(Owned::new(Role::User, output_text, None)); calls.clear(); outputs.clear(); custom_calls.clear(); @@ -1744,17 +1926,18 @@ fn render_request_prompt(request: &CreateRequest) -> Result { // The pinned Qwen template only accepts leading instruction messages. // Keep all instruction text and its order/authority; never demote a late // developer instruction (including approval criteria) into user content. - owned.sort_by_key(|(role, _, _)| !matches!(role, Role::System | Role::Developer)); + owned.sort_by_key(|o| !matches!(o.role, Role::System | Role::Developer)); let messages = owned .iter() - .map(|(role, content, reasoning)| Message { - role: *role, - content, - reasoning: reasoning.as_deref(), + .map(|o| Message { + role: o.role, + content: &o.content, + reasoning: o.reasoning.as_deref(), + parts: o.parts.as_deref(), }) .collect::>(); let catalog = Catalog::new(&request.tools)?; - prompt::render_with_tools( + prompt::render_with_images( &messages, reasoning_effort(request).map_err(|(_, message)| message.to_owned())?, if request.tools_disabled() { @@ -3424,21 +3607,25 @@ mod tests { role: Role::System, content: "Initial instructions", reasoning: None, + parts: None, }, Message { role: Role::Developer, content: "Apply the approval criteria strictly", reasoning: None, + parts: None, }, Message { role: Role::Developer, content: "Return the structured decision", reasoning: None, + parts: None, }, Message { role: Role::User, content: "Review the proposed read", reasoning: None, + parts: None, }, ], Effort::XHigh, @@ -4151,6 +4338,7 @@ mod tests { role: Role::User, content: "Hello", reasoning: None, + parts: None, }], Effort::None, ) diff --git a/control-plane/src/server_api.rs b/control-plane/src/server_api.rs index 2214e2e3..f03ef890 100644 --- a/control-plane/src/server_api.rs +++ b/control-plane/src/server_api.rs @@ -171,7 +171,7 @@ pub async fn api_health(State(state): State) -> Response { reply( StatusCode::OK, json!({"status": "ok", "max_context": context_of(&worker), "model": state.model, - "images": false, "api_key": state.api_key.is_some(), + "images": state.vision.is_some(), "api_key": state.api_key.is_some(), "loaded": is_loaded(&worker), "service": "strata"}), ) } @@ -247,7 +247,7 @@ pub async fn props(State(state): State, request: Request) -> Response "total_slots": 1, "model_alias": state.model, "chat_template": state.chat_template.as_deref().unwrap_or(DEFAULT_CHAT_TEMPLATE), - "modalities": {"vision": false}, + "modalities": {"vision": state.vision.is_some()}, "models_autoload": state.control.is_some(), "is_sleeping": !is_loaded(&worker), "build_info": format!("Strata Next {}", env!("CARGO_PKG_VERSION")), @@ -314,7 +314,7 @@ async fn status_value(state: &AppState) -> Value { "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}, + "vision": {"enabled": state.vision.is_some(), "available": state.vision.is_some(), "error": null}, "activity": {"requests": worker.metrics.started, "in_flight": usize::from(busy) + queued, "last_request_at": last_at}, "last_timings": timings, diff --git a/control-plane/src/vision.rs b/control-plane/src/vision.rs new file mode 100644 index 00000000..8eee05ef --- /dev/null +++ b/control-plane/src/vision.rs @@ -0,0 +1,779 @@ +//! The image encoder client: the resident `strata-vision` process (llama.cpp mtmd plus the model's mmproj +//! file), its `ENC ` line protocol, the content-hash cache, and the per-request embeddings file +//! (`serve/server.py` `Vision` and the image branch of `Service.prepare`). +//! +//! Everything format-level (SVE1 records, `<|image_pad|>` expansion, base64 wording, native formats) lives in +//! `leleka_serving_policy::vision`; this module owns the process and the files. +//! +//! Differences from the Python server, all deliberate: +//! * images in formats `stb_image` cannot read (WebP, TIFF, AVIF, ...) are refused with a clear message: Python +//! converts them with Pillow, which a Python-free serving path does not have; +//! * a fetched `http(s)` image is capped at [`MAX_IMAGE_BYTES`], and a network failure is a 400 naming it; +//! * the per-request `req-*.sve` file is removed when the request ends (Python leaves it behind); +//! * the encoder's stderr is inherited, not discarded. + +use std::{ + collections::VecDeque, + path::{Path, PathBuf}, + process::Stdio, + sync::{ + Arc, + atomic::{AtomicBool, AtomicU64, Ordering}, + }, + time::Duration, +}; + +use leleka_serving_policy::vision as policy; +use serde::Deserialize; +use sha2::{Digest, Sha256}; +use tokio::{ + io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, + process::{Child, ChildStdin, ChildStdout, Command}, + sync::Mutex, + time::timeout, +}; + +/// Encoded images kept on disk, oldest evicted first (`len(self.cache) > 64`). +pub const CACHE_LIMIT: usize = 64; +/// A fetched image larger than this is refused (Python reads without a limit). +pub const MAX_IMAGE_BYTES: usize = 64 * 1024 * 1024; +const FETCH_TIMEOUT: Duration = Duration::from_secs(60); +const START_TIMEOUT: Duration = Duration::from_secs(600); + +/// The config's `vision` section. +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct VisionConfig { + /// The `strata-vision` executable. + pub exe: PathBuf, + pub mmproj: PathBuf, + /// The text model's first GGUF split (opened vocab-only for the tokenizer). + pub model: PathBuf, + #[serde(default)] + pub gpu: bool, + pub threads: Option, + pub max_tokens: Option, + /// Run the encoder on this card alone (`CUDA_DEVICE_ORDER=PCI_BUS_ID`, `CUDA_VISIBLE_DEVICES`), so a spare GPU can + /// hold it while the engine keeps the VRAM of its own cards. + pub cuda_device: Option, +} + +impl VisionConfig { + /// `Vision.__init__`'s arguments. + pub fn args(&self) -> Vec { + let mut args = vec![ + "--mmproj".to_owned(), + self.mmproj.to_string_lossy().into_owned(), + "--model".to_owned(), + self.model.to_string_lossy().into_owned(), + ]; + if self.gpu { + args.push("--gpu".into()); + } + if let Some(threads) = self.threads.filter(|t| *t > 0) { + args.extend(["--threads".to_owned(), threads.to_string()]); + } + if let Some(max) = self.max_tokens.filter(|t| *t > 0) { + args.extend(["--max-tokens".to_owned(), max.to_string()]); + } + args + } + + /// `vision_env`: the environment overrides of the encoder process. + pub fn env(&self) -> Vec<(&'static str, String)> { + match self.cuda_device { + Some(device) => vec![ + ("CUDA_DEVICE_ORDER", "PCI_BUS_ID".to_owned()), + ("CUDA_VISIBLE_DEVICES", device.to_string()), + ], + None => Vec::new(), + } + } + + pub fn validate(&self) -> Result<(), String> { + for (name, path) in [ + ("exe", &self.exe), + ("mmproj", &self.mmproj), + ("model", &self.model), + ] { + if path.as_os_str().is_empty() { + return Err(format!("vision.{name} must not be empty")); + } + } + Ok(()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum VisionError { + /// The caller's image is the problem: HTTP 400 (`ValueError` in Python). + Invalid(String), + /// The encoder itself failed (the pipe is gone, the process would not start). + Failed(String), +} + +impl std::fmt::Display for VisionError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Invalid(message) | Self::Failed(message) => f.write_str(message), + } + } +} + +impl std::error::Error for VisionError {} + +/// One encoded image: its SVE1 file and the number of image tokens it stands for. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Encoded { + pub path: PathBuf, + pub tokens: usize, +} + +/// Keeps a request's temporary files alive until the last clone of the request is dropped. +#[derive(Clone, Debug, Default)] +pub struct Keep(Option>); + +impl Keep { + pub fn none() -> Self { + Self(None) + } +} + +impl PartialEq for Keep { + fn eq(&self, other: &Self) -> bool { + match (&self.0, &other.0) { + (None, None) => true, + (Some(a), Some(b)) => Arc::ptr_eq(a, b), + _ => false, + } + } +} + +#[derive(Debug)] +struct TempFile(PathBuf); + +impl Drop for TempFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + +struct Proc { + child: Child, + stdin: ChildStdin, + lines: tokio::io::Lines>, +} + +#[derive(Default)] +struct Inner { + proc: Option, + /// Content hash (first 32 hex of SHA-256 of the normalized bytes) -> encoded file; insertion order. + cache: VecDeque<(String, Encoded)>, +} + +pub struct Vision { + config: VisionConfig, + dir: PathBuf, + inner: Mutex, + stopped: AtomicBool, + serial: AtomicU64, + /// Taken for the length of an encode and for every engine generation: the engine and the encoder (two processes) + /// must not use the GPU at the same time. Python does the same with its request FIFO. + pub gate: Arc>, +} + +static NEXT_DIR: AtomicU64 = AtomicU64::new(0); + +impl Vision { + /// Start the encoder and wait for its `READY` line (`Vision.__init__`). + pub async fn start(config: VisionConfig) -> Result, VisionError> { + let vision = Self::unstarted(config)?; + { + let mut inner = vision.inner.lock().await; + vision.spawn(&mut inner).await?; + } + Ok(Arc::new(vision)) + } + + /// A client whose process is started by the first [`Vision::restart`] or [`Vision::ensure_running`]. + pub fn unstarted(config: VisionConfig) -> Result { + let dir = std::env::temp_dir().join(format!( + "strata-vision-{}-{}", + std::process::id(), + NEXT_DIR.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir_all(&dir) + .map_err(|e| VisionError::Failed(format!("cannot create {}: {e}", dir.display())))?; + Ok(Self { + config, + dir, + inner: Mutex::new(Inner::default()), + stopped: AtomicBool::new(true), + serial: AtomicU64::new(0), + gate: Arc::new(Mutex::new(())), + }) + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + async fn spawn(&self, inner: &mut Inner) -> Result<(), VisionError> { + let mut command = Command::new(&self.config.exe); + command + .args(self.config.args()) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .kill_on_drop(true); + for (name, value) in self.config.env() { + command.env(name, value); + } + let mut child = command.spawn().map_err(|e| { + VisionError::Failed(format!( + "the vision encoder did not start: {}: {e}", + self.config.exe.display() + )) + })?; + let stdin = child.stdin.take().expect("piped encoder stdin"); + let stdout = child.stdout.take().expect("piped encoder stdout"); + let mut lines = BufReader::new(stdout).lines(); + let first = match timeout(START_TIMEOUT, lines.next_line()).await { + Ok(Ok(Some(line))) => line, + Ok(Ok(None)) => String::new(), + Ok(Err(e)) => { + return Err(VisionError::Failed(format!( + "the vision encoder did not start: {e}" + ))); + } + Err(_) => { + let _ = child.kill().await; + return Err(VisionError::Failed( + "the vision encoder did not start: no READY line in time".into(), + )); + } + }; + if !first.starts_with("READY") { + let _ = child.kill().await; + return Err(VisionError::Failed(format!( + "the vision encoder did not start: {}", + first.trim() + ))); + } + inner.proc = Some(Proc { + child, + stdin, + lines, + }); + self.stopped.store(false, Ordering::Release); + Ok(()) + } + + /// `Vision.alive`: started, not unloaded, and the process still runs. + pub async fn alive(&self) -> bool { + if self.stopped.load(Ordering::Acquire) { + return false; + } + let mut inner = self.inner.lock().await; + inner + .proc + .as_mut() + .is_some_and(|proc| matches!(proc.child.try_wait(), Ok(None))) + } + + async fn close_inner(inner: &mut Inner) { + let Some(mut proc) = inner.proc.take() else { + return; + }; + let quit = async { + proc.stdin.write_all(b"QUIT\n").await.ok()?; + proc.stdin.flush().await.ok()?; + drop(proc.stdin); + timeout(Duration::from_secs(10), proc.child.wait()) + .await + .ok()? + .ok() + }; + if quit.await.is_none() { + let _ = proc.child.kill().await; + } + } + + /// `Vision.close`: ask the encoder to quit, kill it if it does not. + pub async fn close(&self) { + let mut inner = self.inner.lock().await; + Self::close_inner(&mut inner).await; + self.stopped.store(true, Ordering::Release); + } + + /// `Vision.unload`: stop the process (its VRAM or RAM goes back); the encoded images stay cached on disk. + pub async fn unload(&self) { + self.close().await; + } + + /// `Vision.restart`: start the process again after an unload or a death; the cache is kept. + pub async fn restart(&self) -> Result<(), VisionError> { + let mut inner = self.inner.lock().await; + if let Some(mut proc) = inner.proc.take() { + let _ = proc.child.kill().await; + } + self.spawn(&mut inner).await + } + + /// `Service.ensure_loaded`'s vision step: start the encoder again unless it runs. Done before the engine starts + /// (a GPU encoder takes its VRAM first, the engine sizes its cache from what is left). + pub async fn ensure_running(&self) -> Result<(), VisionError> { + if self.alive().await { + return Ok(()); + } + eprintln!("starting the vision encoder again ..."); + self.restart().await + } + + /// `Vision.load`: the bytes behind an image source (a `data:` URL, an http(s) URL or a local path). + pub async fn load(source: &str) -> Result, VisionError> { + if let Some(rest) = source.strip_prefix("data:") { + let (_, payload) = rest.split_once(',').ok_or_else(|| { + VisionError::Invalid("an image data: URL needs a comma before its data".into()) + })?; + return policy::b64decode(payload).map_err(VisionError::Invalid); + } + if source.starts_with("http://") || source.starts_with("https://") { + return fetch(source).await; + } + let path = source.strip_prefix("file://").unwrap_or(source); + if !path.is_empty() && tokio::fs::metadata(path).await.is_ok_and(|m| m.is_file()) { + return tokio::fs::read(path) + .await + .map_err(|e| VisionError::Invalid(format!("the image could not be read ({e})"))); + } + Err(VisionError::Invalid( + "an image must be a data: URL, an http(s) URL or a local file path".into(), + )) + } + + /// `Vision.normalize` without an image library: the formats `strata-vision`'s decoder reads pass through. + pub fn normalize(data: Vec) -> Result, VisionError> { + if policy::is_native_image_format(&data) { + Ok(data) + } else { + Err(VisionError::Invalid( + "this image format is not supported (JPEG, PNG, BMP and GIF are; convert WebP, TIFF, AVIF, ... first)" + .into(), + )) + } + } + + /// `Vision.encode`: the embeddings file of an image and its number of image tokens; the same picture + /// (by content) is encoded once. + pub async fn encode(&self, source: &str) -> Result { + let data = Self::normalize(Self::load(source).await?)?; + let key = hex::encode(Sha256::digest(&data))[..32].to_owned(); + let mut inner = self.inner.lock().await; + if let Some((_, hit)) = inner.cache.iter().find(|(k, _)| *k == key) { + return Ok(hit.clone()); + } + let image = self.dir.join(format!("{key}.img")); + let out = self.dir.join(format!("{key}.sve")); + tokio::fs::write(&image, &data) + .await + .map_err(|e| VisionError::Failed(format!("cannot write {}: {e}", image.display())))?; + let reply = Self::exchange(&mut inner, &image, &out).await; + let _ = tokio::fs::remove_file(&image).await; // #352: also when the encoder's pipe is gone + let line = reply?; + if !line.starts_with("OK") { + return Err(VisionError::Invalid(format!( + "the image could not be read: {}", + match line.strip_prefix("ERR") { + Some(_) => line.get(4..).unwrap_or(""), + None => "the vision encoder stopped", + } + ))); + } + let tokens = line + .split_whitespace() + .nth(1) + .and_then(|n| n.parse::().ok()) + .ok_or_else(|| { + VisionError::Failed(format!("unexpected vision encoder reply: {line}")) + })?; + let encoded = Encoded { path: out, tokens }; + inner.cache.push_back((key, encoded.clone())); + if inner.cache.len() > CACHE_LIMIT + && let Some((_, old)) = inner.cache.pop_front() + { + let _ = tokio::fs::remove_file(&old.path).await; // oldest first + } + Ok(encoded) + } + + /// One `ENC` line and its reply (`""` when the encoder's output ended). + async fn exchange(inner: &mut Inner, image: &Path, out: &Path) -> Result { + let proc = inner + .proc + .as_mut() + .ok_or_else(|| VisionError::Failed("the vision encoder is not running".into()))?; + let line = format!("ENC {} {}\n", image.display(), out.display()); + proc.stdin + .write_all(line.as_bytes()) + .await + .map_err(|e| VisionError::Failed(format!("the vision encoder is gone: {e}")))?; + proc.stdin + .flush() + .await + .map_err(|e| VisionError::Failed(format!("the vision encoder is gone: {e}")))?; + match proc.lines.next_line().await { + Ok(Some(reply)) => Ok(reply.trim().to_owned()), + Ok(None) => Ok(String::new()), + Err(e) => Err(VisionError::Failed(format!( + "the vision encoder is gone: {e}" + ))), + } + } + + /// The concatenation of the images' SVE1 files in prompt order: `GENI`'s embeddings file for one request. + pub async fn combine(&self, images: &[Encoded]) -> Result<(PathBuf, Keep), VisionError> { + let name = format!( + "req-{:x}-{:x}.sve", + std::process::id(), + self.serial.fetch_add(1, Ordering::Relaxed) + ); + let path = self.dir.join(name); + let mut bytes = Vec::new(); + for image in images { + bytes.extend(tokio::fs::read(&image.path).await.map_err(|e| { + VisionError::Failed(format!("cannot read {}: {e}", image.path.display())) + })?); + } + tokio::fs::write(&path, bytes) + .await + .map_err(|e| VisionError::Failed(format!("cannot write {}: {e}", path.display())))?; + Ok((path.clone(), Keep(Some(Arc::new(TempFile(path)))))) + } +} + +impl Drop for Vision { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +async fn fetch(url: &str) -> Result, VisionError> { + let fail = |e: &dyn std::fmt::Display| { + VisionError::Invalid(format!("the image could not be fetched ({e})")) + }; + let roots = webpki_root_certs::TLS_SERVER_ROOT_CERTS + .iter() + .map(|der| reqwest::Certificate::from_der(der.as_ref())) + .collect::, _>>() + .map_err(|e| fail(&e))?; + let client = reqwest::Client::builder() + .tls_certs_only(roots) + .timeout(FETCH_TIMEOUT) + .user_agent("strata") + .build() + .map_err(|e| fail(&e))?; + let mut response = client + .get(url) + .send() + .await + .map_err(|e| fail(&e))? + .error_for_status() + .map_err(|e| fail(&e))?; + let mut data = Vec::new(); + while let Some(chunk) = response.chunk().await.map_err(|e| fail(&e))? { + data.extend_from_slice(&chunk); + if data.len() > MAX_IMAGE_BYTES { + return Err(VisionError::Invalid(format!( + "the image is larger than {} MiB", + MAX_IMAGE_BYTES >> 20 + ))); + } + } + Ok(data) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::os::unix::fs::PermissionsExt; + + fn fake(dir: &Path, mode: &str) -> VisionConfig { + let exe = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/fake_vision.sh"); + let wrapper = dir.join(format!("vision-{mode}.sh")); + std::fs::write( + &wrapper, + format!( + "#!/bin/sh\nexec '{}' {mode} '{}' \"$@\"\n", + exe.display(), + dir.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap(); + VisionConfig { + exe: wrapper, + mmproj: "/m/mmproj.gguf".into(), + model: "/m/model.gguf".into(), + gpu: false, + threads: None, + max_tokens: None, + cuda_device: None, + } + } + + fn scratch(name: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("strata-vision-test-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + fn png(tag: u8) -> Vec { + let mut data = b"\x89PNG\r\n\x1a\n".to_vec(); + data.push(tag); + data + } + + fn data_url(bytes: &[u8]) -> String { + const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::from("data:image/png;base64,"); + for chunk in bytes.chunks(3) { + let n = chunk + .iter() + .enumerate() + .fold(0u32, |n, (i, b)| n | u32::from(*b) << (16 - 8 * i)); + for i in 0..4 { + if i <= chunk.len() { + out.push(ALPHABET[(n >> (18 - 6 * i) & 63) as usize] as char); + } else { + out.push('='); + } + } + } + out + } + + #[test] + fn arguments_and_environment_follow_the_python_server() { + let mut config = VisionConfig { + exe: "/bin/strata-vision".into(), + mmproj: "/m/p.gguf".into(), + model: "/m/t.gguf".into(), + gpu: true, + threads: Some(6), + max_tokens: Some(1024), + cuda_device: Some(2), + }; + assert_eq!( + config.args(), + [ + "--mmproj", + "/m/p.gguf", + "--model", + "/m/t.gguf", + "--gpu", + "--threads", + "6", + "--max-tokens", + "1024" + ] + ); + assert_eq!( + config.env(), + vec![ + ("CUDA_DEVICE_ORDER", "PCI_BUS_ID".to_owned()), + ("CUDA_VISIBLE_DEVICES", "2".to_owned()) + ] + ); + config.gpu = false; + config.threads = Some(0); + config.max_tokens = None; + config.cuda_device = None; + assert_eq!( + config.args(), + ["--mmproj", "/m/p.gguf", "--model", "/m/t.gguf"] + ); + assert!(config.env().is_empty()); + assert!( + serde_json::from_str::(r#"{"exe":"a","mmproj":"b","model":"c","x":1}"#) + .is_err() + ); + } + + #[tokio::test] + async fn sources_load_like_the_python_server() { + let dir = scratch("load"); + let file = dir.join("a.png"); + std::fs::write(&file, png(1)).unwrap(); + assert_eq!(Vision::load(file.to_str().unwrap()).await.unwrap(), png(1)); + assert_eq!( + Vision::load(&format!("file://{}", file.display())) + .await + .unwrap(), + png(1) + ); + assert_eq!(Vision::load(&data_url(&png(2))).await.unwrap(), png(2)); + let nothing = "an image must be a data: URL, an http(s) URL or a local file path"; + for source in ["", "nope.png", dir.to_str().unwrap()] { + assert_eq!( + Vision::load(source).await.unwrap_err(), + VisionError::Invalid(nothing.into()) + ); + } + assert_eq!( + Vision::load("data:image/png;base64,QQ").await.unwrap_err(), + VisionError::Invalid("Incorrect padding".into()) + ); + assert!(matches!( + Vision::load("data:image/png").await, + Err(VisionError::Invalid(_)) + )); + assert!(Vision::normalize(b"RIFF....WEBP".to_vec()).is_err()); + assert_eq!(Vision::normalize(png(3)).unwrap(), png(3)); + } + + #[tokio::test] + async fn http_images_are_fetched_with_the_strata_agent() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/pic.png", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + let mut agents = Vec::new(); + for status in ["200 OK", "404 Not Found"] { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut buffer = vec![0u8; 4096]; + let n = socket.read(&mut buffer).await.unwrap(); + agents.push( + String::from_utf8_lossy(&buffer[..n]) + .lines() + .find(|l| l.to_ascii_lowercase().starts_with("user-agent")) + .unwrap_or("") + .to_owned(), + ); + let body = png(9); + let head = format!( + "HTTP/1.1 {status}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n", + body.len() + ); + socket.write_all(head.as_bytes()).await.unwrap(); + socket.write_all(&body).await.unwrap(); + } + agents + }); + assert_eq!(Vision::load(&url).await.unwrap(), png(9)); + assert!( + matches!(Vision::load(&url).await, Err(VisionError::Invalid(m)) if m.contains("404")) + ); + assert!(server.await.unwrap().iter().all(|a| a.ends_with("strata"))); + } + + #[tokio::test] + async fn encoding_caches_by_content_and_combines_in_prompt_order() { + let dir = scratch("encode"); + let vision = Vision::start(fake(&dir, "ok")).await.unwrap(); + assert!(vision.alive().await); + let a = vision.encode(&data_url(&png(1))).await.unwrap(); + let b = vision.encode(&data_url(&png(2))).await.unwrap(); + let again = vision.encode(&data_url(&png(1))).await.unwrap(); + assert_eq!((a.tokens, b.tokens), (6, 6)); + assert_eq!(a, again, "the same picture is encoded once"); + assert_ne!(a.path, b.path); + let log = std::fs::read_to_string(dir.join("enc.log")).unwrap(); + assert_eq!(log.lines().count(), 2); + // The fake writes one SVE1 record whose first float carries the image's first byte count. + let (combined, keep) = vision + .combine(&[a.clone(), b.clone(), a.clone()]) + .await + .unwrap(); + let one = std::fs::read(&a.path).unwrap(); + let two = std::fs::read(&b.path).unwrap(); + let mut want = one.clone(); + want.extend(&two); + want.extend(&one); + assert_eq!(std::fs::read(&combined).unwrap(), want); + let parsed = policy::parse_embeddings(&want, 4).unwrap(); + assert_eq!(parsed.images.len(), 3); + assert_eq!((parsed.images[0].nx, parsed.images[0].ny), (3, 2)); + drop(keep); + assert!( + !combined.exists(), + "the per-request file goes with the request" + ); + // The temporary image is gone once its reply arrived. + assert!(std::fs::read_dir(vision.dir()).unwrap().all(|e| { + let name = e.unwrap().file_name().into_string().unwrap(); + !name.ends_with(".img") + })); + vision.close().await; + assert!(!vision.alive().await); + } + + #[tokio::test] + async fn encoder_errors_and_death_are_reported_like_the_python_server() { + let dir = scratch("err"); + let vision = Vision::start(fake(&dir, "err")).await.unwrap(); + assert_eq!( + vision.encode(&data_url(&png(1))).await.unwrap_err(), + VisionError::Invalid("the image could not be read: cannot read the image".into()) + ); + vision.close().await; + let dir = scratch("die"); + let vision = Vision::start(fake(&dir, "die")).await.unwrap(); + assert_eq!( + vision.encode(&data_url(&png(1))).await.unwrap_err(), + VisionError::Invalid("the image could not be read: the vision encoder stopped".into()) + ); + assert!(!vision.alive().await, "the process ended"); + assert!(std::fs::read_dir(vision.dir()).unwrap().all(|e| { + !e.unwrap() + .file_name() + .into_string() + .unwrap() + .ends_with(".img") + })); + let dir = scratch("bad"); + match Vision::start(fake(&dir, "badready")).await { + Err(VisionError::Failed(m)) => assert_eq!(m, "the vision encoder did not start: NOPE"), + other => panic!("{:?}", other.map(|_| ())), + } + } + + #[tokio::test] + async fn unload_keeps_the_cache_and_restart_starts_the_encoder_again() { + let dir = scratch("unload"); + let vision = Vision::start(fake(&dir, "ok")).await.unwrap(); + let first = vision.encode(&data_url(&png(5))).await.unwrap(); + vision.unload().await; + assert!(!vision.alive().await); + // cached images need no process + assert_eq!(vision.encode(&data_url(&png(5))).await.unwrap(), first); + vision.ensure_running().await.unwrap(); + assert!(vision.alive().await); + vision.ensure_running().await.unwrap(); + vision.encode(&data_url(&png(6))).await.unwrap(); + assert_eq!( + std::fs::read_to_string(dir.join("starts.log")) + .unwrap() + .lines() + .count(), + 2 + ); + vision.close().await; + } + + #[tokio::test] + async fn the_cache_evicts_the_oldest_image_and_its_file() { + let dir = scratch("evict"); + let vision = Vision::start(fake(&dir, "ok")).await.unwrap(); + let mut first = None; + for tag in 0..=CACHE_LIMIT as u8 { + let encoded = vision.encode(&data_url(&png(tag))).await.unwrap(); + first.get_or_insert(encoded); + } + assert!(!first.unwrap().path.exists()); + assert_eq!(vision.inner.lock().await.cache.len(), CACHE_LIMIT); + vision.close().await; + } +} diff --git a/control-plane/src/wire.rs b/control-plane/src/wire.rs index 3dd1afe5..cc4031ad 100644 --- a/control-plane/src/wire.rs +++ b/control-plane/src/wire.rs @@ -57,6 +57,8 @@ pub struct Generate { pub cvec: Option, /// `GENI`: path of the SVE1 image-embeddings file for this request. pub embeddings: Option, + /// Keeps the request's temporary embeddings file until the request (and its wrap-up passes) is gone. + pub keep: crate::vision::Keep, /// Reasoning-budget wrap-up, executed by the worker; never sent to the engine. pub reasoning: Option, } @@ -318,6 +320,7 @@ mod tests { .get("experimental_speed_projection") .and_then(serde_json::Value::as_bool), embeddings: case["embeddings"].as_str().map(str::to_owned), + keep: Default::default(), reasoning: None, }; assert_eq!( diff --git a/control-plane/src/worker.rs b/control-plane/src/worker.rs index 981d821d..6088cd6f 100644 --- a/control-plane/src/worker.rs +++ b/control-plane/src/worker.rs @@ -117,6 +117,9 @@ pub struct WorkerConfig { pub before_load: Option, /// Reload only when this much VRAM is free (MiB); 0 = always. pub min_free_vram_mib: u64, + /// The image encoder: stopped with the engine, started again before it, and never on the GPU at the same + /// time as a generation. + pub vision: Option>, } impl Default for WorkerConfig { @@ -132,6 +135,7 @@ impl Default for WorkerConfig { stall_timeout: None, before_load: None, min_free_vram_mib: 0, + vision: None, } } } @@ -329,6 +333,20 @@ pub async fn run_supervised( unloaded = true; continue; } + // The image encoder first, as at a start: a GPU encoder takes its VRAM before the engine sizes its cache. + if let Some(vision) = &config.vision + && let Err(error) = vision.ensure_running().await + { + let message = error.to_string(); + eprintln!("{message}"); + let error = LoadError::Failed(message.clone()); + fail_loads(&mut waiting, &error).await; + if let Some(command) = inbox.take() { + send_failure(command.result, message).await; + } + unloaded = true; + continue; + } started_before = true; match run_session( &config, @@ -559,6 +577,9 @@ async fn run_session( if outcome == leleka_serving_policy::idle::Outcome::Unloaded { update(status, WorkerState::Unloaded, None).await; stop(&mut child, &mut stdin).await; + if let Some(vision) = &config.vision { + vision.unload().await; + } let _ = reply.send(outcome); return SessionExit::Unloaded; } @@ -582,6 +603,11 @@ async fn run_session( // Retain the command activity until protocol cleanup, // including STOP/QUIT and failed-process termination. let _activity = command.activity.take(); + // The encoder and the engine never use the GPU at the same time. + let _turn = match &config.vision { + Some(vision) => Some(vision.gate.clone().lock_owned().await), + None => None, + }; tokio::select! { (timed_out, result) = async { let generation = generate(&mut stdin, &mut lines, &mut command, max_context, status, config.stall_timeout); diff --git a/control-plane/tests/fixtures/fake_vision.sh b/control-plane/tests/fixtures/fake_vision.sh new file mode 100755 index 00000000..e5012ded --- /dev/null +++ b/control-plane/tests/fixtures/fake_vision.sh @@ -0,0 +1,33 @@ +#!/bin/sh +# A stand-in for strata-vision (tools/vision/strata_vision.cpp): the same line protocol, no model. +# usage: fake_vision.sh MODE LOGDIR [strata-vision arguments...] +mode="$1"; dir="$2"; shift 2 +printf '%s\n' "$*" >> "$dir/starts.log" +case "$mode" in + badready) printf 'NOPE\n'; exit 1 ;; +esac +printf 'READY 4\n' +while IFS= read -r line; do + case "$line" in + QUIT) exit 0 ;; + 'ENC '*) + rest="${line#ENC }" + out="${rest##* }" + img="${rest% *}" + tag=$(tail -c 1 "$img" | od -An -tu1 | tr -d ' ') + printf '%s tag=%s\n' "$line" "$tag" >> "$dir/enc.log" + case "$mode" in + die) exit 0 ;; + err) printf 'ERR cannot read the image\n'; continue ;; + esac + { + printf 'SVE1\006\000\000\000\003\000\000\000\002\000\000\000\004\000\000\000' + printf "\\$(printf %03o "$tag")\\000\\000\\000" + i=1 + while [ "$i" -lt 24 ]; do printf '\000\000\000\000'; i=$((i+1)); done + } > "$out" + printf 'OK 6 3 2 1\n' + ;; + *) printf 'ERR expected: ENC \n' ;; + esac +done diff --git a/control-plane/tests/fixtures/golden/vision_dialects.json b/control-plane/tests/fixtures/golden/vision_dialects.json new file mode 100644 index 00000000..2296f67f --- /dev/null +++ b/control-plane/tests/fixtures/golden/vision_dialects.json @@ -0,0 +1,460 @@ +{ + "source": "serve/frontend.py openai_to_messages / anthropic_to_messages + chat_template.jinja", + "cases": [ + { + "dialect": "chat", + "request": { + "messages": [ + { + "role": "user", + "content": [ + { + "type": "text", + "text": "what is this?" + }, + { + "type": "image_url", + "image_url": { + "url": "data:image/png;base64,iVBORw0KGgoB", + "detail": "high" + } + } + ] + } + ], + "reasoning_effort": "none" + }, + "prompt": "<|im_start|>user\nwhat is this?<|vision_start|><|image_pad|><|vision_end|><|im_end|>\n<|im_start|>assistant\n\n\n\n\n", + "images": [ + "data:image/png;base64,iVBORw0KGgoB" + ] + }, + { + "dialect": "chat", + "request": { + "messages": [ + { + "role": "user", + "content": [ + { + "type": "image_url", + "image_url": { + "url": "data:image/png;base64,iVBORw0KGgoC" + } + } + ] + } + ], + "reasoning_effort": "none" + }, + "prompt": "<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|><|im_end|>\n<|im_start|>assistant\n\n\n\n\n", + "images": [ + "data:image/png;base64,iVBORw0KGgoC" + ] + }, + { + "dialect": "chat", + "request": { + "messages": [ + { + "role": "user", + "content": [ + { + "type": "image_url", + "image_url": "data:image/png;base64,iVBORw0KGgoD" + }, + { + "type": "text", + "text": "after" + } + ] + } + ], + "reasoning_effort": "none" + }, + "prompt": "<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>after<|im_end|>\n<|im_start|>assistant\n\n\n\n\n", + "images": [ + "data:image/png;base64,iVBORw0KGgoD" + ] + }, + { + "dialect": "chat", + "request": { + "messages": [ + { + "role": "user", + "content": [ + { + "type": "text", + "text": "a" + }, + { + "type": "image_url", + "image_url": { + "url": "data:image/png;base64,iVBORw0KGgoE" + } + }, + { + "type": "text", + "text": "b" + }, + { + "type": "image_url", + "image_url": "data:image/png;base64,iVBORw0KGgoF" + }, + { + "type": "text", + "text": "c" + } + ] + } + ], + "reasoning_effort": "none" + }, + "prompt": "<|im_start|>user\na<|vision_start|><|image_pad|><|vision_end|>b<|vision_start|><|image_pad|><|vision_end|>c<|im_end|>\n<|im_start|>assistant\n\n\n\n\n", + "images": [ + "data:image/png;base64,iVBORw0KGgoE", + "data:image/png;base64,iVBORw0KGgoF" + ] + }, + { + "dialect": "chat", + "request": { + "messages": [ + { + "role": "system", + "content": "be brief" + }, + { + "role": "user", + "content": [ + { + "type": "image_url", + "image_url": { + "url": "data:image/png;base64,iVBORw0KGgoG" + } + }, + { + "type": "text", + "text": "x" + } + ] + } + ], + "reasoning_effort": "none" + }, + "prompt": "<|im_start|>system\nbe brief<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>x<|im_end|>\n<|im_start|>assistant\n\n\n\n\n", + "images": [ + "data:image/png;base64,iVBORw0KGgoG" + ] + }, + { + "dialect": "chat", + "request": { + "messages": [ + { + "role": "user", + "content": "first" + }, + { + "role": "assistant", + "content": "ok" + }, + { + "role": "user", + "content": [ + { + "type": "text", + "text": "again" + }, + { + "type": "image_url", + "image_url": { + "url": "data:image/png;base64,iVBORw0KGgoH" + } + } + ] + } + ], + "reasoning_effort": "none" + }, + "prompt": "<|im_start|>user\nfirst<|im_end|>\n<|im_start|>assistant\n\n\n\n\nok<|im_end|>\n<|im_start|>user\nagain<|vision_start|><|image_pad|><|vision_end|><|im_end|>\n<|im_start|>assistant\n\n\n\n\n", + "images": [ + "data:image/png;base64,iVBORw0KGgoH" + ] + }, + { + "dialect": "chat", + "request": { + "messages": [ + { + "role": "user", + "content": [ + { + "type": "image_url", + "image_url": { + "url": "data:image/png;base64,iVBORw0KGgoI" + } + } + ] + }, + { + "role": "assistant", + "content": "a cat" + }, + { + "role": "user", + "content": [ + { + "type": "image_url", + "image_url": { + "url": "data:image/png;base64,iVBORw0KGgoJ" + } + }, + { + "type": "text", + "text": "and?" + } + ] + } + ], + "reasoning_effort": "none" + }, + "prompt": "<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|><|im_end|>\n<|im_start|>assistant\n\n\n\n\na cat<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>and?<|im_end|>\n<|im_start|>assistant\n\n\n\n\n", + "images": [ + "data:image/png;base64,iVBORw0KGgoI", + "data:image/png;base64,iVBORw0KGgoJ" + ] + }, + { + "dialect": "chat", + "request": { + "messages": [ + { + "role": "user", + "content": [ + { + "type": "text", + "text": "the docs say <|image_pad|> marks an image" + }, + { + "type": "image_url", + "image_url": { + "url": "data:image/png;base64,iVBORw0KGgoK" + } + } + ] + } + ], + "reasoning_effort": "none" + }, + "prompt": "<|im_start|>user\nthe docs say <|image_pad|> marks an image<|vision_start|><|image_pad|><|vision_end|><|im_end|>\n<|im_start|>assistant\n\n\n\n\n", + "images": [ + "data:image/png;base64,iVBORw0KGgoK" + ] + }, + { + "dialect": "messages", + "request": { + "messages": [ + { + "role": "user", + "content": [ + { + "type": "image", + "source": { + "type": "base64", + "media_type": "image/png", + "data": "iVBORw0KGgoL" + } + }, + { + "type": "text", + "text": "describe" + } + ] + } + ], + "thinking": { + "type": "disabled" + } + }, + "prompt": "<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>describe<|im_end|>\n<|im_start|>assistant\n\n\n\n\n", + "images": [ + "data:image/png;base64,iVBORw0KGgoL" + ] + }, + { + "dialect": "messages", + "request": { + "messages": [ + { + "role": "user", + "content": [ + { + "type": "text", + "text": "describe" + }, + { + "type": "image", + "source": { + "type": "base64", + "media_type": "image/jpeg", + "data": "iVBORw0KGgoM" + } + } + ] + } + ], + "thinking": { + "type": "disabled" + }, + "system": "be brief" + }, + "prompt": "<|im_start|>system\nbe brief<|im_end|>\n<|im_start|>user\ndescribe<|vision_start|><|image_pad|><|vision_end|><|im_end|>\n<|im_start|>assistant\n\n\n\n\n", + "images": [ + "data:image/jpeg;base64,iVBORw0KGgoM" + ] + }, + { + "dialect": "messages", + "request": { + "messages": [ + { + "role": "user", + "content": [ + { + "type": "image", + "source": { + "type": "base64", + "media_type": "image/png", + "data": "iVBORw0KGgoN" + } + }, + { + "type": "image", + "source": { + "type": "base64", + "media_type": "image/png", + "data": "iVBORw0KGgoO" + } + }, + { + "type": "text", + "text": "compare" + } + ] + } + ], + "thinking": { + "type": "disabled" + } + }, + "prompt": "<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|><|vision_start|><|image_pad|><|vision_end|>compare<|im_end|>\n<|im_start|>assistant\n\n\n\n\n", + "images": [ + "data:image/png;base64,iVBORw0KGgoN", + "data:image/png;base64,iVBORw0KGgoO" + ] + }, + { + "dialect": "messages", + "request": { + "messages": [ + { + "role": "user", + "content": [ + { + "type": "text", + "text": "look" + }, + { + "type": "image", + "source": { + "type": "url", + "url": "data:image/png;base64,iVBORw0KGgoP" + } + } + ] + } + ], + "thinking": { + "type": "disabled" + } + }, + "prompt": "<|im_start|>user\nlook<|vision_start|><|image_pad|><|vision_end|><|im_end|>\n<|im_start|>assistant\n\n\n\n\n", + "images": [ + "data:image/png;base64,iVBORw0KGgoP" + ] + }, + { + "dialect": "messages", + "request": { + "messages": [ + { + "role": "user", + "content": [ + { + "type": "image", + "source": { + "type": "url", + "url": "data:image/png;base64,iVBORw0KGgoQ" + } + } + ] + } + ], + "thinking": { + "type": "disabled" + } + }, + "prompt": "<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|><|im_end|>\n<|im_start|>assistant\n\n\n\n\n", + "images": [ + "data:image/png;base64,iVBORw0KGgoQ" + ] + }, + { + "dialect": "messages", + "request": { + "messages": [ + { + "role": "user", + "content": "first" + }, + { + "role": "assistant", + "content": [ + { + "type": "text", + "text": "ok" + } + ] + }, + { + "role": "user", + "content": [ + { + "type": "image", + "source": { + "type": "base64", + "media_type": "image/png", + "data": "iVBORw0KGgoR" + } + }, + { + "type": "text", + "text": "now this" + } + ] + } + ], + "thinking": { + "type": "disabled" + } + }, + "prompt": "<|im_start|>user\nfirst<|im_end|>\n<|im_start|>assistant\n\n\n\n\nok<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>now this<|im_end|>\n<|im_start|>assistant\n\n\n\n\n", + "images": [ + "data:image/png;base64,iVBORw0KGgoR" + ] + } + ] +} diff --git a/control-plane/tests/fixtures/mock_engine.sh b/control-plane/tests/fixtures/mock_engine.sh index c843f049..38f282a6 100755 --- a/control-plane/tests/fixtures/mock_engine.sh +++ b/control-plane/tests/fixtures/mock_engine.sh @@ -148,6 +148,29 @@ case "$2" in esac done ;; + images) + # GEN and GENI: log the line, answer "Hi". $3 is a scratch directory. + dir="$3" + printf 'boot\n' >> "$dir/boots" + printf 'READY 4096 stop\n' + while IFS= read -r line; do + case "$line" in + GEN*) + printf '%s\n' "$line" >> "$dir/requests" + case "$line" in + GENI*) + set -- $line + # the embeddings path is the field before the token ids + eval "emb=\${$(($# - 1))}" + [ -s "$emb" ] && printf 'embeddings-present\n' >> "$dir/requests" + ;; + esac + printf 'T 72\nT 105\nDONE 2 7 1.0 2.0 stop 0 0 0 0 0\n' ;; + QUIT) exit 0 ;; + *) printf 'ERR unexpected request\n' ;; + esac + done + ;; stall) printf 'READY 4096 stop\n' IFS= read -r line || exit 3 diff --git a/control-plane/tests/golden/gen_goldens.py b/control-plane/tests/golden/gen_goldens.py index a14b163b..330b670f 100644 --- a/control-plane/tests/golden/gen_goldens.py +++ b/control-plane/tests/golden/gen_goldens.py @@ -539,8 +539,72 @@ def vision(): "base64": b64, "sources": src, "prepare": prepared}, dest="policy") +def vision_dialects(): + """Chat and Messages requests that carry pictures, through the real `openai_to_messages` / `anthropic_to_messages` + and the real chat template: the prompt text and the picture sources in prompt order.""" + import base64 + from pathlib import Path + from serve.frontend import ChatTemplate, anthropic_to_messages, images_of, openai_to_messages + + template = ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja") + counter = iter(range(1, 250)) + + def url(): + # a PNG signature and one tag byte: the tests find the picture again by its last byte + return "data:image/png;base64," + base64.b64encode(b"\x89PNG\r\n\x1a\n" + bytes([next(counter)])).decode() + + def chat(messages): + return {"dialect": "chat", "request": {"messages": messages, "reasoning_effort": "none"}} + + def claude(messages, system=None): + request = {"messages": messages, "thinking": {"type": "disabled"}} + if system: + request["system"] = system + return {"dialect": "messages", "request": request} + + def b64(media="image/png"): + data = url().split(",", 1)[1] + return {"type": "image", "source": {"type": "base64", "media_type": media, "data": data}} + + cases = [ + chat([{"role": "user", "content": [{"type": "text", "text": "what is this?"}, + {"type": "image_url", "image_url": {"url": url(), "detail": "high"}}]}]), + chat([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}]}]), + chat([{"role": "user", "content": [{"type": "image_url", "image_url": url()}, {"type": "text", "text": "after"}]}]), + chat([{"role": "user", "content": [{"type": "text", "text": "a"}, {"type": "image_url", "image_url": {"url": url()}}, + {"type": "text", "text": "b"}, {"type": "image_url", "image_url": url()}, + {"type": "text", "text": "c"}]}]), + chat([{"role": "system", "content": "be brief"}, + {"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}, {"type": "text", "text": "x"}]}]), + chat([{"role": "user", "content": "first"}, {"role": "assistant", "content": "ok"}, + {"role": "user", "content": [{"type": "text", "text": "again"}, {"type": "image_url", "image_url": {"url": url()}}]}]), + chat([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}]}, + {"role": "assistant", "content": "a cat"}, + {"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}, {"type": "text", "text": "and?"}]}]), + chat([{"role": "user", "content": [{"type": "text", "text": "the docs say <|image_pad|> marks an image"}, + {"type": "image_url", "image_url": {"url": url()}}]}]), + claude([{"role": "user", "content": [b64(), {"type": "text", "text": "describe"}]}]), + claude([{"role": "user", "content": [{"type": "text", "text": "describe"}, b64("image/jpeg")]}], system="be brief"), + claude([{"role": "user", "content": [b64(), b64(), {"type": "text", "text": "compare"}]}]), + claude([{"role": "user", "content": [{"type": "text", "text": "look"}, {"type": "image", "source": {"type": "url", "url": url()}}]}]), + claude([{"role": "user", "content": [{"type": "image", "source": {"type": "url", "url": url()}}]}]), + claude([{"role": "user", "content": "first"}, {"role": "assistant", "content": [{"type": "text", "text": "ok"}]}, + {"role": "user", "content": [b64(), {"type": "text", "text": "now this"}]}]), + ] + out = [] + for case in cases: + req = case["request"] + if case["dialect"] == "chat": + messages, tools, kw = openai_to_messages(req) + else: + messages, tools, kw = anthropic_to_messages(req) + out.append({**case, "prompt": template.render(messages, tools=tools, **kw), "images": images_of(messages)}) + write("vision_dialects", {"source": "serve/frontend.py openai_to_messages / anthropic_to_messages + chat_template.jinja", + "cases": out}) + + SECTIONS = {"gen_lines": gen_lines, "shared": shared, "reasoning": reasoning, "http": http_surface, - "timings": timings, "vision": vision} + "timings": timings, "vision": vision, "vision_dialects": vision_dialects} def main(argv): diff --git a/control-plane/tests/vision_http.rs b/control-plane/tests/vision_http.rs new file mode 100644 index 00000000..f34ca6aa --- /dev/null +++ b/control-plane/tests/vision_http.rs @@ -0,0 +1,659 @@ +//! Pictures over HTTP in the three dialects (Chat Completions, Messages, Responses): the request is parsed, the +//! template writes `<|vision_start|><|image_pad|><|vision_end|>` per picture, the resident encoder (a stand-in for +//! `strata-vision`) is asked for the rows, every pad becomes one pad per row and the engine receives `GENI` with the +//! embeddings file. The engine is the mock in `tests/fixtures/mock_engine.sh` (mode `images`). + +use std::{ + fs, + os::unix::fs::PermissionsExt, + path::{Path, PathBuf}, + sync::Arc, + time::Duration, +}; + +use leleka_serving_policy::vision as policy; +use serde_json::{Map, Value, json}; +use strata_control::{ + app::{AppState, router}, + tokenizer::Tokenizer, + vision::{Vision, VisionConfig}, + worker::{WorkerConfig, WorkerState, WorkerStatus, run_supervised}, +}; +use tokio::sync::{RwLock, mpsc, watch}; + +const SPECIALS: [&str; 7] = [ + "<|im_start|>", + "<|im_end|>", + "", + "", + "<|vision_start|>", + "<|image_pad|>", + "<|vision_end|>", +]; +const PAD: u32 = 256 + 5; +const START: u32 = 256 + 4; +const END: u32 = 256 + 6; + +fn scratch(name: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("strata-vision-http-{}-{name}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir +} + +fn tokenizer(dir: &Path) -> Arc { + let root = dir.join("tokenizer"); + fs::create_dir(&root).unwrap(); + let mut vocabulary = Map::new(); + for (id, ch) in strata_control::tokenizer::byte_alphabet() + .0 + .iter() + .enumerate() + { + vocabulary.insert(ch.to_string(), json!(id)); + } + for (offset, token) in SPECIALS.iter().enumerate() { + vocabulary.insert((*token).into(), json!(256 + offset)); + } + let total = 256 + SPECIALS.len(); + fs::write( + root.join("vocab.json"), + serde_json::to_vec(&vocabulary).unwrap(), + ) + .unwrap(); + fs::write(root.join("merges.txt"), "").unwrap(); + let mut types = vec![1u8; total]; + types[256..].fill(3); + fs::write( + root.join("token_type.json"), + serde_json::to_vec(&types).unwrap(), + ) + .unwrap(); + fs::write( + root.join("tokenizer.json"), + serde_json::to_vec(&json!({ + "model": "gpt2", "pre": "qwen35", "vocab_size": total, "n_merges": 0, + "pre_pattern": leleka_tokenizer::QWEN35_PATTERN, + "special_ids": {"tokenizer.ggml.eos_token_id": 257} + })) + .unwrap(), + ) + .unwrap(); + Arc::new(Tokenizer::from_assets(&root).unwrap()) +} + +fn png(tag: u8) -> Vec { + let mut data = b"\x89PNG\r\n\x1a\n".to_vec(); + data.push(tag); + data +} + +fn base64(bytes: &[u8]) -> String { + const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::new(); + for chunk in bytes.chunks(3) { + let n = chunk + .iter() + .enumerate() + .fold(0u32, |n, (i, b)| n | (u32::from(*b) << (16 - 8 * i))); + for i in 0..4 { + out.push(if i <= chunk.len() { + ALPHABET[((n >> (18 - 6 * i)) & 63) as usize] as char + } else { + '=' + }); + } + } + out +} + +fn data_url(tag: u8) -> String { + format!("data:image/png;base64,{}", base64(&png(tag))) +} + +fn fake_encoder(dir: &Path, mode: &str) -> VisionConfig { + let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures"); + let wrapper = dir.join("strata-vision.sh"); + fs::write( + &wrapper, + format!( + "#!/bin/sh\nexec '{}' {mode} '{}' \"$@\"\n", + fixtures.join("fake_vision.sh").display(), + dir.display() + ), + ) + .unwrap(); + fs::set_permissions(&wrapper, fs::Permissions::from_mode(0o755)).unwrap(); + serde_json::from_value( + json!({"exe": wrapper, "mmproj": "/m/mmproj.gguf", "model": "/m/model.gguf"}), + ) + .unwrap() +} + +struct Harness { + base: String, + dir: PathBuf, + state: AppState, + stop: watch::Sender, + worker: tokio::task::JoinHandle<()>, + server: tokio::task::JoinHandle<()>, + client: reqwest::Client, +} + +impl Harness { + async fn start(name: &str, encoder: Option<&str>) -> Self { + let dir = scratch(name); + let tokenizer = tokenizer(&dir); + let vision = match encoder { + Some(mode) => Some(Vision::start(fake_encoder(&dir, mode)).await.unwrap()), + None => None, + }; + let engine = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mock_engine.sh"); + let config = WorkerConfig { + executable: engine.into_os_string(), + args: vec![ + "images".into(), + dir.to_string_lossy().into_owned(), + "x".into(), + ], + startup_timeout: Duration::from_secs(10), + vision: vision.clone(), + ..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 state = AppState { + model: Some("strata-test".into()), + worker: status, + generation: Some(requests), + control: Some(control), + tokenizer: Some(tokenizer), + vision, + ..Default::default() + }; + 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; + }); + tokio::time::timeout(Duration::from_secs(10), async { + while state.worker.read().await.state != WorkerState::Ready { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("worker ready"); + Self { + base, + dir, + state, + stop, + worker, + server, + client: reqwest::Client::new(), + } + } + + async fn post(&self, path: &str, body: Value) -> (u16, Value) { + let response = self + .client + .post(format!("{}{path}", self.base)) + .header("content-type", "application/json") + .header("anthropic-version", "2023-06-01") + .body(body.to_string()) + .send() + .await + .unwrap(); + let status = response.status().as_u16(); + ( + status, + serde_json::from_str(&response.text().await.unwrap()).unwrap_or(Value::Null), + ) + } + + async fn get(&self, path: &str) -> Value { + serde_json::from_str( + &self + .client + .get(format!("{}{path}", self.base)) + .send() + .await + .unwrap() + .text() + .await + .unwrap(), + ) + .unwrap() + } + + fn lines(&self, file: &str) -> Vec { + fs::read_to_string(self.dir.join(file)) + .unwrap_or_default() + .lines() + .map(str::to_owned) + .collect() + } + + /// The engine lines of this run: what the mock logged for each GEN / GENI. + fn engine_lines(&self) -> Vec { + self.lines("requests") + } + + async fn finish(self) { + self.server.abort(); + self.stop.send(true).unwrap(); + let _ = tokio::time::timeout(Duration::from_secs(25), self.worker).await; + if let Some(vision) = &self.state.vision { + vision.close().await; + } + let _ = fs::remove_dir_all(self.dir); + } +} + +/// `(max_new, embeddings path, ids)` of a `GENI` line. +fn geni_line(line: &str) -> (u32, String, Vec) { + let fields: Vec<&str> = line.split(' ').collect(); + assert_eq!(fields[0], "GENI", "{line}"); + let ids = fields + .last() + .unwrap() + .split(',') + .map(|n| n.parse().unwrap()) + .collect(); + ( + fields[1].parse().unwrap(), + fields[fields.len() - 2].to_owned(), + ids, + ) +} + +/// Every maximal run of pads, with the token before and after it. +fn pad_runs(ids: &[u32]) -> Vec<(u32, usize, u32)> { + let mut runs = Vec::new(); + let mut at = 0; + while at < ids.len() { + if ids[at] == PAD { + let from = at; + while at < ids.len() && ids[at] == PAD { + at += 1; + } + runs.push((ids[from - 1], at - from, ids[at])); + } else { + at += 1; + } + } + runs +} + +async fn wait_for(what: &str, mut ready: impl FnMut() -> bool) { + for _ in 0..200 { + if ready() { + return; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + panic!("timed out waiting for {what}"); +} + +#[tokio::test] +async fn chat_messages_and_responses_pictures_reach_the_engine_as_geni() { + let h = Harness::start("dialects", Some("ok")).await; + + // Chat Completions: image_url as an object with detail, and as a bare string + let (status, body) = h + .post( + "/v1/chat/completions", + json!({"model": "strata-test", "max_tokens": 20, "messages": [{"role": "user", "content": [ + {"type": "text", "text": "what is this?"}, + {"type": "image_url", "image_url": {"url": data_url(1), "detail": "high"}}, + {"type": "image_url", "image_url": data_url(2)}, + ]}]}), + ) + .await; + assert_eq!(status, 200, "{body}"); + assert_eq!(body["choices"][0]["message"]["content"], "Hi"); + + // Messages: base64 source + let (status, body) = h + .post( + "/v1/messages", + json!({"model": "strata-test", "max_tokens": 20, "messages": [{"role": "user", "content": [ + {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": base64(&png(3))}}, + {"type": "text", "text": "and this?"}, + ]}]}), + ) + .await; + assert_eq!(status, 200, "{body}"); + assert_eq!(body["content"][0]["text"], "Hi"); + + // Responses: input_image + let (status, body) = h + .post( + "/v1/responses", + json!({"model": "strata-test", "max_output_tokens": 20, "store": false, "reasoning": {"effort": "none"}, + "input": [{"role": "user", "content": [ + {"type": "input_text", "text": "look"}, + {"type": "input_image", "image_url": data_url(1)}]}]}), + ) + .await; + assert_eq!(status, 200, "{body}"); + assert_eq!(body["output"][0]["content"][0]["text"], "Hi"); + + let lines = h.engine_lines(); + let sent: Vec<&String> = lines.iter().filter(|l| l.starts_with("GENI")).collect(); + assert_eq!(sent.len(), 3, "{lines:?}"); + // Chat: two pictures, six rows each, in prompt order, text before them + let (max_new, path, ids) = geni_line(sent[0]); + assert!( + max_new > 0 && path.contains("/req-") && path.ends_with(".sve"), + "{}", + sent[0] + ); + assert_eq!(pad_runs(&ids), vec![(START, 6, END), (START, 6, END)]); + let text = String::from_utf8_lossy( + &ids.iter() + .filter(|id| **id < 256) + .map(|id| *id as u8) + .collect::>(), + ) + .into_owned(); + assert!(text.contains("what is this?"), "{text}"); + // Messages: the picture comes first in the user turn + let (_, _, ids) = geni_line(sent[1]); + assert_eq!(pad_runs(&ids), vec![(START, 6, END)]); + let at = ids.iter().position(|id| *id == START).unwrap(); + let after = String::from_utf8_lossy( + &ids[at + 8..] + .iter() + .take_while(|id| **id < 256) + .map(|id| *id as u8) + .collect::>(), + ) + .into_owned(); + assert!(after.starts_with("and this?"), "{after}"); + // Responses + let (_, _, ids) = geni_line(sent[2]); + assert_eq!(pad_runs(&ids), vec![(START, 6, END)]); + // the engine saw a non-empty embeddings file for each (the mock checks at request time) + assert_eq!( + lines.iter().filter(|l| *l == "embeddings-present").count(), + 3, + "{lines:?}" + ); + // the encoder ran for three distinct pictures only (picture 1 was sent twice) + assert_eq!(h.lines("enc.log").len(), 3); + // the per-request files go with their requests + let vision_dir = h.state.vision.as_ref().unwrap().dir().to_path_buf(); + wait_for("req files removed", || { + fs::read_dir(&vision_dir) + .unwrap() + .all(|e| !e.unwrap().file_name().to_string_lossy().starts_with("req-")) + }) + .await; + // the combined file of the first request held two SVE1 records + let (status, _) = h.post("/v1/chat/completions", json!({"model": "strata-test", "max_tokens": 5, "messages": [{"role": "user", "content": "plain"}]})).await; + assert_eq!(status, 200); + assert!( + h.engine_lines().last().unwrap().starts_with("GEN "), + "text requests stay GEN" + ); + + // streaming Chat with a picture + let response = h + .client + .post(format!("{}/v1/chat/completions", h.base)) + .header("content-type", "application/json") + .body(json!({"model": "strata-test", "max_tokens": 20, "stream": true, "messages": [{"role": "user", "content": [ + {"type": "image_url", "image_url": {"url": data_url(1)}}]}]}).to_string()) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + let text = response.text().await.unwrap(); + assert!(text.contains("\"Hi\"") || text.contains("H"), "{text}"); + assert!( + h.engine_lines() + .iter() + .filter(|l| l.starts_with("GENI")) + .count() + == 4 + ); + + h.finish().await; +} + +#[tokio::test] +async fn pictures_need_the_encoder_and_a_readable_image() { + // without the encoder: the Python server's words, in each dialect + let h = Harness::start("noenc", None).await; + let message = "this server was started without the vision encoder (run setup again and choose 'vision'), so it cannot read images"; + for (path, body) in [ + ( + "/v1/chat/completions", + json!({"model": "strata-test", "max_tokens": 5, "messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": data_url(1)}}]}]}), + ), + ( + "/v1/messages", + json!({"model": "strata-test", "max_tokens": 5, "messages": [{"role": "user", "content": [{"type": "image", "source": {"type": "url", "url": "http://x/y.png"}}]}]}), + ), + ( + "/v1/responses", + json!({"model": "strata-test", "store": false, "input": [{"role": "user", "content": [{"type": "input_image", "image_url": data_url(1)}]}]}), + ), + ] { + let (status, body) = h.post(path, body).await; + assert_eq!(status, 400, "{path} {body}"); + let text = body.to_string(); + assert!(text.contains(message), "{path} {text}"); + } + assert!(h.engine_lines().is_empty()); + assert_eq!(h.get("/props").await["modalities"]["vision"], false); + assert_eq!(h.get("/v1/status").await["vision"]["enabled"], false); + assert_eq!(h.get("/api/health").await["images"], false); + h.finish().await; + + // an encoder that cannot read the picture + let h = Harness::start("bad-image", Some("err")).await; + let (status, body) = h + .post("/v1/chat/completions", json!({"model": "strata-test", "max_tokens": 5, "messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": data_url(1)}}]}]})) + .await; + assert_eq!(status, 400, "{body}"); + assert!( + body.to_string() + .contains("the image could not be read: cannot read the image"), + "{body}" + ); + // unsupported formats and unreadable sources + for (url, want) in [ + ( + "data:image/webp;base64,UklGRg==", + "this image format is not supported", + ), + ( + "no/such/file.png", + "an image must be a data: URL, an http(s) URL or a local file path", + ), + ( + "", + "an image must be a data: URL, an http(s) URL or a local file path", + ), + ] { + let (status, body) = h + .post("/v1/chat/completions", json!({"model": "strata-test", "max_tokens": 5, "messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url}}]}]})) + .await; + assert_eq!(status, 400, "{body}"); + assert!(body.to_string().contains(want), "{body}"); + } + assert!(h.engine_lines().is_empty()); + h.finish().await; +} + +#[tokio::test] +async fn token_counters_do_not_start_the_encoder_and_count_one_pad_per_picture() { + let h = Harness::start("count", Some("ok")).await; + let count = |n: usize| { + h.post( + "/v1/messages/count_tokens", + json!({"model": "strata-test", "messages": [{"role": "user", "content": (0..n) + .map(|i| json!({"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": base64(&png(i as u8))}})) + .collect::>()}]}), + ) + }; + let (status, one) = count(1).await; + assert_eq!(status, 200, "{one}"); + let (_, three) = count(3).await; + // three pictures add two more `<|vision_start|><|image_pad|><|vision_end|>` triples: 6 tokens + assert_eq!( + three["input_tokens"].as_u64().unwrap() - one["input_tokens"].as_u64().unwrap(), + 6 + ); + assert!(h.lines("enc.log").is_empty(), "counting never encodes"); + let (status, body) = h + .post( + "/v1/responses/input_tokens", + json!({"model": "strata-test", "input": [{"role": "user", "content": [{"type": "input_image", "image_url": data_url(1)}]}]}), + ) + .await; + assert_eq!(status, 200, "{body}"); + assert!(h.lines("enc.log").is_empty()); + h.finish().await; +} + +#[tokio::test] +async fn unload_stops_the_encoder_and_the_next_request_starts_it_before_the_engine() { + let h = Harness::start("lifecycle", Some("ok")).await; + assert_eq!(h.get("/props").await["modalities"]["vision"], true); + assert_eq!(h.get("/v1/status").await["vision"]["available"], true); + assert_eq!(h.get("/api/health").await["images"], true); + assert_eq!( + h.get("/v1/models").await["data"][0]["architecture"]["input_modalities"], + json!(["text", "image"]) + ); + let vision = h.state.vision.clone().unwrap(); + let body = json!({"model": "strata-test", "max_tokens": 5, "messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": data_url(1)}}]}]}); + assert_eq!(h.post("/v1/chat/completions", body.clone()).await.0, 200); + assert!(vision.alive().await); + let (status, answer) = h.post("/unload", json!({})).await; + assert_eq!(status, 200, "{answer}"); + assert!( + !vision.alive().await, + "unloading the model unloads the encoder" + ); + // the cached picture needs no encoder, but the request restarts both + assert_eq!(h.post("/v1/chat/completions", body).await.0, 200); + assert!(vision.alive().await); + assert_eq!(h.lines("starts.log").len(), 2); + assert_eq!(h.lines("boots").len(), 2); + h.finish().await; +} + +#[test] +fn the_expansion_matches_the_engine_side_position_table() { + // The rows the encoder wrote line up with the pads the server sent: one SVE1 record of 6 rows per picture. + let mut record = Vec::new(); + for v in [policy::SVE1_MAGIC, 6, 3, 2, 4] { + record.extend_from_slice(&v.to_le_bytes()); + } + record.extend(std::iter::repeat_n(0u8, 6 * 4 * 4)); + let embeddings = policy::parse_embeddings(&record, 4).unwrap(); + let ids: Vec = [1, PAD, PAD, PAD, PAD, PAD, PAD, 9] + .iter() + .map(|v| i64::from(*v)) + .collect(); + let positions = policy::build_positions(&ids, 16, &embeddings, 4, i64::from(PAD)).unwrap(); + assert_eq!(positions.images.len(), 1); +} + +/// The ids of a request as the template wrote them: bytes as bytes, specials by name, and a run of the rows one +/// picture got collapsed back to the single `<|image_pad|>` of the template. +fn prompt_of(ids: &[u32], rows: usize) -> String { + let mut bytes = Vec::new(); + let mut at = 0; + while at < ids.len() { + let id = ids[at]; + if id == PAD { + assert!( + ids[at..].len() >= rows && ids[at..at + rows].iter().all(|i| *i == PAD), + "a full run of {rows} rows" + ); + at += rows; + } else { + at += 1; + } + match id { + 0..=255 => bytes.push(id as u8), + _ => bytes.extend(SPECIALS[id as usize - 256].bytes()), + } + } + String::from_utf8(bytes).unwrap() +} + +/// The pictures' tag bytes (the last byte of each fake PNG) in the order the golden lists their sources. +fn tags_of(sources: &Value) -> Vec { + sources + .as_array() + .unwrap() + .iter() + .map(|source| { + let payload = source.as_str().unwrap().split_once(',').unwrap().1; + format!( + "tag={}", + policy::b64decode(payload).unwrap().last().unwrap() + ) + }) + .collect() +} + +/// Every Chat and Messages request of `fixtures/golden/vision_dialects.json` (recorded from the Python handlers +/// `openai_to_messages` / `anthropic_to_messages` and the chat template) reaches the engine as the same prompt, with +/// the same pictures in the same order. +#[tokio::test] +async fn pictures_render_and_order_like_the_python_handlers() { + let golden: Value = + serde_json::from_str(include_str!("fixtures/golden/vision_dialects.json")).unwrap(); + let cases = golden["cases"].as_array().unwrap(); + assert!(cases.len() >= 14); + let h = Harness::start("golden", Some("ok")).await; + let (mut sent, mut encoded) = (0, 0); + for (index, case) in cases.iter().enumerate() { + let mut body = case["request"].clone(); + body["model"] = json!("strata-test"); + body["max_tokens"] = json!(20); + let path = match case["dialect"].as_str().unwrap() { + "chat" => "/v1/chat/completions", + _ => "/v1/messages", + }; + let (status, answer) = h.post(path, body).await; + assert_eq!(status, 200, "case {index}: {answer}"); + let lines = h.engine_lines(); + let geni: Vec<&String> = lines.iter().filter(|l| l.starts_with("GENI")).collect(); + assert_eq!(geni.len(), sent + 1, "case {index}"); + sent += 1; + let (_, _, ids) = geni_line(geni[sent - 1]); + assert_eq!( + prompt_of(&ids, 6), + case["prompt"].as_str().unwrap(), + "case {index}" + ); + let want = tags_of(&case["images"]); + let log = h.lines("enc.log"); + let got: Vec = log[encoded..] + .iter() + .map(|l| l.rsplit(' ').next().unwrap().to_owned()) + .collect(); + encoded = log.len(); + assert_eq!(got, want, "case {index}: pictures in prompt order"); + } + h.finish().await; +} diff --git a/docs/port-remaining.md b/docs/port-remaining.md new file mode 100644 index 00000000..b11d2f62 --- /dev/null +++ b/docs/port-remaining.md @@ -0,0 +1,46 @@ +# Remaining Strata port: status, divergences and call sites + +Everything here is verified without a GPU. Items are numbered as in the port brief. Oracle = the Python server and +engine under `engine/strata`. + +## 1. Vision over HTTP + +| Piece | Rust | Oracle | +| --- | --- | --- | +| Image parts, three dialects | `control-plane/src/chat.rs` (`image_url`), `messages.rs` (`image` blocks), `responses.rs` (`input_image`) | `serve/frontend.py` `_parts_of`, `_image_source`, `images_of` | +| Template with picture items | `prompt.rs` (`Part`, `render_with_images`) | `serve/chat_template.jinja` | +| Encoder client, cache, `ENC` protocol | `control-plane/src/vision.rs` | `serve/server.py` `Vision`, `tools/vision/strata_vision.cpp` | +| Pad expansion, SVE1 files, M-RoPE positions | `crates/serving-policy/src/vision.rs` (existing) | `Service.prepare`, `generate.cpp` | +| `GENI` line | `wire.rs` (existing) | `StrataEngine.generate` | + +Flow of a request with pictures: parse the part in the dialect adapter (all three reduce to a Responses +`input_image`), `render_request` writes `<|vision_start|><|image_pad|><|vision_end|>` per picture and returns the +sources in prompt order, the prompt is tokenized, `expand_images` encodes the pictures (holding `Vision::gate`, the +mutex the worker also holds for every generation, so encoder and engine never share the GPU), turns each pad that +follows `<|vision_start|>` into one pad per image token (a pad anywhere else stays literal text), concatenates the SVE1 +files into a per-request `req-*.sve` and puts its path in `Generate.embeddings` (`GENI`). The reasoning-budget +wrap-up pass re-sends the same embeddings. The file is removed when the last clone of the request is dropped. + +Configuration: a top-level `vision` object `{exe, mmproj, model, gpu, threads, max_tokens, cuda_device}` (as in the +Python config). It needs an engine and refuses `lazy_load` (`lazy loading is text-only`). `strata-vision` starts +before the engine, stops when the engine is unloaded and starts again before the next load. `/props`, `/v1/status`, +`/api/health` and `/v1/models` report `images`/`modalities`/`architecture` accordingly. + +Goldens: `control-plane/tests/fixtures/golden/vision_dialects.json` is recorded from the real Python handlers and +template by `gen_goldens.py vision_dialects`; `tests/vision_http.rs` replays all fourteen requests over HTTP against +the mock engine and a stand-in encoder (`tests/fixtures/fake_vision.sh`) and compares prompt text and picture order. +`crates/serving-policy` already golden-tests the base64 decoder, sources, expansion and position table. + +Deliberate divergences: + +1. WebP, TIFF, AVIF and other formats `stb_image` cannot read are refused with a clear 400. Python converts them + with Pillow; the Python-free serving path has no decoder for them. +2. A fetched `http(s)` image is capped at 64 MiB and a network failure is a 400 naming it (Python: no cap, an + unhandled `URLError`). +3. `req-*.sve` files are deleted with the request (Python leaves them in its temp directory). +4. `count_tokens` / `input_tokens` render the prompt with one pad per picture and never start the encoder, as the + Python `_count_tokens` does; the true count only exists after encoding. +5. Local file paths are accepted as image sources exactly as in Python. This lets an API client name any file the + server can read as an image (the bytes only reach the encoder), so run the server behind an API key. +6. The Chat adapter is stricter than Python's: image parts only in user messages, unknown part keys rejected. + An image beside a `tool_result` in a Messages user turn is kept (Python drops it).