diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ea47f84..09a22565 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ - `ARC_REPLAY_WHY=1` now says, for each list recorded after the first step, why (a new shape, a second list, memory freed). The exit line counts steps replayed whole, steps with a list recorded, lists, and arguments updated. +- Added `POST /v1/chat/completions/input_tokens` to count the loaded model's Chat Completions input (#108). + - **Fixed: `/v1/models` now says that Qwen4-35B-A3B is experimental**, as `--list-models` already did. The note is on the loaded model and on its catalog entries, so the web UI and other clients can show it. diff --git a/USAGE.md b/USAGE.md index 1f416d3e..d7073a91 100644 --- a/USAGE.md +++ b/USAGE.md @@ -665,7 +665,7 @@ front does them, and its own updates keep them secure. **`--no-webui`** (`INFERZERO_NO_WEBUI=1`; the launchers' option "API only (no web UI)", `zero-server -NoWebui`, `zero-launcher.sh --no-webui`) serves only the model API: -`/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/messages` (and `/count_tokens`), `/v1/embeddings`, +`/v1/chat/completions` (and `/v1/chat/completions/input_tokens`), `/v1/completions`, `/v1/responses`, `/v1/messages` (and `/count_tokens`), `/v1/embeddings`, `/v1/models`, `/v1/audio/transcriptions` / `translations`, `/health` and `/props`. Everything else answers 404, from this computer too: the web UI, its files, projects, memory, MCP servers, the tools, saved sessions, slots, remote access, `/metrics`, `/tokenize` and Ollama's `/api/*`. Requests can't refer to files saved on the server. Tool calls go back to diff --git a/docs/server.md b/docs/server.md index c1907a9b..ce28f6fe 100644 --- a/docs/server.md +++ b/docs/server.md @@ -103,6 +103,12 @@ always parses and fits the schema: types, properties / required / additionalProperties, items, enum, const, anyOf / oneOf, `$ref`); `tool_choice` `none` / `auto` / `required` / a named function (the answer starts with a call). +- `POST /v1/chat/completions/input_tokens` accepts the same JSON body as Chat Completions. It returns + `{"input_tokens": N}` for the loaded model's rendered prompt, including message history, tool declarations, + template options and native image or audio positions. Clients can count prompts longer than the context window. + Counting does not generate a reply, claim a conversation slot or update the prompt cache. A template error, + a prompt that needs a speech transcript, or an OCR workflow without a single page that fits returns HTTP 400. If Chat would switch to + another model, load that model before counting (HTTP 409). - Other API formats, on the same models and features (`tools/api_compat.h`): - OpenAI `POST /v1/completions` (a raw prompt, no chat template: code completion) and `POST /v1/responses` (Responses API: input items, function calls and their outputs, reasoning, streamed events). diff --git a/setup.ps1 b/setup.ps1 index 61291d70..54862592 100644 --- a/setup.ps1 +++ b/setup.ps1 @@ -316,7 +316,7 @@ else { if (-not $m4) { Note "the tests need the 4B model: setup -Models 4b -Tests" } else { [string[]]$tools = @("tools\tok_test.cpp", "tools\chat_render.cpp", "tools\ref_forward.cpp", "tools\tool_stream_test.cpp", - "tests\test_http.cpp", "tests\test_api_compat.cpp", "tests\test_xcache_pools.cpp", "tests\test_xram_plan.cpp", "tests\test_hang_probe.cpp", "tests\test_sampler.cpp", + "tests\test_http.cpp", "tests\test_api_compat.cpp", "tests\test_chat_input.cpp", "tests\test_xcache_pools.cpp", "tests\test_xram_plan.cpp", "tests\test_hang_probe.cpp", "tests\test_sampler.cpp", "tests\test_hc.cpp", "tests\test_quant_rows.cpp", "tests\test_web_tools.cpp", "tests\test_gguf_pack.cpp", "tests\test_json.cpp", "tests\test_fa.cpp", "tests\test_route.cpp", "tests\test_chat_store.cpp", "tests\test_doc_read.cpp", diff --git a/src/audio_gemma4.h b/src/audio_gemma4.h index a00ffaa4..21a5c8ee 100644 --- a/src/audio_gemma4.h +++ b/src/audio_gemma4.h @@ -15,6 +15,7 @@ class GemmaAudioEncoder { public: virtual ~GemmaAudioEncoder() = default; virtual int out_dim() const = 0; + virtual size_t token_count(size_t samples) const = 0; virtual std::vector encode(const std::vector& s, int& n_tok) = 0; }; @@ -34,12 +35,12 @@ class AudioGemma4 : public GemmaAudioEncoder { } // Tokens of a clip of n 16 kHz samples. - int tokens(size_t n) const { return (int)((n + frame - 1) / frame); } + size_t token_count(size_t n) const override { return (n + frame - 1) / frame; } // 16 kHz samples -> n_tok x n_out embeddings (row-major). int out_dim() const override { return n_out; } std::vector encode(const std::vector& s, int& n_tok) override { - n_tok = tokens(s.size()); + n_tok = (int)token_count(s.size()); std::vector out((size_t)n_tok * n_out); #pragma omp parallel for for (int t = 0; t < n_tok; ++t) { diff --git a/src/http.h b/src/http.h index 51bf089c..ca9b5f69 100644 --- a/src/http.h +++ b/src/http.h @@ -248,7 +248,7 @@ class HttpServer { // sessions, slots, remote access), and the rest run as a foreign page's requests (no saved files, chats or projects) bool api_only = false; static bool api_path(const std::string& p) { - static const char* const ok[] = {"/health", "/props", "/v1/models", "/v1/chat/completions", "/v1/completions", + static const char* const ok[] = {"/health", "/props", "/v1/models", "/v1/chat/completions", "/v1/chat/completions/input_tokens", "/v1/completions", "/v1/embeddings", "/v1/messages", "/v1/messages/count_tokens", "/v1/responses", "/v1/audio/transcriptions", "/v1/audio/translations"}; for (const char* k : ok) @@ -399,7 +399,7 @@ class HttpServer { const std::string m = rq.method == "OPTIONS" ? rq.header("access-control-request-method") : rq.method; if (m == "GET" || m == "HEAD") return true; if (m != "POST") return false; - static const char* const gen[] = {"/v1/chat/completions", "/chat/completions", "/v1/completions", "/completions", + static const char* const gen[] = {"/v1/chat/completions", "/v1/chat/completions/input_tokens", "/chat/completions", "/v1/completions", "/completions", "/v1/messages", "/messages", "/v1/messages/count_tokens", "/messages/count_tokens", "/v1/responses", "/responses", "/api/chat", "/api/generate", "/api/show", "/tokenize", "/v1/audio/transcriptions", "/v1/audio/translations"}; diff --git a/src/vision_gemma4.h b/src/vision_gemma4.h index db90e126..e22bb7e6 100644 --- a/src/vision_gemma4.h +++ b/src/vision_gemma4.h @@ -21,6 +21,7 @@ class GemmaImageEncoder { int min_tokens = 0, max_tokens = 0; // tokens per image (smaller images are scaled up, larger ones down) virtual ~GemmaImageEncoder() = default; virtual int out_dim() const = 0; + virtual int plan(int w, int h, int& W, int& H) const = 0; virtual std::vector encode(const ImageRGB& im, int& n_tok) = 0; }; @@ -56,7 +57,7 @@ class VisionGemma4 : public GemmaImageEncoder { } // Tokens an image of this size becomes, and the resized size. - int plan(int w, int h, int& W, int& H) const { + int plan(int w, int h, int& W, int& H) const override { const int64_t px = (int64_t)patch * patch; img::fit_size(w, h, patch, (int64_t)min_tokens * px, (int64_t)max_tokens * px, W, H); // scaling up rounds each side up, which can pass max_tokens (when min is close to max): round down again diff --git a/tests/run_tests.ps1 b/tests/run_tests.ps1 index 0ef85edb..7622529a 100644 --- a/tests/run_tests.ps1 +++ b/tests/run_tests.ps1 @@ -195,6 +195,7 @@ Unit "Every kernel has a route in docs/routes.md (the migration leaves none behi Unit "Every switch has a kind and a fate in scripts/switches.tsv (the registry's first step)" (Get-Command powershell).Source @("-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "tests\test_switch_registry.ps1") "is current" Unit "HTTP parser (malformed requests)" .\bin\test_http.exe @() "test_http: all passed" Unit "API compatibility" .\bin\test_api_compat.exe @() "all passed" +if (Have $Model4B) { Unit "Chat input tokens against reference prompts" .\bin\test_chat_input.exe @($Model4B) "all passed" } Unit "web tools (HTML to text, result parsing, address filter)" .\bin\test_web_tools.exe @() "test_web_tools: all passed" if (Test-Path .\bin\test_chat_store.exe) { Unit "chat folders and the terminal tool" .\bin\test_chat_store.exe @() "test_chat_store: all passed" } if (Test-Path .\bin\test_doc_read.exe) { Unit "reading DOCX / PDF, outline, search" .\bin\test_doc_read.exe @() "test_doc_read: all passed" } @@ -435,7 +436,8 @@ foreach ($eng in $engines) { if (-not (Test-Path -LiteralPath $exe)) { Skip "$tag server smoke test" "$exe not built"; continue } if (-not $sm) { Skip "$tag server smoke test" "no 4B, 27B or 35B-A3B model"; continue } Write-Host " model: $sm, port $Port" - $srv = Start-Process -FilePath $exe -ArgumentList @("-m", "`"$sm`"", "--port", $Port, "--ctx", "8192", "--alias", "test", "--no-prefix-cache") -PassThru -WindowStyle Hidden + $sessionDir = Join-Path ([IO.Path]::GetTempPath()) ([Guid]::NewGuid().ToString("N")) + $srv = Start-Process -FilePath $exe -ArgumentList @("-m", "`"$sm`"", "--port", $Port, "--ctx", "8192", "--alias", "test", "--no-prefix-cache", "--session-cache-gb", "1", "--session-dir", "`"$sessionDir`"") -PassThru -WindowStyle Hidden try { $up = $false for ($i = 0; $i -lt $ServerWait -and -not $srv.HasExited; $i++) { @@ -448,6 +450,86 @@ foreach ($eng in $engines) { Check "$tag API tool call" ($o -match "turn 1: finish=tool_calls") Check "$tag API prefix reuse" ($o -match "cache_n=([1-9]\d*)") + # Compare with the next real Chat response on this isolated server. Sizing also runs with + # streaming and cache controls set, while the previously held generation remains observable. + $chatUrl = "http://127.0.0.1:$Port/v1/chat/completions" + $fixtures = @{} + foreach ($line in Get-Content -Encoding UTF8 tests\chat_golden\render.cases) { + $fields = $line -split "`t", 2 + $fixtures[$fields[0]] = $fields[1] | ConvertFrom-Json + } + $cases = @("simple", "declared tools", "tools", "no_think") + if ((Invoke-RestMethod "http://127.0.0.1:$Port/props").vision) { + $png = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC" + $parts = @(@{type="image_url"; image_url=@{url=$png}}, @{type="text"; text="Which color?"}) + $fixtures["image"] = @{messages=@(@{role="user"; content=$parts})} + $cases += "image" + } + foreach ($name in $cases) { + $fixture = if ($name -eq "declared tools") { $fixtures["simple"] } else { $fixtures[$name] } + $chat = @{model="test"; messages=$fixture.messages; max_tokens=1; temperature=0} + if ($name -eq "declared tools" -or $name -eq "tools") { $chat.tools = $fixtures["tools"].tools } + if ($name -eq "no_think") { $chat.chat_template_kwargs = @{enable_thinking=$false} } + $before = (Invoke-RestMethod "http://127.0.0.1:$Port/props").stats | ConvertTo-Json -Depth 16 -Compress + $chat.stream = $true + $chat.cache_prompt = $false + $count = Invoke-RestMethod "$chatUrl/input_tokens" -Method Post -ContentType "application/json" -Body ($chat | ConvertTo-Json -Depth 32) + $after = (Invoke-RestMethod "http://127.0.0.1:$Port/props").stats | ConvertTo-Json -Depth 16 -Compress + Check "$tag $name sizing preserves generation state" ($before -eq $after) + $chat.stream = $false + $reply = Invoke-RestMethod $chatUrl -Method Post -ContentType "application/json" -Body ($chat | ConvertTo-Json -Depth 32) + Check "$tag $name exact Chat input tokens" ((@($count.PSObject.Properties.Name) -join ",") -eq "input_tokens" -and + $count.input_tokens -gt 0 -and $count.input_tokens -eq $reply.usage.prompt_tokens) + } + # Save a real conversation, then count a different one with caching disabled. + $chat.messages = @(@{role="user"; content=(" x" * 1100)}) + $chat.cache_prompt = $true + $held = $chat | ConvertTo-Json -Depth 32 + $null = Invoke-RestMethod $chatUrl -Method Post -ContentType "application/json" -Body $held + $sessionsUrl = "http://127.0.0.1:$Port/sessions" + $saved = Invoke-RestMethod "$sessionsUrl/save" -Method Post + # Hold a different, unsaved prefix so restoring the file cannot mask a reset of the live KV. + $chat.messages = @(@{role="user"; content=(" sky" * 130)}) + $held = $chat | ConvertTo-Json -Depth 32 + $null = Invoke-RestMethod $chatUrl -Method Post -ContentType "application/json" -Body $held + $warm = Invoke-RestMethod $chatUrl -Method Post -ContentType "application/json" -Body $held + $state = Invoke-RestMethod $sessionsUrl + Check "$tag primed a saved session" ($saved.saved -and $state.conversations -gt 0 -and $state.bytes -gt 0) + $files = @(Get-ChildItem -LiteralPath $state.dir -Filter '*.arcs') + $hashes = @($files | Get-FileHash | ForEach-Object { $_.Hash }) + $before = $state | ConvertTo-Json -Compress + $null = Invoke-RestMethod "$chatUrl/input_tokens" -Method Post -ContentType "application/json" -Body '{"cache_prompt":false,"messages":[{"role":"user","content":"Another chat"}]}' + $after = Invoke-RestMethod $sessionsUrl | ConvertTo-Json -Compress + $newHashes = @(Get-ChildItem -LiteralPath $state.dir -Filter '*.arcs' | Get-FileHash | ForEach-Object { $_.Hash }) + $again = Invoke-RestMethod $chatUrl -Method Post -ContentType "application/json" -Body $held + Check "$tag sizing preserves the saved files and held prefix" ($before -eq $after -and $files.Count -gt 0 -and + ($hashes -join ',') -eq ($newHashes -join ',') -and $warm.timings.cache_n -ge 128 -and $again.timings.cache_n -eq $warm.timings.cache_n) + + $other = (Invoke-RestMethod "http://127.0.0.1:$Port/v1/models").data | Where-Object { -not $_.loaded } | Select-Object -First 1 + if ($other) { + $body = @{model=$other.id; messages=$fixtures["simple"].messages} | ConvertTo-Json -Depth 8 -Compress + foreach ($path in @("/v1/chat/completions/input_tokens", "/v1/messages/count_tokens")) { + $r = Raw-Http $Port ("POST $path HTTP/1.1`r`nHost: 127.0.0.1:$Port`r`nContent-Type: application/json`r`nContent-Length: {0}`r`n`r`n{1}" -f [Text.Encoding]::UTF8.GetByteCount($body), $body) + Check "$tag $path requires the requested model" ((Status-Line $r) -match "^HTTP/1\.[01] 409") + } + Check "$tag counting kept the loaded model" ((Invoke-RestMethod "http://127.0.0.1:$Port/health").model -eq "test") + } else { Skip "$tag count on another model" "no other model in the catalog" } + + $body = '{"messages":[]}' + $r = Raw-Http $Port ("POST /v1/chat/completions/input_tokens HTTP/1.1`r`nHost: 127.0.0.1:$Port`r`nContent-Type: application/json`r`nContent-Length: {0}`r`n`r`n{1}" -f $body.Length, $body) + Check "$tag unrenderable Chat input -> 400" ((Status-Line $r) -match "^HTTP/1\.[01] 400" -and $r -match "messages required") + + # The Qwen smoke models tokenize each repeated " x" as one token. Calibrate the template + # overhead on a short input, then count a prompt far beyond the server's 8192-token context. + $counts = foreach ($n in @(4, 500000)) { + $long = @{model="test"; messages=@(@{role="user"; content=(" x" * $n)})} + (Invoke-RestMethod "$chatUrl/input_tokens" -Method Post -ContentType "application/json" -Body ($long | ConvertTo-Json -Depth 8)).input_tokens + } + Check "$tag exact count beyond model context" (($counts[1] - $counts[0]) -eq (500000 - 4)) + $body = '{"speech":"whisper","messages":[{"role":"user","content":[{"type":"input_audio","input_audio":{"data":"AA==","format":"wav"}}]}]}' + $r = Raw-Http $Port ("POST /v1/chat/completions/input_tokens HTTP/1.1`r`nHost: 127.0.0.1:$Port`r`nContent-Type: application/json`r`nContent-Length: {0}`r`n`r`n{1}" -f $body.Length, $body) + Check "$tag transcript-dependent prompt -> 400" ((Status-Line $r) -match "^HTTP/1\.[01] 400" -and $r -match "transcript") + $body = '{"model":"test","prompt":"","max_tokens":4}' $r = Raw-Http $Port ("POST /v1/completions HTTP/1.1`r`nHost: 127.0.0.1`r`nContent-Type: application/json`r`nContent-Length: {0}`r`n`r`n{1}" -f [System.Text.Encoding]::UTF8.GetByteCount($body), $body) Check "$tag empty prompt -> 400" ((Status-Line $r) -match "^HTTP/1\.[01] 400") (Status-Line $r) @@ -463,7 +545,8 @@ foreach ($eng in $engines) { Check "$tag JSON nested 100,000 deep -> 400" ((Status-Line $r) -match "^HTTP/1\.[01] 400") (Status-Line $r) Check "$tag /health after the nested JSON" (Health $Port) } finally { - if (-not $srv.HasExited) { Stop-Process -Id $srv.Id -Force -ErrorAction SilentlyContinue } + if (-not $srv.HasExited) { Stop-Process -Id $srv.Id -Force -ErrorAction SilentlyContinue; $srv.WaitForExit() } + if (Test-Path -LiteralPath $sessionDir) { Remove-Item -LiteralPath $sessionDir -Recurse -Force } } } diff --git a/tests/test_chat_input.cpp b/tests/test_chat_input.cpp new file mode 100644 index 00000000..a94c9318 --- /dev/null +++ b/tests/test_chat_input.cpp @@ -0,0 +1,55 @@ +// CPU-only check of serverz's Chat input against the reference prompts in tests/chat_golden. +#include "../tools/chat_input.h" +#include +#include +#include + +static void check(bool ok, const std::string& what) { + if (!ok) throw std::runtime_error(what); +} + +static void check_prompts(const Tokenizer& tokenizer, const std::string& family, chatinput::ModelTemplate model) { + const std::string dir = "tests/chat_golden/"; + std::ifstream cases(dir + (model.qwen4 ? "render_q4.cases" : "render.cases")); + check(cases.good(), "cannot open cases for " + family); + std::string line; + while (std::getline(cases, line)) { + const auto tab = line.find('\t'); + check(tab != std::string::npos, "invalid render case"); + const auto name = family + "." + line.substr(0, tab); + Json body = Json::parse(line.substr(tab + 1)); + if (body.has("preserve_thinking")) { // the fixture's renderer option, as sent over HTTP + Json kwargs = Json::object(); + kwargs.set("preserve_thinking", body["preserve_thinking"]); + body.set("chat_template_kwargs", kwargs); + } + std::ifstream file(dir + "render/" + name + ".txt", std::ios::binary); + check(file.good(), "missing golden for " + name); + const std::string golden{std::istreambuf_iterator(file), {}}; + const auto prompt = chatinput::render(body, tokenizer, model); + check(prompt.tokens(tokenizer) == tokenizer.encode(golden, true), "wrong prompt tokens for " + name); + } +} + +int main(int argc, char** argv) try { + if (argc != 2) throw std::runtime_error("usage: test_chat_input model.gguf (from the repository root)"); + const GgufFile model(argv[1]); + const Tokenizer tokenizer(model); + check_prompts(tokenizer, "q35", {}); + check_prompts(tokenizer, "q38", {.qwen38 = true}); + check_prompts(tokenizer, "q4", {.qwen4 = true, .can_preserve = true, .default_preserve = true}); + const Json body = Json::parse(R"({"messages":[{"role":"unknown","content":"Hello"}]})"); + bool rejected = false; + try { + chatinput::render(body, tokenizer, {.inkling = true}); + } catch (const std::exception& e) { + check(std::string(e.what()).find("Unknown message role: unknown") != std::string::npos, e.what()); + rejected = true; + } + check(rejected, "template error did not reach the caller"); + std::cout << "test_chat_input: all passed\n"; + return 0; +} catch (const std::exception& e) { + std::cerr << e.what() << '\n'; + return 1; +} diff --git a/tests/test_ocr_input.sh b/tests/test_ocr_input.sh new file mode 100755 index 00000000..2e25ea54 --- /dev/null +++ b/tests/test_ocr_input.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# Run against an isolated OCR server with a vision projector, e.g. --alias test-ocr --ctx 2048. +# The two-page fixture exercises the PDF wrapper; the official OCR task keeps the appended text. +set -euo pipefail +base=${1:-http://127.0.0.1:8090} +curl -fsS "$base/props" | jq -e '.ocr and .vision' >/dev/null +ctx=$(curl -fsS "$base/health" | jq -er '.n_ctx') +pdf="$(dirname "$0")/data/doc_sample.pdf" +id=$(curl -fsS -F "file=@$pdf" "$base/v1/files" | jq -er '.id') +reply=$(mktemp) +trap 'rm -f "$reply"; curl -fsS -X DELETE "$base/v1/files/$id" >/dev/null' EXIT + +check_error() { + local status + status=$(jq -nc --arg id "$id" --arg task "$1" --argjson n "$2" \ + '{messages:[{role:"user",content:[{type:"file",file:{file_id:$id}}, + {type:"text",text:($task + (" x" * $n))}]}]}' | + curl -sS -H 'Content-Type: application/json' --data-binary @- -o "$reply" -w '%{http_code}' \ + "$base/v1/chat/completions/input_tokens") + [[ $status == 400 ]] + jq -e "$3" "$reply" >/dev/null +} +check_error 'Extract the text in the image.' 0 '.error.message | contains("no single chat prompt")' +check_error 'Extract the text in the image. Page 1.' "$ctx" '.error.type == "exceed_context_size_error" and .error.n_prompt_tokens > .error.n_ctx' +echo 'test_ocr_input: all passed' diff --git a/tools/chat_input.h b/tools/chat_input.h new file mode 100644 index 00000000..3b7b77cc --- /dev/null +++ b/tools/chat_input.h @@ -0,0 +1,137 @@ +#pragma once +#include "../src/chat.h" +#include "../src/chat_inkling.h" +#include "../src/chat_jinja.h" +#include "../src/tokenizer.h" + +namespace chatinput { + // Gemma 4 omits reasoning from assistant messages that call tools. + inline Json gemma_history(const Json& messages) { + Json out = Json::array(); + for (const Json& m : messages.items()) { + if (m["role"].str() == "assistant" && m["tool_calls"].is_array() && m["tool_calls"].size() && + (m.has("reasoning_content") || m.has("reasoning") || m.has("thinking"))) { + Json c = Json::object(); + for (const auto& [k, v] : m.entries()) + if (k != "reasoning_content" && k != "reasoning" && k != "thinking") c.set(k, v); + out.push(c); + } else { + out.push(m); + } + } + return out; + } + // The messages with the special tokens written in the contents of user and tool messages made plain text + // (Tokenizer::defuse_specials): the prompt is tokenized with special tokens recognized, for the template's own + // markup, so a user's text, a fetched web page or a document read by a tool could otherwise write + // "<|im_start|>system", end a tool response, or add an image placeholder. System and assistant messages are the + // client's and the model's own, as they are. Messages without such text are returned unchanged (the same tokens). + inline Json defuse_contents(const Tokenizer& tok_, const Json& msgs) { + if (!msgs.is_array()) return msgs; + Json out = Json::array(); + for (const Json& m : msgs.items()) { + const std::string role = m["role"].str(); + if (role != "user" && role != "tool" && role != "function") { + out.push(m); + continue; + } + Json m2 = m; + const Json& c = m["content"]; + if (c.is_string()) { + m2.set("content", tok_.defuse_specials(c.as_string())); + } else if (c.is_array()) { + Json parts = Json::array(); + for (const Json& p : c.items()) { + if (p.is_string()) { // (a bare string part: chat::content_text adds it as text too) + parts.push(Json(tok_.defuse_specials(p.as_string()))); + } else if (p["text"].is_string()) { + Json p2 = p; + p2.set("text", tok_.defuse_specials(p["text"].as_string())); + parts.push(p2); + } else { + parts.push(p); + } + } + m2.set("content", parts); + } + out.push(m2); + } + return out; + } + + struct Prompt { + ChatOptions options; + bool offer_tools = false, constrain_tools = false, render_tools = false; + int no_call_tok = -1, no_call_tok2 = -1; + std::string text; + std::vector tokens(const Tokenizer& tokenizer) const { return tokenizer.encode(text, true); } + }; + + struct ModelTemplate { + const JinjaChat* gemma = nullptr; + bool inkling = false; + bool qwen38 = false, qwen4 = false; + bool can_preserve = false, default_preserve = false; + }; + + inline Prompt render(const Json& body, const Tokenizer& tokenizer, const ModelTemplate& model) { + const Json& messages = body["messages"]; + if (!messages.is_array() || messages.size() == 0) throw std::runtime_error("messages required"); + Prompt p; + const Json& tools = body["tools"]; + p.offer_tools = !tools.is_null(); + // tool_choice "none": the tools stay in the prompt (it is the same as the turns before, so the prompt cache holds: + // the web UI's last answer after its tool rounds processed the whole chat again without them), and the call's + // open marker is never drawn (no_call_tok, below) + const bool no_calls = body["tool_choice"].str() == "none"; + if (no_calls && tools.is_array() && tools.size()) { + const std::vector o = tokenizer.encode(model.gemma ? "<|tool_call>" : model.inkling ? "<|content_invoke_tool_json|>" : "", true); + if (o.size() == 1) p.no_call_tok = o[0]; + else p.offer_tools = false; // (not one token: the tools left out, as before) + if (model.inkling) { + const int t2 = tokenizer.token("<|content_invoke_tool_text|>"); + if (t2 >= 0) p.no_call_tok2 = t2; + } + } else if (no_calls) { + p.offer_tools = false; + } + const std::string format = body["response_format"]["type"].str(); + p.constrain_tools = p.offer_tools && format != "json_object" && format != "json_schema"; + ChatOptions& co = p.options; + if (body["enable_thinking"].is_bool()) co.enable_thinking = body["enable_thinking"].as_bool(); + if (body["chat_template_kwargs"]["enable_thinking"].is_bool()) co.enable_thinking = body["chat_template_kwargs"]["enable_thinking"].as_bool(); + const std::string effort = body["reasoning_effort"].str(body["chat_template_kwargs"]["reasoning_effort"].str()); + if (effort == "none" || effort == "minimal" || effort == "off") co.enable_thinking = false; + else if (model.qwen4) co.reasoning_effort = effort; // render_qwen4 maps the word, high by default + else if (effort == "low") co.reasoning_effort = "low"; + else if (effort == "medium") co.reasoning_effort = "medium"; + else if (!effort.empty()) co.reasoning_effort = "xhigh"; + // earlier turns keep their reasoning: only where the model's template offers it (Qwen3.6) + co.preserve_thinking = model.can_preserve && body["chat_template_kwargs"]["preserve_thinking"].as_bool(model.default_preserve); + // Gemma 4: an assistant message with tool calls goes in without its reasoning. The template keeps that reasoning + // while the turn's tool rounds go on and drops it once the user writes again, so the next turn's prompt differed + // right before the tool results: a 20K-token result processed again for a one-line question (E4B: 38 s). Without + // it every turn renders the same; a tool round only goes back over the reasoning just generated (rewind) + const Json gmsgs = model.gemma ? gemma_history(messages) : Json(); + const Json& rmsgs = model.gemma ? gmsgs : messages; // (the messages the template renders) + const bool raw_prompt = body["__raw_prompt"].is_string(); // (api_compat: the prompt text as it is) + p.render_tools = p.constrain_tools && !raw_prompt; + if (raw_prompt) co.enable_thinking = false; + const Json no_tools; + const Json& rendered_tools = p.render_tools ? tools : no_tools; + // (Inkling 2: its effort message; thinking off is effort 0 ("none"), else the request's reasoning_effort, a name or + // a number, and none given the template's default 0.9. A name the format does not know is a 400, as there) + Json ink_effort; + if (model.inkling) { + const Json& re = body["reasoning_effort"].is_null() ? body["chat_template_kwargs"]["reasoning_effort"] : body["reasoning_effort"]; + if (!co.enable_thinking) ink_effort = Json("none"); + else if (re.is_number() || (re.is_string() && !re.as_string().empty())) ink_effort = re; + } + if (raw_prompt) p.text = body["__raw_prompt"].str(); + else if (model.inkling) p.text = inkling::render(messages, rendered_tools, ink_effort); + else if (model.gemma) p.text = model.gemma->render(rmsgs, rendered_tools, true, co.enable_thinking); + else if (model.qwen4) p.text = chat::render_qwen4(messages, rendered_tools, co); + else p.text = chat::render(messages, rendered_tools, co, model.qwen38); + return p; + } +} // namespace chatinput diff --git a/tools/server.cpp b/tools/server.cpp index c23e6d43..535a2194 100644 --- a/tools/server.cpp +++ b/tools/server.cpp @@ -33,6 +33,7 @@ #include "../src/http.h" #include "../src/full_speed.h" #include "api_compat.h" +#include "chat_input.h" #include "json_constraint.h" #include "tool_constraint.h" #include "sampler.h" @@ -335,61 +336,57 @@ class Server { acquire(lk); f(); } - // The messages with the special tokens written in the contents of user and tool messages made plain text - // (Tokenizer::defuse_specials): the prompt is tokenized with special tokens recognized, for the template's own - // markup, so a user's text, a fetched web page or a document read by a tool could otherwise write - // "<|im_start|>system", end a tool response, or add an image placeholder. System and assistant messages are the - // client's and the model's own, as they are. Messages without such text are returned unchanged (the same tokens). - Json defuse_contents(const Json& msgs) const { - if (!msgs.is_array()) return msgs; - Json out = Json::array(); - for (const Json& m : msgs.items()) { - const std::string role = m["role"].str(); - if (role != "user" && role != "tool" && role != "function") { - out.push(m); - continue; - } - Json m2 = m; - const Json& c = m["content"]; - if (c.is_string()) { - m2.set("content", tok_.defuse_specials(c.as_string())); - } else if (c.is_array()) { - Json parts = Json::array(); - for (const Json& p : c.items()) { - if (p.is_string()) { // (a bare string part: chat::content_text adds it as text too) - parts.push(Json(tok_.defuse_specials(p.as_string()))); - } else if (p["text"].is_string()) { - Json p2 = p; - p2.set("text", tok_.defuse_specials(p["text"].as_string())); - parts.push(p2); - } else { - parts.push(p); - } + static bool reject_foreign_files(const HttpRequest& rq, const Json& body, HttpResponse& rs) { + if (!rq.foreign) return false; + for (const Json& m : body["messages"].items()) + for (const Json& p : m["content"].items()) + if (p["type"].str() == "file" || p["type"].str() == "input_file" || p.dump().find("\"/files/") != std::string::npos) { + rs.send(403, "application/json", err("saved files and chats are only for the server's own page").dump()); + return true; } - m2.set("content", parts); - } - out.push(m2); + return false; + } + + chatinput::Prompt prepare_chat_input(Json& body) { + { // the web UI's saved files ("file" parts): as text, or as references to the image / audio (server_files.h) + bool any = false; + for (const Json& m : body["messages"].items()) + for (const Json& p : m["content"].items()) any = any || p["type"].str() == "file" || p["type"].str() == "input_file"; + bool tools = false; // (the file tools offered: a long document goes in as its outline) + for (const Json& t : body["tools"].items()) tools = tools || t["function"]["name"].str() == "read_file"; + if (any) body.set("messages", files::expand_files(body["messages"], tools, eng_.ctx)); } - return out; + // (special tokens written in user and tool contents, the files' text included: plain text, see defuse_contents) + if (!body["__raw_prompt"].is_string()) body.set("messages", chatinput::defuse_contents(tok_, body["messages"])); + // (an OCR model: its own task prompt, tools/server_ocr.h; after the saved files became image parts: the web UI + // sends its images as files) + if (ocr_) body = ocr_request(body); + return chatinput::render(body, tok_, {.gemma = jinja_.get(), .inkling = ink_, .qwen38 = q38_, .qwen4 = q4_, + .can_preserve = can_preserve_, .default_preserve = default_preserve_}); } - // The prompt tokens of a chat request (Anthropic's count_tokens): its rendered prompt, each image or audio part - // counted as its placeholder token. No engine lock: rendering and tokenizing use no engine state (chat() does both - // before taking it). -1: the template could not render the messages. A prompt that cannot fit the context: the - // count it has at least (more than the context), not tokenized (as chat() refuses it). - int count_tokens(const Json& body) { - ChatOptions co; - if (body["enable_thinking"].is_bool()) co.enable_thinking = body["enable_thinking"].as_bool(); - std::string prompt; + + void send_input_tokens(const HttpRequest& rq, HttpResponse& rs, Json chat_body) { try { - const Json msgs = defuse_contents(body["messages"]); - prompt = jinja_ ? jinja_->render(gemma_ ? gemma_history(msgs) : msgs, body["tools"], true, co.enable_thinking) - : render_qwen(msgs, body["tools"], co); - } catch (const std::exception&) { - return -1; + Json single_input; + const bool ocr_page = ocr_ && (ocr_batch(rq, chat_body, rs, &single_input) || ocr_pdf(rq, chat_body, rs, &single_input)); + if (ocr_page) { + if (single_input.is_null()) return; // OCR already returned the reason it cannot supply one prompt. + chat_body = std::move(single_input); + } + Json result = Json::object(); + const auto input = prepare_chat_input(chat_body); + auto ids = input.tokens(tok_); + const size_t count = expand_media(chat_media(chat_body["messages"]), ids); + if (!count) throw std::runtime_error("the prompt is empty (no tokens)"); + // The OCR wrapper reports usage only for pages admitted by its inner chat request. + if (ocr_page && !prompt_fits(count)) return overflow(rs, count); + result.set("input_tokens", count); + rs.send(200, "application/json", result.dump()); + } catch (const std::exception& e) { + Json failure = err(e.what()); + if (rq.path != "/v1/chat/completions/input_tokens") failure.set("type", "error"); + rs.send(400, "application/json", failure.dump()); } - if (const size_t L = tok_.max_token_bytes(); L && prompt.size() / L > (size_t)eng_.ctx) - return (int)std::min(prompt.size() / L, INT_MAX); - return (int)tok_.encode(prompt, true).size(); } void handle(const HttpRequest& rq, HttpResponse& rs) { if (rq.method == "GET" && (rq.path == "/" || rq.path == "/index.html")) return serve_ui(rs); @@ -569,7 +566,7 @@ class Server { Json last_timings_; struct MediaEmb { std::shared_ptr> e; - int gw = 0, gh = 0; // merged-token grid (Qwen M-RoPE); 0 for Gemma and audio + int rows = 0, gw = 0, gh = 0; // embedding rows and merged-token grid (Qwen M-RoPE); 0 for Gemma and audio }; std::map img_cache_; // media embeddings keyed by the file bytes size_t img_cache_bytes_ = 0; // (their floats: the cache is emptied past 512 MB or 64 entries) @@ -881,10 +878,6 @@ class Server { bool can_preserve_ = false; // the template has Qwen3.6's preserve_thinking option bool default_preserve_ = false; // --preserve-thinking (requests can override it: chat_template_kwargs) bool q4_ = false; // Qwen4's template (src/chat.h render_qwen4): preserve_thinking on by default - // the prompt text of the Qwen family's templates (not Gemma's or Inkling's) - std::string render_qwen(const Json& messages, const Json& tools, const ChatOptions& co) const { - return q4_ ? chat::render_qwen4(messages, tools, co) : chat::render(messages, tools, co, q38_); - } private: void serve_ui(HttpResponse& rs) { @@ -1038,6 +1031,7 @@ class Server { // nothing worth saving (cache off, already saved, under 1,024 tokens). #include "server_cache.h" // (saved state: prefix cache, sessions) +#include "server_chat_media.h" #include "server_chat.h" // (the chat endpoint) #include "server_ocr.h" // (OCR models: asked with their own task prompts) }; @@ -2457,20 +2451,39 @@ static int server_main(int argc, char** argv) { apic::Adapter ad(kit->second, in, rs); return dispatch(rq2, rs); } - // Anthropic token count - if (rq.method == "POST" && (rq.path == "/v1/messages/count_tokens" || rq.path == "/messages/count_tokens")) { - Json in, chat_body; - std::string e; - if (!Json::try_parse(rq.body, in) || !apic::to_chat("anthropic", in, chat_body, e)) - return rs.send(400, "application/json", "{\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"bad request\"}}"); + const bool native_count = rq.path == "/v1/chat/completions/input_tokens"; + if (rq.method == "POST" && (native_count || rq.path == "/v1/messages/count_tokens" || rq.path == "/messages/count_tokens")) { + Json chat_body; + if (native_count) { + if (!Json::try_parse(rq.body, chat_body) || !chat_body.is_object()) + return rs.send(400, "application/json", "{\"error\":{\"type\":\"invalid_request_error\",\"message\":\"a Chat Completions JSON object is required\"}}"); + } else { + Json in; + std::string e; + if (!Json::try_parse(rq.body, in) || !apic::to_chat("anthropic", in, chat_body, e)) + return rs.send(400, "application/json", "{\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"bad request\"}}"); + } + if (Server::reject_foreign_files(rq, chat_body, rs)) return; + auto count_loaded = [&] { // caller pins the model for preprocessing, rendering and tokenization + if (!cur) return rs.send(503, "application/json", "{\"error\":{\"type\":\"server_error\",\"message\":\"load a chat model before counting its input tokens\"}}"); + if (wh && srvwh::Service::has_audio_parts(chat_body) && wh->needs_transcript(chat_body, cur->srv->has_audio())) + return rs.send(400, "application/json", "{\"error\":{\"type\":\"invalid_request_error\",\"message\":\"the prompt depends on a speech transcript\"}}"); + return cur->srv->send_input_tokens(rq, rs, std::move(chat_body)); + }; + const std::string want = chat_body["model"].str(); std::shared_lock lk(swap_mu); - if (!cur) return no_model(rs); - const int n = cur->srv->count_tokens(chat_body); - if (n < 0) // (the template could not render these messages) - return rs.send(400, "application/json", "{\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"the chat template cannot render these messages\"}}"); - Json r = Json::object(); - r.set("input_tokens", n); - return rs.send(200, "application/json", r.dump()); + if (swap && cur && !want.empty() && want != cur->alias && !known_unknown(want)) { + lk.unlock(); + std::unique_lock catalog_lock(swap_mu); + // The same catalog lookup as Chat. Never swap a model or save/evict a held prefix to count. + if (cur && want != cur->alias) { + const ModelInfo* target = find_model(want); + if (target && target->alias != cur->alias) + return rs.send(409, "application/json", "{\"error\":{\"message\":\"load the requested model before counting its input tokens\"}}"); + } + return count_loaded(); + } + return count_loaded(); } // the saved transcripts and their queue (the Transcript tab; tools/server_whisper.h) if (rq.path == "/v1/transcripts" || rq.path.rfind("/v1/transcripts/", 0) == 0 || rq.path == "/v1/live" || @@ -2592,24 +2605,13 @@ static int server_main(int argc, char** argv) { if (Json::try_parse(rq.body, in) && srvwh::Service::has_audio_parts(in)) { // (a page of another local server: the rule of chat() (server_chat.h) before Whisper reads a saved file it // names, whose transcript would reach that page in the answer; self audit 2026-11-19) - if (rq.foreign) - for (const Json& m : in["messages"].items()) - for (const Json& p : m["content"].items()) - if (p["type"].str() == "file" || p["type"].str() == "input_file" || - p.dump().find("\"/files/") != std::string::npos) - return rs.send(403, "application/json", - "{\"error\":{\"message\":\"saved files and chats are only for the server's own page\"," - "\"type\":\"invalid_request_error\"}}"); + if (Server::reject_foreign_files(rq, in, rs)) return; bool hears = false; { std::shared_lock lk(swap_mu); hears = cur && cur->srv->has_audio(); } - const std::string speech = in["speech"].str(); - // (nothing of the service loaded and nothing asked of it: as without the service, the request goes to the model - // it names, which may hear it; every server has the service now, to load speech models from Settings) - const bool none = speech.empty() && !wh->has_whisper() && !wh->asr_loaded(); - if (!none && (speech == "whisper" || (speech != "model" && !hears))) { + if (wh->needs_transcript(in, hears)) { std::string bad; int st = 400; if (!wh->audio_to_text(in, bad, st, [&] { return rs.client_gone(); })) diff --git a/tools/server_chat.h b/tools/server_chat.h index c5994852..6a613321 100644 --- a/tools/server_chat.h +++ b/tools/server_chat.h @@ -2,73 +2,45 @@ // A part of class Server (tools/server.cpp), included inside the class body at the place it was cut from: // not a header of its own. Split out of tools/server.cpp unchanged on 2026-10-24 (QUEUE item 11). - // Gemma 4: the messages as the template gets them: an assistant message with tool calls without its reasoning (see - // chat(); count_tokens renders the same) - static Json gemma_history(const Json& messages) { - Json out = Json::array(); - for (const Json& m : messages.items()) { - if (m["role"].str() == "assistant" && m["tool_calls"].is_array() && m["tool_calls"].size() && - (m.has("reasoning_content") || m.has("reasoning") || m.has("thinking"))) { - Json c = Json::object(); - for (const auto& [k, v] : m.entries()) - if (k != "reasoning_content" && k != "reasoning" && k != "thinking") c.set(k, v); - out.push(c); - } else { - out.push(m); - } - } - return out; + bool prompt_fits(size_t n) const { return n + 64 <= (size_t)eng_.ctx; } + // Same wording and error type as llama-server, so that clients recognize a context overflow (Pi then compacts + // the conversation and retries). The hybrid DeltaNet state cannot drop old tokens, so there is no server-side + // context shift. + void overflow(HttpResponse& rs, size_t n, const char* at_least = "") const { + Json e = Json::object(); + e.set("code", 400); + e.set("message", std::string("the request exceeds the available context size (prompt ") + at_least + std::to_string(n) + + " tokens, context " + std::to_string(eng_.ctx) + " tokens), try increasing it"); + e.set("type", "exceed_context_size_error"); + e.set("n_prompt_tokens", (int)std::min(n, INT_MAX)); + e.set("n_ctx", eng_.ctx); + Json r = Json::object(); + r.set("error", e); + return rs.send(400, "application/json", r.dump()); } + void chat(const HttpRequest& rq, HttpResponse& rs) { const auto t_req = clk::now(); // (the request's arrival: time to first token, end to end) Json body; if (!Json::try_parse(rq.body, body)) return rs.send(400, "application/json", err("invalid JSON body").dump()); - // (a page of another local server: no "file" parts (chat:, transcript:, a saved file) and no /files/ - // references, which would paste the user's chats and files into a prompt whose answer that page reads; the - // foreign_ok rule says such pages never reach them, audit 2026-11-18) - if (rq.foreign) - for (const Json& m : body["messages"].items()) - for (const Json& p : m["content"].items()) - if (p["type"].str() == "file" || p["type"].str() == "input_file" || p.dump().find("\"/files/") != std::string::npos) - return rs.send(403, "application/json", err("saved files and chats are only for the server's own page").dump()); + if (reject_foreign_files(rq, body, rs)) return; if (ocr_ && ocr_batch(rq, body, rs)) return; // (several images / PDFs at once: file by file, tools/server_ocr.h) if (ocr_ && ocr_pdf(rq, body, rs)) return; // (an OCR model and a PDF: page by page, tools/server_ocr.h) // (/metrics: in the server, waiting until past claim_slot; after the OCR batches, which call chat() per page: each // page is a request of its own, the batch not one more that would wait for ever, audit 2026-11-12) const zmet::Inflight inflight_m; - { // the web UI's saved files ("file" parts): as text, or as references to the image / audio (server_files.h) - bool any = false; - for (const Json& m : body["messages"].items()) - for (const Json& p : m["content"].items()) any = any || p["type"].str() == "file" || p["type"].str() == "input_file"; - bool tools = false; // (the file tools offered: a long document goes in as its outline) - for (const Json& t : body["tools"].items()) tools = tools || t["function"]["name"].str() == "read_file"; - if (any) body.set("messages", files::expand_files(body["messages"], tools, eng_.ctx)); + chatinput::Prompt input; + try { + input = prepare_chat_input(body); + } catch (const std::exception& e) { + return rs.send(400, "application/json", err(e.what()).dump()); } - // (special tokens written in user and tool contents, the files' text included: plain text, see defuse_contents) - if (!body["__raw_prompt"].is_string()) body.set("messages", defuse_contents(body["messages"])); - // (an OCR model: its own task prompt, tools/server_ocr.h; after the saved files became image parts: the web UI - // sends its images as files) - if (ocr_) body = ocr_request(body); const Json& messages = body["messages"]; - if (!messages.is_array() || messages.size() == 0) return rs.send(400, "application/json", err("messages required").dump()); const std::string folder = prompt_folder(messages); // Pi: the project folder (its system-prompt cache) - Json tools = body["tools"]; - // tool_choice "none": the tools stay in the prompt (it is the same as the turns before, so the prompt cache holds: - // the web UI's last answer after its tool rounds processed the whole chat again without them), and the call's - // open marker is never drawn (no_call_tok, below) + const Json no_tools; + const Json& offered = input.offer_tools ? body["tools"] : no_tools; const bool no_calls = body["tool_choice"].str() == "none"; - int no_call_tok = -1, no_call_tok2 = -1; // (no_call_tok2: Inkling 2's call as text, which parse() takes too) - if (no_calls && tools.is_array() && tools.size()) { - const std::vector o = tok_.encode(gemma_ ? "<|tool_call>" : ink_ ? "<|content_invoke_tool_json|>" : "", true); - if (o.size() == 1) no_call_tok = o[0]; - else tools = Json(); // (not one token: the tools left out, as before) - if (ink_) { - const int t2 = tok_.token("<|content_invoke_tool_text|>"); - if (t2 >= 0) no_call_tok2 = t2; - } - } else if (no_calls) { - tools = Json(); - } + const int no_call_tok = input.no_call_tok, no_call_tok2 = input.no_call_tok2; // tool_choice "required" / a named function: the answer starts with a tool call (to that function) std::string force_tool; bool force_tool_on = false; @@ -77,13 +49,13 @@ std::string fname = tc["function"]["name"].str(tc["name"].str()); // (a name that is not one of the tools: no call to it can pass the constraint, and every token scanned the // whole vocabulary, the engine held, to the end of the context: audit 2026-11-18. Then any tool, as "required") - if (!fname.empty() && tools.is_array()) { + if (!fname.empty() && offered.is_array()) { bool known = false; - for (const Json& t : tools.items()) known = known || t["function"]["name"].str(t["name"].str()) == fname; + for (const Json& t : offered.items()) known = known || t["function"]["name"].str(t["name"].str()) == fname; if (!known) fname.clear(); } // (Inkling 2: not forced yet; its call is a message of its own, src/chat_inkling.h) - if (!ink_ && tools.is_array() && tools.size() && (tc.str() == "required" || !fname.empty() || + if (!ink_ && offered.is_array() && offered.size() && (tc.str() == "required" || !fname.empty() || !tc["function"]["name"].str(tc["name"].str()).empty())) { force_tool_on = true; force_tool = gemma_ ? "<|tool_call>call:" + (fname.empty() ? std::string() : fname + "{") @@ -97,30 +69,19 @@ const std::string ty = rf["type"].str(); if (ty == "json_object") jc = std::make_unique(Json::object(), true); else if (ty == "json_schema") jc = std::make_unique(rf["json_schema"]["schema"].is_object() ? rf["json_schema"]["schema"] : Json::object(), false); - if (jc) tools = Json(); // (structured answers, no tool calls) } // tool calls (Gemma 4 and Qwen formats): while a call is open, only tokens that keep it well formed and fitting // its tool's schema (tools/tool_constraint.h; ARC_TOOL_CONSTRAINT=0 turns it off) std::unique_ptr tcc; { const char* e = getenv("ARC_TOOL_CONSTRAINT"); - if (tools.is_array() && tools.size() && !no_calls && !(e && std::string(e) == "0")) { - if (gemma_) tcc = std::make_unique(tools); - else if (!ink_) tcc = std::make_unique(tools); // (Inkling 2: no constraint yet) + if (input.constrain_tools && offered.is_array() && offered.size() && !no_calls && !(e && std::string(e) == "0")) { + if (gemma_) tcc = std::make_unique(offered); + else if (!ink_) tcc = std::make_unique(offered); // (Inkling 2: no constraint yet) if (tcc && tcc->empty()) tcc.reset(); } } - ChatOptions co; - if (body["enable_thinking"].is_bool()) co.enable_thinking = body["enable_thinking"].as_bool(); - if (body["chat_template_kwargs"]["enable_thinking"].is_bool()) co.enable_thinking = body["chat_template_kwargs"]["enable_thinking"].as_bool(); - const std::string effort = body["reasoning_effort"].str(body["chat_template_kwargs"]["reasoning_effort"].str()); - if (effort == "none" || effort == "minimal" || effort == "off") co.enable_thinking = false; - else if (q4_) co.reasoning_effort = effort; // (Qwen4: render_qwen4 maps the word, high by default) - else if (effort == "low") co.reasoning_effort = "low"; - else if (effort == "medium") co.reasoning_effort = "medium"; - else if (!effort.empty()) co.reasoning_effort = "xhigh"; - // earlier turns keep their reasoning: only where the model's template offers it (Qwen3.6) - co.preserve_thinking = can_preserve_ && body["chat_template_kwargs"]["preserve_thinking"].as_bool(default_preserve_); + const ChatOptions& co = input.options; SamplingParams sp = defaults_; if (body["temperature"].is_number()) sp.temperature = (float)body["temperature"].as_number(); if (body["top_p"].is_number()) sp.top_p = (float)body["top_p"].as_number(); @@ -163,34 +124,8 @@ const int top_lp = (int)body["top_logprobs"].as_clamped(0, 0, 20); const bool usage_in_stream = body["stream_options"]["include_usage"].as_bool(false); - // Gemma 4: an assistant message with tool calls goes in without its reasoning. The template keeps that reasoning - // while the turn's tool rounds go on and drops it once the user writes again, so the next turn's prompt differed - // right before the tool results: a 20K-token result processed again for a one-line question (E4B: 38 s). Without - // it every turn renders the same; a tool round only goes back over the reasoning just generated (rewind) - const Json gmsgs = gemma_ ? gemma_history(messages) : Json(); - const Json& rmsgs = gemma_ ? gmsgs : messages; // (the messages the template renders) - std::string prompt; - const bool raw_prompt = body["__raw_prompt"].is_string(); // (api_compat: the prompt text as it is) - if (raw_prompt) { - tools = Json(); - co.enable_thinking = false; - } - // (Inkling 2: its effort message; thinking off is effort 0 ("none"), else the request's reasoning_effort, a name or - // a number, and none given the template's default 0.9. A name the format does not know is a 400, as there) - Json ink_effort; - if (ink_) { - const Json& re = body["reasoning_effort"].is_null() ? body["chat_template_kwargs"]["reasoning_effort"] : body["reasoning_effort"]; - if (!co.enable_thinking) ink_effort = Json("none"); - else if (re.is_number() || (re.is_string() && !re.as_string().empty())) ink_effort = re; - } - try { - prompt = raw_prompt ? body["__raw_prompt"].str() - : ink_ ? inkling::render(messages, tools, ink_effort) - : jinja_ ? jinja_->render(rmsgs, tools, true, co.enable_thinking) - : render_qwen(messages, tools, co); - } catch (const std::exception& e) { - return rs.send(400, "application/json", err(e.what()).dump()); - } + const Json& tools = input.render_tools ? offered : no_tools; + const std::string& prompt = input.text; // ARC_DUMP_PROMPT=file: every rendered prompt appended to the file (to see where a turn's prompt differs from the // last one, which decides how much of the cache is reused) if (const char* df = getenv("ARC_DUMP_PROMPT")) { @@ -202,128 +137,26 @@ fclose(f); } } - // Same wording and error type as llama-server, so that clients recognize a context overflow (Pi then compacts - // the conversation and retries). The hybrid DeltaNet state cannot drop old tokens, so there is no server-side - // context shift. - auto overflow = [&](size_t n, const char* at_least) { - Json e = Json::object(); - e.set("code", 400); - e.set("message", std::string("the request exceeds the available context size (prompt ") + at_least + std::to_string(n) + - " tokens, context " + std::to_string(eng_.ctx) + " tokens), try increasing it"); - e.set("type", "exceed_context_size_error"); - e.set("n_prompt_tokens", (int)std::min(n, INT_MAX)); - e.set("n_ctx", eng_.ctx); - Json r = Json::object(); - r.set("error", e); - return rs.send(400, "application/json", r.dump()); - }; // (no token holds more than max_token_bytes() bytes of text: a prompt longer than ctx such tokens cannot fit, // refused before the tokenizer allocates for it; every prompt that might fit is tokenized as before) if (const size_t L = tok_.max_token_bytes(); L && prompt.size() / L > (size_t)eng_.ctx) - return overflow(prompt.size() / L, "at least "); - std::vector P = tok_.encode(prompt, true); + return overflow(rs, prompt.size() / L, "at least "); + std::vector P = input.tokens(tok_); // media: the template writes one <|image|> per image part and one <|audio|> per input_audio part; each becomes // <|image> / <|audio> + n embedding rows + / . Images are read non-causally, audio causally. - struct ImgSpan { - size_t start; - int n; - std::shared_ptr> embd; - bool causal = false; - int gw = 0, gh = 0; // Qwen images: grid for the M-RoPE positions - }; std::vector spans; - // the engine lock, taken before the media are encoded: the media cache and the encoders (which share the GPU - // queue with the engine) must not run alongside another request (one thread per connection) std::unique_lock lock(mu_, std::defer_lock); - { - std::vector urls; - std::vector> clips; - try { - for (const Json& m : messages.items()) - for (const Json& part : m["content"].items()) { - const std::string ty = part["type"].str(); - if (ty == "image_url") urls.push_back(part["image_url"].is_string() ? part["image_url"].str() : part["image_url"]["url"].str()); - else if (ty == "image") urls.push_back(part["image"].is_string() ? part["image"].str() : part["image_url"]["url"].str()); - else if (ty == "input_audio" || ty == "audio") { - // OpenAI: {"input_audio": {"data": , "format": "wav" | "mp3" ...}}; a data URL also works - const Json& a = part[ty == "audio" ? "audio" : "input_audio"]; - const std::string d = a.is_string() ? a.str() : a["data"].str(); - std::string f; // (the web UI's saved file: "/files/", tools/server_files.h) - if (files::store().resolve(d, f)) clips.emplace_back(f.begin(), f.end()); - else clips.push_back(d.rfind("data:", 0) == 0 ? img::from_data_url(d) : img::base64_decode(d)); - } - } - } catch (const std::exception& e) { - return rs.send(400, "application/json", err(std::string("media: ") + e.what()).dump()); - } - if (!urls.empty() && (!has_vision() || img_tok_ < 0)) - return rs.send(400, "application/json", err("this model was loaded without an image encoder (mmproj)").dump()); - if (!clips.empty() && (!audio_ || aud_tok_ < 0)) - return rs.send(400, "application/json", err("this model was loaded without an audio encoder (mmproj with audio)").dump()); - if (!urls.empty() || !clips.empty()) { - acquire(lock); - std::vector P2; - size_t ki = 0, ka = 0; - auto fnv = [](const std::vector& bytes) { - uint64_t h = 1469598103934665603ull; // FNV-1a of the file bytes - for (uint8_t b : bytes) h = (h ^ b) * 1099511628211ull; - return h; - }; - try { - for (int t : P) { - const bool is_img = t == img_tok_ && ki < urls.size(), is_aud = t == aud_tok_ && ka < clips.size(); - if (!is_img && !is_aud) { P2.push_back(t); continue; } - std::vector bytes; - if (is_img) { - std::string f; - const std::string& u = urls[ki++]; - bytes = files::store().resolve(u, f) ? std::vector(f.begin(), f.end()) : img::from_data_url(u); - } else { - bytes = std::move(clips[ka++]); - } - const uint64_t h = fnv(bytes) ^ (is_img ? 0 : 0x5bd1e995ull); - auto it = img_cache_.find(h); - if (it == img_cache_.end()) { - const auto t0 = clk::now(); - int n = 0, gw = 0, gh = 0; - std::shared_ptr> e; - if (is_img) { - const ImageRGB im = img::decode(bytes); - e = std::make_shared>(qvision_ ? qvision_->encode(im, n, gw, gh) : vision_->encode(im, n)); - zlog::eprintf("image %dx%d -> %d tokens, encoded in %.0f ms\n", im.w, im.h, n, ms_since(t0)); - } else { - const std::vector s16 = audio::decode_16k(bytes); - e = std::make_shared>(audio_->encode(s16, n)); - zlog::eprintf("audio %.1f s -> %d tokens, decoded and encoded in %.0f ms\n", s16.size() / 16000.0, n, ms_since(t0)); - } - if (img_cache_.size() > 64 || img_cache_bytes_ + e->size() * 4 > (512u << 20)) { - img_cache_.clear(); - img_cache_bytes_ = 0; - } - img_cache_bytes_ += e->size() * 4; - it = img_cache_.emplace(h, MediaEmb{e, gw, gh}).first; - } - const int width = is_img ? (qvision_ ? qvision_->n_out : vision_->out_dim()) : audio_->out_dim(); - const int n = (int)(it->second.e->size() / width); - const int beg = is_img ? img_beg_ : aud_beg_, end = is_img ? img_end_ : aud_end_; - if (beg >= 0) P2.push_back(beg); - // causal: audio, Qwen images, and every token of E2B / E4B (llama.cpp: "always causal"); the 12B's images - // attend to themselves both ways - const bool causal = !is_img || qvision_ != nullptr || eng_.hp.n_ple != 0; - spans.push_back({P2.size(), n, it->second.e, causal, it->second.gw, it->second.gh}); - // placeholder id: identical media (encoded to the same token count) match in the prefix cache - const int ph = -1 - (int)((h ^ ((uint64_t)n * 0x9e3779b97f4a7c15ull)) & 0x3fffffff); - P2.insert(P2.end(), n, ph); - if (end >= 0) P2.push_back(end); - } - } catch (const std::exception& e) { - return rs.send(400, "application/json", err(std::string("media: ") + e.what()).dump()); - } - P.swap(P2); + try { + auto media = chat_media(messages); + if (!media.empty()) { + acquire(lock); // the media cache and encoders share the engine's queue + expand_media(std::move(media), P, &spans); } + } catch (const std::exception& e) { + return rs.send(400, "application/json", err(std::string("media: ") + e.what()).dump()); } if (P.empty()) return rs.send(400, "application/json", err("the prompt is empty (no tokens)").dump()); - if ((int)P.size() + 64 > eng_.ctx) return overflow(P.size(), ""); + if (!prompt_fits(P.size())) return overflow(rs, P.size()); if (max_tokens <= 0 || (int)P.size() + max_tokens > eng_.ctx) max_tokens = eng_.ctx - (int)P.size(); if (!lock.owns_lock()) acquire(lock); diff --git a/tools/server_chat_media.h b/tools/server_chat_media.h new file mode 100644 index 00000000..e89b0c5a --- /dev/null +++ b/tools/server_chat_media.h @@ -0,0 +1,126 @@ +// Media parts of a chat prompt. Included inside class Server. + struct ChatMedia { + std::vector urls; + std::vector> clips; + size_t ki = 0, ka = 0; + bool empty() const { return urls.empty() && clips.empty(); } + // Consume a part only at the placeholder emitted by this model's template. + bool take(int t, int img_tok, int aud_tok, bool& is_img, std::vector& bytes) { + is_img = t == img_tok && ki < urls.size(); + if (!is_img && !(t == aud_tok && ka < clips.size())) return false; + if (is_img) { + std::string f; + const std::string& u = urls[ki++]; + bytes = files::store().resolve(u, f) ? std::vector(f.begin(), f.end()) : img::from_data_url(u); + } else { + bytes = std::move(clips[ka++]); + } + return true; + } + }; + ChatMedia chat_media(const Json& messages) const { + ChatMedia media; + for (const Json& m : messages.items()) + for (const Json& part : m["content"].items()) { + const std::string ty = part["type"].str(); + if (ty == "image_url") media.urls.push_back(part["image_url"].is_string() ? part["image_url"].str() : part["image_url"]["url"].str()); + else if (ty == "image") media.urls.push_back(part["image"].is_string() ? part["image"].str() : part["image_url"]["url"].str()); + else if (ty == "input_audio" || ty == "audio") { + // OpenAI: {"input_audio": {"data": , "format": "wav" | "mp3" ...}}; a data URL also works + const Json& a = part[ty == "audio" ? "audio" : "input_audio"]; + const std::string d = a.is_string() ? a.str() : a["data"].str(); + std::string f; // (the web UI's saved file: "/files/", tools/server_files.h) + if (files::store().resolve(d, f)) media.clips.emplace_back(f.begin(), f.end()); + else media.clips.push_back(d.rfind("data:", 0) == 0 ? img::from_data_url(d) : img::base64_decode(d)); + } + } + if (!media.urls.empty() && (!has_vision() || img_tok_ < 0)) + throw std::runtime_error("this model was loaded without an image encoder (mmproj)"); + if (!media.clips.empty() && !has_audio()) + throw std::runtime_error("this model was loaded without an audio encoder (mmproj with audio)"); + return media; + } + struct ImgSpan { + size_t start; + int n; + std::shared_ptr> embd; + bool causal = false; + int gw = 0, gh = 0; // Qwen images: grid for the M-RoPE positions + }; + + // Both callers plan the decoded media. Generation also encodes it and checks the plan before caching it. + MediaEmb prepare_medium(bool image, const std::vector& bytes, bool encode) { + MediaEmb m; + int actual = 0; + const auto t0 = clk::now(); + if (image) { + const auto im = img::decode(bytes); + int w, h; + m.rows = qvision_ ? qvision_->plan(im.w, im.h, w, h) : vision_->plan(im.w, im.h, w, h); + if (encode) { + m.e = std::make_shared>(qvision_ ? qvision_->encode(im, actual, m.gw, m.gh) : vision_->encode(im, actual)); + zlog::eprintf("image %dx%d -> %d tokens, encoded in %.0f ms\n", im.w, im.h, actual, ms_since(t0)); + } + } else { + const auto samples = audio::decode_16k(bytes); + m.rows = (int)audio_->token_count(samples.size()); + if (encode) { + m.e = std::make_shared>(audio_->encode(samples, actual)); + zlog::eprintf("audio %.1f s -> %d tokens, decoded and encoded in %.0f ms\n", samples.size() / 16000.0, actual, ms_since(t0)); + } + } + if (encode) { + const int width = image ? (qvision_ ? qvision_->n_out : vision_->out_dim()) : audio_->out_dim(); + if (actual != m.rows || m.e->size() != (size_t)m.rows * width) + throw std::runtime_error(std::string(image ? "image" : "audio") + " encoder planned " + std::to_string(m.rows) + + " rows of width " + std::to_string(width) + ", returned " + std::to_string(actual) + + " rows and " + std::to_string(m.e->size()) + " values"); + } + return m; + } + + // With spans, replace placeholders with the actual input positions. Counting visits the same + // positions without allocating embeddings or touching the engine or its media cache. + size_t expand_media(ChatMedia media, std::vector& ids, std::vector* spans = nullptr) { + if (media.empty()) return ids.size(); + size_t count = 0; + std::vector expanded; + auto append = [&](int token, size_t n = 1) { + count += n; + if (spans) expanded.insert(expanded.end(), n, token); + }; + for (int t : ids) { + bool image; + std::vector bytes; + if (!media.take(t, img_tok_, aud_tok_, image, bytes)) { append(t); continue; } + MediaEmb m; + int placeholder = 0; + if (spans) { + uint64_t h = 1469598103934665603ull; + for (uint8_t b : bytes) h = (h ^ b) * 1099511628211ull; + if (!image) h ^= 0x5bd1e995ull; + auto it = img_cache_.find(h); + if (it == img_cache_.end()) { + m = prepare_medium(image, bytes, true); + if (img_cache_.size() > 64 || img_cache_bytes_ + m.e->size() * 4 > (512u << 20)) { + img_cache_.clear(); + img_cache_bytes_ = 0; + } + img_cache_bytes_ += m.e->size() * 4; + img_cache_.emplace(h, m); + } else { + m = it->second; + } + placeholder = -1 - (int)((h ^ ((uint64_t)m.rows * 0x9e3779b97f4a7c15ull)) & 0x3fffffff); + } else { + m = prepare_medium(image, bytes, false); + } + const int beg = image ? img_beg_ : aud_beg_, end = image ? img_end_ : aud_end_; + if (beg >= 0) append(beg); + if (spans) spans->push_back({count, m.rows, m.e, !image || qvision_ != nullptr || eng_.hp.n_ple != 0, m.gw, m.gh}); + append(placeholder, m.rows); + if (end >= 0) append(end); + } + if (spans) ids.swap(expanded); + return count; + } diff --git a/tools/server_ocr.h b/tools/server_ocr.h index b2d98357..7749af6d 100644 --- a/tools/server_ocr.h +++ b/tools/server_ocr.h @@ -48,7 +48,7 @@ static constexpr int kOcrMaxPages = 50; // (a PDF's pages read per request; mor // (read_file). A new file never takes an existing one's place: "name (2).md" then; append (the web UI's "lanjut" // turns): the named file goes on. Every answer ends with the file it went to ("[OCR: ... added to F]" / // "[OCR: saved to F]", F "PATH; in this chat's files as NAME" for a folder of the user's). - bool ocr_pdf(const HttpRequest& rq, const Json& body, HttpResponse& rs) { + bool ocr_pdf(const HttpRequest& rq, const Json& body, HttpResponse& rs, Json* single_input = nullptr) { const Json& msgs = body["messages"]; int last = -1; for (int i = 0; i < (int)msgs.size(); ++i) @@ -114,6 +114,13 @@ static constexpr int kOcrMaxPages = 50; // (a PDF's pages read per request; mor } first = std::max(1, first); const int n = std::min(pages, upto ? upto : first + kOcrMaxPages - 1); + if (single_input) { + if (first != n) return no_single_ocr_prompt(rs); + const std::string url = ocr_page_url(doc, first, err); + if (url.empty()) rs.send(400, "application/json", Server::err("the page could not be rendered: " + err).dump()); + else *single_input = ocr_image_body(url, task); + return true; + } const bool stream = body["stream"].as_bool(false); const std::string id = "chatcmpl-arc" + std::to_string(++counter_); const long long created = (long long)time(nullptr); @@ -158,12 +165,12 @@ static constexpr int kOcrMaxPages = 50; // (a PDF's pages read per request; mor if (!rs.sse_event(chunk(id, created, d, Json()).dump())) return true; sent = piece.size(); } - const std::string png = doc.render(p, 150, err); - if (png.empty()) { + const std::string url = ocr_page_url(doc, p, err); + if (url.empty()) { piece += "[the page could not be rendered: " + err + "]"; } else { std::string text; - if (ocr_image(rq, rs, "data:image/png;base64," + apic::base64_encode(png), task, tally, text)) { + if (ocr_image(rq, rs, url, task, tally, text)) { piece += text; } else { failed = "page " + std::to_string(p) + ": " + text; @@ -490,9 +497,15 @@ static constexpr int kOcrMaxPages = 50; // (a PDF's pages read per request; mor : m.md.string() + (!m.ref.empty() ? "; in the project as " + m.ref : m.md_chat.empty() ? "" : "; in this chat's files as " + m.md_chat.filename().string()); } - // One image read by the model (url: a data URL or /files/) with the task's words, through chat(): its text, or - // false and why. Its tokens and timings go into t. - bool ocr_image(const HttpRequest& rq, HttpResponse& outer, const std::string& image_url, const std::string& task, OcrTally& t, std::string& text) { + static bool no_single_ocr_prompt(HttpResponse& rs) { + rs.send(400, "application/json", err("this OCR workflow has no single chat prompt to count").dump()); + return true; + } + static std::string ocr_page_url(pdfr::Pdf& doc, int page, std::string& err) { + const std::string png = doc.render(page, 150, err); + return png.empty() ? "" : "data:image/png;base64," + apic::base64_encode(png); + } + static Json ocr_image_body(const std::string& image_url, const std::string& task) { Json url = Json::object(), img = Json::object(), txt = Json::object(), content = Json::array(), msg = Json::object(), one = Json::array(), req = Json::object(); url.set("url", image_url); @@ -507,8 +520,12 @@ static constexpr int kOcrMaxPages = 50; // (a PDF's pages read per request; mor one.push(msg); req.set("messages", one); req.set("stream", false); + return req; + } + // One image read by the model, with the task's words, through chat(). + bool ocr_image(const HttpRequest& rq, HttpResponse& outer, const std::string& image_url, const std::string& task, OcrTally& t, std::string& text) { HttpRequest rq2 = rq; - rq2.body = req.dump(); + rq2.body = ocr_image_body(image_url, task).dump(); HttpResponse r2(plat::kNoSocket); int st = 0; std::string out; @@ -543,7 +560,7 @@ static constexpr int kOcrMaxPages = 50; // (a PDF's pages read per request; mor // "ocr_save" {name, folder, append, per_file}: as ocr_pdf's. per_file false: one .md (name, default " and N more.md"), each file under "# NAME" in it; true: one .md per file, ".md" (name not // read), and append goes on with the file in progress, the one the last "added to F" note named. - bool ocr_batch(const HttpRequest& rq, const Json& body, HttpResponse& rs) { + bool ocr_batch(const HttpRequest& rq, const Json& body, HttpResponse& rs, Json* single_input = nullptr) { const Json& msgs = body["messages"]; int last = -1; for (int i = 0; i < (int)msgs.size(); ++i) @@ -644,6 +661,24 @@ static constexpr int kOcrMaxPages = 50; // (a PDF's pages read per request; mor } } const Json& sv = body["ocr_save"]; + auto image_url = [&](Item& it, int page, std::string& why) -> std::string { + if (it.pdf) return ocr_page_url(it.doc, page, why); + if (it.info.id.rfind("project:", 0) != 0) return "/files/" + it.info.id; + std::string bytes; + std::error_code ec; + if (std::filesystem::file_size(std::filesystem::path(it.info.path), ec) > kOcrMaxImageBytes || ec) why = "the image is larger than 64 MB"; + else if (files::Store::read(it.info.path, bytes)) return "data:" + ocr_image_mime(it.info.name) + ";base64," + apic::base64_encode(bytes); + else why = "the file cannot be read"; + return ""; + }; + if (single_input) { + if (fk != nf - 1 || fp != items[fk].pages) return no_single_ocr_prompt(rs); + std::string why = items[fk].err; + const std::string url = why.empty() ? image_url(items[fk], fp, why) : ""; + if (url.empty()) rs.send(400, "application/json", err("cannot prepare OCR input: " + why).dump()); + else *single_input = ocr_image_body(url, task); + return true; + } const bool saving = sv.as_bool(false) || sv.is_object(), per_file = sv["per_file"].as_bool(false); OcrDirs dirs; OcrMd md; // (the .md written now: the merged one, or the file in progress's) @@ -736,19 +771,10 @@ static constexpr int kOcrMaxPages = 50; // (a PDF's pages read per request; mor } std::string text, err; bool ok = false; - if (it.pdf) { - const std::string png = it.doc.render(p, 150, err); - if (png.empty()) text = "[the page could not be rendered: " + err + "]", ok = true; - else ok = ocr_image(rq, rs, "data:image/png;base64," + apic::base64_encode(png), task, tally, text); - } else if (it.info.id.rfind("project:", 0) == 0) { // (a project's file: its bytes, it has no /files/ address) - std::string bytes; - std::error_code ec; - if (std::filesystem::file_size(std::filesystem::path(it.info.path), ec) > kOcrMaxImageBytes || ec) text = "the image is larger than 64 MB"; - else if (files::Store::read(it.info.path, bytes)) ok = ocr_image(rq, rs, "data:" + ocr_image_mime(it.info.name) + ";base64," + apic::base64_encode(bytes), task, tally, text); - else text = "the file cannot be read"; - } else { - ok = ocr_image(rq, rs, "/files/" + it.info.id, task, tally, text); - } + const std::string url = image_url(it, p, err); + if (!url.empty()) ok = ocr_image(rq, rs, url, task, tally, text); + else if (it.pdf) text = "[the page could not be rendered: " + err + "]", ok = true; + else text = err; if (!ok) { failed = "file " + std::to_string(k + 1) + (it.pdf ? ", page " + std::to_string(p) : "") + ": " + text; text = "[" + failed + "]"; diff --git a/tools/server_whisper.h b/tools/server_whisper.h index a9303254..3127dd14 100644 --- a/tools/server_whisper.h +++ b/tools/server_whisper.h @@ -503,6 +503,11 @@ class Service { static constexpr size_t kInlineChars = 12000; // (what writes chat audio; the atomic snapshot: asr_id changes under engines_mu_ while a chat thread asks) std::string clip_model() const { return asr_loaded() ? "Qwen3-ASR" : "Whisper"; } + bool needs_transcript(const Json& body, bool hears) const { + const std::string speech = body["speech"].str(); + if (speech.empty() && !has_whisper() && !asr_loaded()) return false; + return speech == "whisper" || (speech != "model" && !hears); + } static bool has_audio_parts(const Json& body) { for (const Json& m : body["messages"].items()) for (const Json& p : m["content"].items()) { diff --git a/zero/audio_gemma4a.h b/zero/audio_gemma4a.h index c54f1876..fae1fd79 100644 --- a/zero/audio_gemma4a.h +++ b/zero/audio_gemma4a.h @@ -40,6 +40,17 @@ class AudioGemma4A : public GemmaAudioEncoder { build_mel_filters(); } + static constexpr size_t clip_samples = 30 * 16000; + static constexpr int mel_window = 320, mel_hop = 160; + static int mel_frames(size_t samples) { + return std::max(1, (int)(((int64_t)samples + mel_window / 2 - (mel_window + 1)) / mel_hop + 1)); + } + static int subsampled(int length) { return (length - 1) / 2 + 1; } + size_t token_count(size_t samples) const override { + auto rows = [](size_t n) { return subsampled(subsampled(mel_frames(n))); }; + return samples / clip_samples * rows(clip_samples) + + (samples % clip_samples ? rows(samples % clip_samples) : 0); + } int out_dim() const override { return n_out; } // GPU memory of the encoder (weights, the relative-position projections, buffers for a 30-second clip). @@ -56,7 +67,7 @@ class AudioGemma4A : public GemmaAudioEncoder { const auto t0 = std::chrono::steady_clock::now(); std::vector out; n_tok = 0; - const size_t clip = 30 * 16000; + const size_t clip = clip_samples; for (size_t off = 0; off < s.size(); off += clip) { int n = 0; const std::vector e = encode_clip(s.data() + off, std::min(clip, s.size() - off), n); @@ -148,10 +159,8 @@ class AudioGemma4A : public GemmaAudioEncoder { // log-mel frames [T][128] of one clip (llama.cpp's semicausal padding and frame count) std::vector mel(const float* x, size_t n, int& T) const { - const int win = 320, fft = 512, hop = 160, nb = 257, pad_left = win / 2; - const int64_t n_left = (int64_t)n + pad_left; - T = (int)((n_left - (win + 1)) / hop + 1); - if (T < 1) T = 1; + const int win = mel_window, fft = 512, hop = mel_hop, nb = 257, pad_left = win / 2; + T = mel_frames(n); const int64_t need = (int64_t)(T - 1) * hop + fft; const int64_t total = std::max(need - (int64_t)n, pad_left) + (int64_t)n; std::vector p((size_t)std::max(total, need), 0.0f); @@ -197,8 +206,8 @@ class AudioGemma4A : public GemmaAudioEncoder { // in [Ci][T][F] -> out [Co][T'][F']; w [Co][Ci][3 (time)][3 (freq)] static std::vector conv_ln_relu(const std::vector& in, int Ci, int T, int F, const std::vector& w, const std::vector& nw, int Co, int& To, int& Fo) { - To = (T - 1) / 2 + 1; - Fo = (F - 1) / 2 + 1; + To = subsampled(T); + Fo = subsampled(F); std::vector out((size_t)Co * To * Fo); #pragma omp parallel for for (int t = 0; t < To; ++t) { diff --git a/zero/audio_qwen3a.h b/zero/audio_qwen3a.h index 17684dac..d1f4208c 100644 --- a/zero/audio_qwen3a.h +++ b/zero/audio_qwen3a.h @@ -58,6 +58,7 @@ class AudioQwen3A : public GemmaAudioEncoder { if (F % kChunk) t += chunk_tokens(F % kChunk); return t; } + size_t token_count(size_t samples) const override { return tokens(samples); } static int chunk_tokens(int L) { for (int i = 0; i < 3; ++i) L = (L - 1) / 2 + 1; return L; diff --git a/zero/vision_gemma4v.h b/zero/vision_gemma4v.h index 67e61b20..d827a387 100644 --- a/zero/vision_gemma4v.h +++ b/zero/vision_gemma4v.h @@ -80,7 +80,7 @@ class VisionGemma4V : public GemmaImageEncoder { } // Tokens an image of this size becomes, and the resized size (multiples of 48 pixels). - int plan(int w, int h, int& W, int& H) const { + int plan(int w, int h, int& W, int& H) const override { const int unit = patch * pool; const int64_t px = (int64_t)unit * unit; img::fit_size(w, h, unit, (int64_t)min_tokens * px, (int64_t)max_tokens * px, W, H);