Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions docs/server.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
2 changes: 1 addition & 1 deletion setup.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
5 changes: 3 additions & 2 deletions src/audio_gemma4.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<float> encode(const std::vector<float>& s, int& n_tok) = 0;
};

Expand All @@ -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<float> encode(const std::vector<float>& s, int& n_tok) override {
n_tok = tokens(s.size());
n_tok = (int)token_count(s.size());
std::vector<float> out((size_t)n_tok * n_out);
#pragma omp parallel for
for (int t = 0; t < n_tok; ++t) {
Expand Down
4 changes: 2 additions & 2 deletions src/http.h
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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"};
Expand Down
3 changes: 2 additions & 1 deletion src/vision_gemma4.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<float> encode(const ImageRGB& im, int& n_tok) = 0;
};

Expand Down Expand Up @@ -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
Expand Down
87 changes: 85 additions & 2 deletions tests/run_tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand Down Expand Up @@ -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++) {
Expand All @@ -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)
Expand All @@ -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 }
}
}

Expand Down
55 changes: 55 additions & 0 deletions tests/test_chat_input.cpp
Original file line number Diff line number Diff line change
@@ -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 <fstream>
#include <iostream>
#include <iterator>

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<char>(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;
}
25 changes: 25 additions & 0 deletions tests/test_ocr_input.sh
Original file line number Diff line number Diff line change
@@ -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'
Loading