Skip to content

Latest commit

 

History

History
1292 lines (1112 loc) · 100 KB

server.md

File metadata and controls

1292 lines (1112 loc) · 100 KB

amql-server — HTTP endpoints for AMQL containers

amql-server loads one or more VINDEX3 containers and serves each on the endpoints its recorded facts say it can answer. Nothing is guessed from a model's name: a container that cannot serve an endpoint is not offered on it, and the startup log says why.

dotnet build -c Release src/Amql.Server
./bin/win-x64/Release/amql-server --model von=<von-container> --model chat=<qwen-container> --model emb=<embedding-container> \
                          --urls http://127.0.0.1:8000 [--api-key KEY] [--max-tokens N] [--no-warm] \
                          [--adapter [id=]<dir>[,<dir>…]] [--think] [--temperature T] [--top-p P] [--top-k K] \
                          [--vote K] [--vote-temperature T] \
                          [--config <models.json>] [--state <file>] [--cluster-listen IP:PORT] [--cluster-name NAME] [--max-ram GB] [--gpu-memory GB] [--cpu] [--no-batch] [--batch-bf16]

AMQL Studio starts and stops the server with the models you choose and shows what it is doing; everything below applies whichever way it is started.

Container Endpoints
Von decision model (ModernBERT + option-marker head) POST /v1/decisions, POST /v1/systemone (OpenJEV's path), POST /api/v1/decisions (jevai.org's { code, message, data } envelope)
Embedding container (convert-to-embedding, an embedding surface) POST /v1/embeddings
Generative decoder with a chat template POST /v1/chat/completions, POST /v1/responses, streaming (SSE) or not, with the reasoning and tools its template writes
Every model GET /v1/models, GET /v1/models/{id} (with capabilities, and for chat models context_length, tools, thinking, adapters and defaults), GET /health
The server itself GET /amql/status: what it is doing (see Status)
Management PUT/DELETE /v1/models/{id}, POST /v1/models/{id}/load, /unload (see Models at run time); the cluster routes (see Clusters)

A sequence classifier or a bare encoder loads but is offered no endpoint (the log notes amql-cli classify).

Several models

One server serves any number of models, each under its own id, and a request picks one with model. Give them as --model id=<dir> (repeatable), or in a --config JSON file, where each model also gets its own adapters and defaults. Paths are relative to the file, comments and trailing commas are allowed, and an unknown setting is refused at startup:

{
  "models": [
    { "id": "qwen-think", "path": "qwen3.5-0.8b", "adapters": ["adapters/stop-circling"],
      "think": true, "temperature": 0 },
    { "id": "qwen", "path": "qwen3.5-0.8b", "think": false, "max_tokens": 1024 }
  ]
}

"kv_dir" gives a model its own folder for paged-out prompt state (see Concurrency). A model's own settings (think, max_tokens, temperature, top_p, top_k) come first, then the server's flags, then the built-in defaults; a request's own fields override all of them. A model that thinks by default gets 4096 tokens unless something says otherwise. The same container may be served under several ids, here with and without adapters; each loads its own copy. GET /v1/models lists every model with what it serves and the defaults it applies, and GET /v1/models/{id} returns one (404 model_not_found otherwise).

Routing, concurrency, auth

  • A request's model names a loaded model by id (--model id=<dir>, default: the directory name). An unknown id is a 404 model_not_found; a model that does not serve the endpoint is a 400 model_not_supported. Omitting model is allowed when exactly one loaded model serves the endpoint. For decisions, model names TypeSafe's hosted Jev (openjev, typesafe-ai/jev), so any unmatched name falls back to the sole Von model; the response reports the version actually served.
  • A chat model on the GPU engine batches its requests (see Concurrency). Anything else serves one request at a time per model; on the CPU, different models run in parallel, and with CUDA on the managed GPU path takes turns across all models, because its kernels stage through process-wide device buffers and two sessions on the GPU at once would overwrite each other's activations. Generation runs off the request thread, streams through a channel, and stops at the next token when the client disconnects, streamed or not, a reply regenerated by an agent rule and a vote's answers included. A request whose client went while it waited is not started. A prompt being read is given up between slices of a long prompt in a batch; a prompt read in one piece (a model served one request at a time, or a contrast's second sequence) is read whole first.
  • --api-key (or AMQL_API_KEY) requires Authorization: Bearer <key> on /v1/*, /api/* and /amql/*; /health is open. Without a key the server logs that it is unauthenticated — bind it to loopback.
  • Weights are warmed at startup (one short forward pass per model) so the first request does not pay for widening them; --no-warm skips that.

Memory and device

  • --max-ram GB is the RAM the process aims to stay under. It selects the lean working set, as amql-cli --max-ram does, unless AMQL_WEIGHTS chose a mode: weights stream through a cache sized to fit. That is slower, but it serves models larger than memory.
  • --gpu-memory GB caps the GPU memory the weights may take. The rest stay on the host, and 0 keeps every weight there. Without it the loader takes the device's free memory, less a margin.
  • --cpu serves on the CPU even when a GPU is available.
  • The GPU engine's KV cache is FP16 by default (--kv-format fp16): half f32's memory (32 KiB a token on Qwen 3.5 4B), a little faster decode at long contexts, and on the 4B no measurable difference from f32 (perplexity 10.325 against 10.326, the same top token at all 8,192 positions). Paged-out files are half the size too. --kv-format f32 (or AMQL_KV_FORMAT=f32) keeps the values as computed.
  • --max-context N (1M, 512K, a token count; "max_context" per model in --config) serves a model at a context length other than its own. A conversation that fits the trained length runs exactly as before; one that will go past it runs extended rotary frequencies (--rope-extend). Past 256K, use --kv-format nvfp4 and a --kv-gpu-budget that holds the state (about 11 GB at 1M on Qwen 3.5 4B), or it is released after each reply. Reading 1M tokens takes about half an hour. See Running a model past its trained context.
  • --kv-format nvfp4 stores the GPU engine's KV cache as NVFP4: ~7x less memory a token on Qwen 3.5 4B (592 bytes a position instead of 4,096), faster decode at long contexts, and paged-out files 7x smaller. Replies differ slightly from f32 KV's (perplexity +0.4%, KL 0.008 on the 4B). See The KV cache. With it, each conversation's system prompt, tools and first user message stay out of the 4-bit rounding (--kv-exact-prefix auto, the default; N tokens, or 0 for none), so the instructions every later token reads keep their precision (at most 16,384 tokens of them, so a document as the first message does not fill the GPU). They are kept at FP16 by default: half f32's memory, and on the 4B no measurable difference from f32 (KL under 0.00005, the same top token at all 8,192 positions). --kv-exact-format f32 keeps them at f32, bit for bit an f32 cache's.

Status

GET /amql/status reports what the server is doing, for a monitor to poll. AMQL Studio's Monitor reads it once a second. It returns:

  • process: pid, working set, private bytes, managed heap, CPU seconds, and whether the GPU is in use.
  • totals: requests and failures since start, and requests and completion tokens over the last minute.
  • models: for each model, its capabilities, the requests in flight, requests, errors, prompt and completion tokens, mean decode tokens/s, last use, context length, adapters and load notes.
  • active and recent (the newest 50 of 200 kept): each request's path, model, status, prompt and completion tokens (streamed so far for an active one), seconds, ttft_seconds (time to first token, from when generation starts), decode_tps (tokens after the first over the time after it) and finish reason.

Health checks, /v1/models and status polls are left out of the counts and lists. The endpoint needs the API key when one is set. Each model also reports its state (see below), and error when it failed.

The host

GET /amql/system reports the machine the server runs on, for a monitor on another machine (AMQL Studio's remote servers), which cannot run nvidia-smi there itself: host, os, architecture, processors, cpu_percent (the whole host, measured between two calls: null on the first), memory (total_bytes, available_bytes), gpus (each GPU nvidia-smi lists: index, name, memory_total_bytes, memory_used_bytes, utilization_percent, temperature_c, power_watts, and unified for a GPU that shares the system's memory, whose figures are then the machine's), process (pid, working_set_bytes, cpu_seconds, gpu_bytes where the driver reports memory per process, not under WDDM), uptime_seconds and, with a model store, store (path, free_bytes). nvidia-smi runs at most once every two seconds whatever the number of callers; without it gpus is empty. The endpoint needs the API key when one is set.

The model store

--model-store DIR (or AMQL_MODEL_STORE) gives the server a folder of containers that another machine can list, send to and delete from over HTTP, so a server can be given a model without a share or a copy by hand. AMQL Studio's Send to remote servers uses it. Without a store these routes answer 501 no_model_store. They change the host's disk, so they follow the model routes' rule: the API key when one is set and, with none, callers on this machine only (403 management_needs_api_key).

Route Body Does
GET /amql/containers {store, free_bytes, data: [{name, path, bytes, files, models}], incoming: [{name, bytes, received}]}; models are the ids that serve each container
POST /amql/containers/{name}/upload {"files": [{"path", "bytes"}, …], "replace"?: false} begins an upload, or resumes the same one (the same manifest); answers each file's received bytes. 409 container_exists without replace; 507 insufficient_storage when the disk lacks the room left to send plus 1 GiB
PUT /amql/containers/{name}/files?path=&offset= the bytes writes a piece of a file from offset (the file is cut there first, so a piece sent again replaces itself); 409 upload_gap past the file's end; answers received
POST /amql/containers/{name}/commit {"files": [{"path", "sha256"}, …], "replace"?: false} checks each file's size and SHA-256 (reading every byte), then moves the folder into the store: 201 {name, path, bytes, files}. A file that differs is discarded (422 upload_corrupt) and the upload resumes without it
DELETE /amql/containers/{name}/upload drops an upload in progress
DELETE /amql/containers/{name} deletes a container; 409 container_in_use while a model's path is it

A name is one folder name (letters, digits, ., _, -, +, not starting with .); a file's path is relative and /-separated, with no .., drive or root (400 otherwise). Uploads in progress are kept under .incoming in the store, so one broken off by a dropped connection or a restart resumes where it stopped. Replacing a container that a model serves is refused; remove the model first.

As a cluster node, a server with a store looks for a coordinator's container there by its folder name when the coordinator's path does not exist on this host. A container sent to every node of a cluster under one name is therefore found by each (the join still checks that each node's copy is the coordinator's).

Models at run time

The models a server lists can change while it runs. --model and --config fill the list at start and load each model then, in order, exactly as before (a model that fails to load there stops the start, exit 1, except a distributed one, which waits for its nodes: see Clusters); the routes below change the same list, and --state <file> keeps those changes across restarts (see Settings that survive a restart).

Route Body Answer
PUT /v1/models/{id} a --config model entry (path required, id optional and equal to the route's; adapters, kv_dir, max_context, format, defaults, cluster), and "load": true to load it at once the model as GET /v1/models/{id} gives it; 201 added, 200 replaced
DELETE /v1/models/{id} {"id", "object": "model", "deleted": true}
POST /v1/models/{id}/load the model, loaded; 503 model_load_failed with the reason
POST /v1/models/{id}/unload optional {"if_idle": true} the model, unloaded; 409 model_busy with if_idle while requests are in flight. A distributed model is no longer wanted (no more attempts to form it)

Relative paths in a PUT body are taken from the server's working directory. PUT on a listed id replaces its settings: a loaded model is unloaded (after its requests in flight) and the next load uses the new ones.

GET /v1/models and GET /v1/models/{id} give each model's state and in_flight (requests holding it), error when it failed, and cluster when it has a distribution (see Clusters):

  • unloaded: listed, nothing held. The next request that names it, or POST …/load, loads it.
  • loading: its engines are being built (and its cluster formed). Every request for it waits for this one load; none starts a second.
  • loaded: serving.
  • unloading: it takes no new requests and is freed when those in flight have finished.
  • failed: the last load of a model without a distribution failed; error says why. The next request tries the load again.
  • waiting: a distributed model that is wanted but not formed (its nodes cannot be reached, refuse, or lack room; or its cluster ended). The server tries again in the background; a request gets 503 model_waiting_for_cluster at once, with Retry-After and the reason (see Clusters).

An unloaded model reports what it served when it was last loaded; one never loaded yet reports no capabilities, so a request that leaves model out is routed only among models whose capabilities are known (start models always are). A request that names an unloaded model loads it and is then served; it waits for the load (warming included). If it waited on a load that failed it gets 503 model_load_failed.

Unloading with requests in flight. Unloading never frees an engine a request is using. A request holds its model from routing until its response has ended (streamed replies included); an unload marks the model unloading, so no new request reaches its engines, and frees them once the last hold is released. The POST returns then. A request that arrives meanwhile waits for the unload to finish and then loads the model again: an explicit unload is not a ban, DELETE is. With {"if_idle": true} an unload is refused instead (409) while any request is in flight.

What is freed. The batch thread is stopped first (it owns the engine), then the generator's session and its device engine (weights, KV cache, graphs), the embedder's session, the adapters, the KV page store (kept state is written to disk first, as at shutdown), the operand store and the container. If the batch thread does not stop within 10 s its engine is left allocated and the log says so, since freeing it under a running step would crash. Von decision and classifier engines hold no device memory of their own and go with the container. On an RTX 5090 it does: a distributed Qwen 3.5 4B unloaded and loaded four times left the card at 7,002-7,004 MiB each time it was unloaded and 16,016 MiB each time it was loaded (the end-to-end run in Tensor parallelism). A part that fails to free (an engine whose cluster has ended) no longer keeps the rest: the container and store are freed anyway.

Authorisation. These routes, and every route below that changes something, need the API key when one is set, as every /v1 route does. With no key set they answer only callers on this machine (loopback); others get 403 management_needs_api_key. A reverse proxy on the same machine counts as loopback: put a key on a server that one forwards to. AMQL Manager forwards only its own list of inference paths, none of these.

Clusters

A model can be spread over the GPUs of several hosts, the design in Tensor parallelism. Clustering is a property of a model at run time: each model has a distribution (its node set) or none, and loads through the cluster when it has one, on this host alone when not. Models with different node sets and local models live side by side.

The engine. On a host with a CUDA device the backend is the tensor-parallel engine (TpClusterBackend over TpCluster and TpNode, Tensor parallelism). Without one (--cpu, no device, no native library) it is NoClusterBackend: every route in this section answers 501 cluster_not_available with the reason, --cluster-listen and a model's "cluster" in --config stop the start with that error, and the server behaves exactly as before.

What a distributed model does not do. It is a chat model served by the batch scheduler like a local one (continuous batching, prompt prefixes kept and rewound, fork-and-vote, contrast, Entail adapters, tools, constraints, memory packs, --kv-format, prompt state paged to disk, and speculative decoding when the model has a drafter), with these exceptions, each also listed under distributed.not_supported in GET /v1/models/{id} (with "images": false):

  • speculative decoding is served as on a local model: a reply running alone drafts and verifies, batched replies step. The drafter (an MTP layer, or one attached) runs whole on the coordinator, which plans room for it; GET /v1/models/{id} reports "speculation": true when it runs (false without a drafter or with AMQL_MTP_DRAFTS=0), and the load notes say so. See Tensor parallelism for what it costs on a cluster;
  • no images: the vision tower does not run across nodes (the model loads, reading text);
  • not served a request at a time: with --no-batch, or an adapter that cannot run once per request, the load fails with the reason (a request held for its whole length would hold the device lock across link waits);
  • embeddings, classification and decisions models do not distribute (the load fails with the reason).

A model's distribution

// PUT /v1/models/{id}/cluster, or "cluster" in a --config model entry
{
  "nodes": ["10.0.0.2:7100", { "address": "10.0.0.3:7100", "capacity": "12GiB" }],
  "capacity": "8GiB",      // what this host (the coordinator) gives the model; default: its own default
  "context": 32768,        // tokens of KV cache to plan for; default: the model's context
  "key_name": "lab",       // one of this host's keys; or "key": "<secret>", the distribution's own
  "load": true             // PUT only: load now
}

Sizes are bytes or text ("12GiB", "512MB"; GB and GiB are both 2^30). A node's capacity is what it gives this model; left out, the node gives its default (its free device memory at the join, less a reserve, or its --cluster-capacity).

  • PUT /v1/models/{id}/cluster sets it; a loaded model is unloaded (after its requests) so the next load forms the cluster. Answers as GET.
  • GET /v1/models/{id}/cluster: model, state, error, distribution (the nodes, capacities, context, which key: "own", or the key's name, never the secret; formed, and each node's state, bytes_held and capacity while formed), and while formed plan (the shard plan as JSON) and plan_text. 404 no_distribution when the model has none.
  • DELETE /v1/models/{id}/cluster removes it: the model is unloaded (its shards released on every node) and loads on this host alone next time.

At load the coordinator forms the cluster (connects, proves the key, agrees the container and the shard plan, loads every node's shard), then builds the model over it as over a local engine: tokenizer, template, adapters and batch scheduler as usual. Unloading, deleting the model or removing its distribution releases the shards on every node.

Desired state. A distributed model that was asked to load (at start, POST …/load, "load": true, a request) stays wanted until it is unloaded (POST …/unload), deleted, or its distribution removed; the server keeps trying to bring it to that state, so a cluster survives being started in any order and a node being restarted with no one calling the API.

  • It never stops the start. If its nodes cannot be reached, refuse, or lack room (at start or at a load), the model goes to waiting with the reason and the server serves everything else.
  • Retry. While wanted and not formed it is tried again in the background: 1 s, doubling to 30 s, ±20% jitter. Each attempt first probes the nodes (as POST /v1/cluster/probe does) and forms only when every node is reachable and accepts; a change in the nodes' reachability, and a change in the reason, is logged once, not at every attempt.
  • A request for a waiting model gets 503 model_waiting_for_cluster at once, with Retry-After (seconds to the next attempt) and the reason; it does not block for the retry. POST …/load on a waiting model tries now and waits for that attempt.
  • A cluster that ends on its own (a link drops, a node fails or restarts, a member leaves): the requests in flight fail with the engine's error ("node 1 (10.0.0.2:7100): the link dropped …"), every shard it can reach is freed, and the model goes back to waiting; the retry forms it again when every node is back. No request is needed. The coordinator watches its links, so a node that goes while the model is idle is noticed within a second.
  • Refusals that cannot heal by waiting (another build, a container that differs or is missing, a key the node does not hold, no key on this host, a model that cannot batch) are retried at the 30 s rate and reported with "refused": true, since an operator may fix the node; they never stop the server.
  • Explicit actions end the wanting: unload, delete, or removing the distribution (DELETE …/cluster). Setting another distribution (PUT …/cluster) on a wanted model forms it again over the new nodes, in the background.
  • POST /v1/models/{id}/cluster/retry tries now (and makes the model wanted).

A restarted node holds nothing and needs only its start settings (--cluster-listen, its key): the coordinator's retry joins it again. A restarted coordinator comes back with its models (from --config, or its state file) and forms them again; a node that still holds a membership for the same model from the coordinator's previous life frees that shard before loading the new one, rather than waiting out the 60 s silence. "The same coordinator and model" is all of: the coordinator's lineage (--cluster-name, by default the machine's name and --urls), the model's id, the key it proved (by the node's name for it), and the address its link comes from as the node's socket sees it (not as the coordinator names itself). A coordinator elsewhere, even with the key, cannot evict another's membership by naming its lineage: its address differs. Two servers on one machine must not share a --cluster-name.

What every node must share. Beyond the key and the container (hashes of index.json and the system graph), the join carries and checks: the AMQL build (a node of another build refuses, naming both), the model as it runs (the system graph after the context extension, which the coordinator sends: a node runs the coordinator's max_context, whatever its own --max-context says), the settings that change a node's arithmetic (--batch-bf16's AMQE_GEMM_FROM, AMQE_ATTN_ROWS, AMQL_RESIDENT_BF16, AMQL_GPU_FORMAT and the like: a difference is refused, naming each), the shard plan (KV format and planned context included) and a weight patch's hash. The planner counts the bytes a tensor takes on the device (an FP8 or patched tensor as f32).

Adapters. A model's Entail adapters run beside it on the coordinator, over its tokens and logits, as for a local model; nothing of them goes to the nodes. A distributed model supports them, batched per request as usual. (They are not weight patches: amql-server applies none. A weight patch on a distributed model is amql-cli generate --tp … --patch, sent to every node at the join; see Tensor parallelism.)

This host as a node

  • --cluster-listen IP:PORT opens the node endpoint, so other hosts' coordinators can join this one. Off by default: without it the server opens no cluster port (it can still coordinate its own models).
  • --cluster-capacity GB: what this node gives a cluster that does not say.
  • A node accepts a join only when the coordinator proves one of its keys. --cluster-key KEY or AMQL_CLUSTER_KEY sets the key named default; PUT /v1/cluster/key {"key": "<secret>", "name"?: "lab"} sets one at run time and DELETE /v1/cluster/key[?name=lab] clears one (or all). The key routes answer only callers on this machine, whatever the API key. With no key set every join is refused. Named keys let two groups overlap on a node without trusting each other; a distribution names the one it uses (key_name), gives its own (key), or uses default.
  • Keys never appear in an answer or a log line: reports name them, request bodies on these routes are never written to AMQL_SERVER_DUMP, and a body that is not JSON is refused without quoting it.
  • GET /v1/cluster: listening (the node endpoint, or null), keys (names only), coordinating (each model with a distribution, as GET /v1/models/{id}/cluster) and memberships (each cluster this host holds a shard of: id, model, container, coordinator, bytes_held, capacity, key (name), since).
  • DELETE /v1/cluster/memberships/{id} leaves one: its shard is freed here and that cluster ends (its coordinator puts the model back to waiting, as above, and its retry may join this host again while the model is wanted). A link that drops or a coordinator that goes releases a membership after the backend's timeout (60 s of silence), or at once when the same coordinator joins again after a restart.

Memberships and this host's own models. Being a member never blocks the host's own models; only memory is shared. When a join needs room the backend asks the server to unload idle local models, least recently used first, one at a time until its device has the room: never a model with a request in flight, never a distributed one. They stay listed and load again on their next request. A join that still does not fit is refused with the numbers.

The device gate. On a CUDA build, models that do not batch take turns on the device through one process-wide lock (ModelHost.DeviceGate): a request holds it for its whole length. A batching model's scheduler holds it around each device call (a step, a prefill, a mark, a rewind, a fork…), so models interleave a step at a time. Nothing else takes it: loads, warm-up, unloads and sequence releases run without it, for local and distributed models alike. That is unchanged for local models. With clusters:

  • the scheduler takes the lock through ModelHost.DeviceTurns (a TpDeviceGate over the same semaphore), which records which thread holds it;
  • a distributed engine lets the lock go around every wait on a link (an operator's partial, a worker's acknowledgement, the links' own lock while the heartbeat has them) and takes it back after, when the waiting thread is the one holding it; the device work between waits is done under it;
  • a member's shard work takes the lock around each operation it runs, and lets it go while it waits for an operator's input.

So the lock is never held while a link is waited on: two hosts that each coordinate a model the other is a member of would otherwise each hold their lock waiting for the other's shard. ServerClusterTests runs exactly that, in one process (both servers share the one lock, the harder case): with the release removed it deadlocks (the test times out after 3 minutes); with it, every request finishes. Holding the lock for a whole request is why a distributed model is never served a request at a time. A model's device work that runs without the lock (its load, its warm-up) runs beside other models' as it always has.

A model's cluster state

GET /v1/models/{id} (and each entry of GET /v1/models) gives a distributed model's cluster, one shape in both: the distribution (nodes, capacity, context, key as "own" or a name, never the secret; formed) and where it is. node_states (with bytes_held, the coordinator first, while formed) is still given but deprecated: read nodes[].

Field
state forming (an attempt under way), ready (formed and serving), waiting; when the model is not wanted (explicitly unloaded, or never loaded), unloaded; also unloading while it goes
attempts attempts since it last began waiting (while ready: the attempts it took)
next_attempt_in_s seconds to the next attempt while waiting; null otherwise
last_error why the last attempt failed or why the cluster ended; null once formed
since when the cluster's current state began (ISO 8601, UTC)
refused the last failure cannot heal by waiting (retried at the 30 s rate)
nodes[] each other node, in the distribution's order: address, node (its number in the cluster; the coordinator is 0), capacity (the distribution's, else what it offered or was planned), state (ready, lost, unreachable, refused, failed; null before anything is known), error, bytes (held while formed, else null)
// GET /v1/models/big  (a model waiting for one of its nodes)
{
  "id": "big", "object": "model", "state": "waiting", "in_flight": 0,
  "error": "10.0.0.3:7100 cannot be reached: cannot connect: No connection could be made …",
  "cluster": {
    "nodes": [
      { "address": "10.0.0.2:7100", "capacity": 13421772800, "node": 1, "state": "ready", "error": null, "bytes": null },
      { "address": "10.0.0.3:7100", "capacity": 12884901888, "node": 2, "state": "unreachable", "error": "cannot connect: …", "bytes": null }
    ],
    "capacity": 8589934592, "context": 32768, "key": "default",
    "state": "waiting", "attempts": 4, "next_attempt_in_s": 6.3,
    "last_error": "10.0.0.3:7100 cannot be reached: cannot connect: …",
    "since": "2026-12-02T09:14:03.1200000+00:00", "refused": false, "formed": false
  }
}

A request for it:

HTTP/1.1 503 Service Unavailable
Retry-After: 7

{"error": {"message": "the model 'big' is waiting for its cluster: 10.0.0.3:7100 cannot be reached: …",
           "type": "server_error", "param": null, "code": "model_waiting_for_cluster"}}

Cluster routes

Route Body Answer
GET /v1/models/{id}/cluster the distribution and its state (above), the plan while formed
PUT /v1/models/{id}/cluster a distribution, "load"? as GET
DELETE /v1/models/{id}/cluster the model, now local
POST /v1/models/{id}/cluster/retry 202 with the model's cluster object as it is now; the attempt runs in the background (poll GET /v1/models/{id})
POST /v1/models/{id}/cluster/plan a distribution (none: the model's own) the plan it would get and each node's probe; changes nothing
POST /v1/cluster/plan {"container": "<folder>", …a distribution} the same for a container the server does not list; adds nothing to the server
POST /v1/cluster/probe {"nodes": [...], "key_name"?, "key"?, "container"?} each node, without joining it
GET /v1/cluster this host: listening, keys (names), coordinating, memberships
DELETE /v1/cluster/memberships/{id} leaves one
PUT /v1/cluster/key {"key", "name"?} sets a key (callers on this machine only, whatever the API key)
DELETE /v1/cluster/key[?name=lab] clears one key, or all (callers on this machine only); 404 key_not_found when there is none

Every 404 these routes give for something that does not exist (model_not_found, no_distribution, membership_not_found, key_not_found) carries the usual JSON {"error": {…}} body; an empty-bodied 404 or 405 means the route itself is missing (an older server). A server started with only --cluster-listen (no model) is a valid node and lists no models.

Retry now.

curl -X POST http://127.0.0.1:8000/v1/models/big/cluster/retry
# 202 {"nodes": [{"address": "10.0.0.2:7100", "node": 1, "state": "unreachable", …}], "capacity": …, "context": …,
#      "key": "default", "state": "forming", "attempts": 5, "next_attempt_in_s": null, "last_error": "…", "since": "…",
#      "refused": false, "formed": false}

Probe asks each node what it is, without joining it: connects, proves the key both ways (the key named by key_name, else the distribution-style key given here, else the default key), and asks. container is optional: a model id this server lists (preferred: its container is used) or a container folder on this host; with one, each node says whether it holds the same container (by identity, as a join checks), and has_container is null without one. Every entry carries the address as asked, in the order asked. Nothing on the node changes.

curl -X POST http://127.0.0.1:8000/v1/cluster/probe -H 'Content-Type: application/json' \
     -d '{"nodes": ["10.0.0.2:7100", "10.0.0.9:7100"], "container": "big"}'
{
  "build": "1.4.0+6609eb8",             // this host's
  "nodes": [
    { "address": "10.0.0.2:7100", "reachable": true, "key_ok": true, "version": "1.4.0+6609eb8", "same_build": true,
      "device": "CUDA device, 31.84 GiB", "free_bytes": 30064771072, "capacity": 29527900160, "has_container": true,
      "state": "ready", "error": null },
    { "address": "10.0.0.9:7100", "reachable": false, "key_ok": null, "version": null, "same_build": null,
      "device": null, "free_bytes": null, "capacity": null, "has_container": null,
      "state": "unreachable", "error": "cannot connect: …" }
  ]
}

A node with another key answers "key_ok": false (and no version: it says nothing more before the key is proved); one with no key set refuses the hello ("key_ok": false, "this node has no cluster key set …"); one of another build "same_build": false with both versions in error; one without the container "has_container": false. capacity is what the node offers a cluster that names none.

Plan gives the shard plan a distribution would get from what its nodes offer now (the nodes are asked, as a join's first step, and nothing is joined or loaded), with the probe of the model's container on each node beside it (the plan route always checks the container itself). POST /v1/cluster/plan takes the same body plus "container" (a folder on this host) for a model the server does not list yet:

curl -X POST http://127.0.0.1:8000/v1/models/big/cluster/plan -H 'Content-Type: application/json' \
     -d '{"nodes": ["10.0.0.2:7100"], "capacity": "8GiB", "context": 32768}'
{
  "model": "big",
  "distribution": { "nodes": [{"address": "10.0.0.2:7100", "capacity": null}], "capacity": 8589934592, "context": 32768, "key": "default" },
  "plan": { … },                        // ShardPlan.ToJson, as GET …/cluster gives while formed; null when it cannot be made
  "plan_text": "node 0 …\nnode 1 …",    // null when it cannot be made
  "nodes": [ { "address": "coordinator", "node": 0, "bytes": 4363145216, "capacity": 8589934592, "error": null },
             { "address": "10.0.0.2:7100", "node": 1, "bytes": 4637851648, "capacity": 29527900160, "error": null } ],
  "probe": { "build": "…", "nodes": [ { "address": "10.0.0.2:7100", "reachable": true, "key_ok": true, … } ] },
  "error": null
}

When the plan cannot be made (a node unreachable or refusing, the model does not fit, no such key here) plan and plan_text are null, error says why, and a node's error says what that node answered when it is the cause; the answer is still 200. A 4xx is only a malformed request (400) or an unknown model (404).

Settings that survive a restart

Models and distributions given at start (--model, --config) are there at every start. Changes made at run time are written to the state file when the server has one (--state <file>; AMQL Manager gives each server one) and applied at the next start, after the start settings:

  • a model added at run time (PUT /v1/models/{id}), with its settings;
  • a start model whose settings changed at run time (a distribution set or removed): its new settings;
  • a start model deleted at run time: not listed at the next start (PUT it again to bring it back);
  • whether each model is wanted loaded: a model loaded when the server stopped loads again, one unloaded stays unloaded (a start model too), a distributed one waits for its nodes as above.

Keys are never written: a key comes from the start settings (--cluster-key, AMQL_CLUSTER_KEY). A distribution that had its own key ("key") is written without it and waits after a restart, refused, until it is given again (PUT …/cluster with "key", or use "key_name"). Writes are atomic (a temporary file beside it, flushed, then moved over it) and made only when something changed. A state file that cannot be read (not JSON, another version) is reported at start, kept beside it as <file>.unreadable, and ignored; a missing one is an empty one. Neither stops the start.

// the state file
{
  "version": 1,
  "models": [
    { "id": "local", "source": "config", "wanted": true },
    { "id": "big", "source": "runtime", "wanted": true,
      "model": { "id": "big", "path": "D:\\models\\qwen3.5-4b",
                 "cluster": { "nodes": ["10.0.0.2:7100"], "capacity": 8589934592, "context": 32768 } } }
  ],
  "removed": []
}

The seam

IClusterBackend (StartNodeAsync, FormAsync, Memberships, LeaveAsync, MembershipEnded, Listening, Available, and ProbeAsync and PlanAsync, which a backend may leave out: the server then forms without probing first and the plan route answers with the reason) and IDistributedModel (PlanJson, PlanText, Nodes, CreateSession, Ended, ReleaseAsync, RunsOnBatchScheduler) are what the engine is adapted to; IClusterHost (UnloadIdleModelAsync) and ClusterKeyRing are what the server gives it. CreateSession(plan, store) returns the session the model's generator runs on in place of the local one; ModelHost.Load(..., sessions) takes it. ClusterBackends.Create picks TpClusterBackend (src/Amql.Server/TpClusterBackend.cs) when the engine can run. The route and state tests drive an in-memory backend (ServerModelRegistryTests); ServerClusterTests drives the real one (GPU).

Concurrency

A chat model the GPU engine runs is served by continuous batching. One thread owns the engine; each request gets a sequence of its own on it (its own KV cache, recurrent state and position, over the one uploaded copy of the weights), is prefilled when it arrives, and then joins the running batch: every step advances up to 8 requests by one token in a single pass, and a request leaves the batch the moment it finishes, so a waiting one takes its place at once. Up to 64 requests per model are accepted; past 8 they wait their turn.

  • The same answers. A request's tokens do not depend on what else is running: the projections share each weight read across the batch's rows, but every row keeps its own accumulation order, and attention and the Gated DeltaNet recurrence run per sequence. Tests hold batched logits to each sequence alone (within 1e-4, sequences joining and leaving), and many requests at once to the same answers as one at a time, greedy and seeded sampling alike.
  • Per step: the GEMVs take up to 8 rows; attention and the recurrence take the whole batch in one launch each (per-sequence cache, state and position pointers in a table the captured graph reads); the head writes every row's logits to pinned host memory, and each request samples from its row in place, on its own core.
  • Entail adapters run per request (each request gets its own copy), so stop-circling and no-copy batch too. The dense adapter form, which cannot be copied on the GPU, falls back to one request at a time.
  • --no-batch turns it off. --batch-bf16 runs batches of 4 or more on tensor cores (cuBLAS, activations rounded to BF16, as prompts already are): about 1.6x the throughput at 8, but a reply then depends slightly on what shares its batch.
  • Speculative decoding. A reply running alone on a model with a drafter (Qwen 3.5's MTP layer, or one attached to its container) takes several tokens a step. The drafter proposes as many as have been holding, or the context does when the reply's last 8 tokens appeared in it before. The model runs them as rows of one pass, and the reply takes each row exactly as a plain step would: adapters, constraints and the sampler, in order, for as long as it chooses the next draft. The replies are the same token for token, greedy or sampled with a seed; on Qwen 3.5 4B they come 1.4–1.65x faster. AMQL_MTP_DRAFTS=0 turns it off, AMQL_SUFFIX_DRAFT=0 the context's drafts, and AMQL_SERVER_TIMING=1 logs drafts kept and where a step's time goes. See GPU inference performance. A distributed model speculates the same way, its drafter on the coordinator.
  • 4-bit weights. Point a model's path at a container compiled with amql-cli quantise --format nvfp4 (or mxfp4) and the GPU engine runs its projections at 4 bits. On Qwen 3.5 4B decode is ~1.6x faster, and perplexity rises ~4% (NVFP4). Entail adapters are unaffected: they run their own programs over the tokens. AMQL_GPU_FORMAT=nvfp4|mxfp4 quantises an ordinary container at load instead, the same weights the compiled container holds. See GPU inference performance.
  • /v1/models gives each chat model's concurrency (8 when it batches, else 1) and, when it does not batch, why (batching). AMQL_SERVER_TIMING=1 logs where a batch step's time goes; AMQL_GPU_ENGINE_TIMING=1 the engine's launch, wait and copy.

Qwen 3.5 0.8B on an RTX 5090, agent-sized prompts with 12 tools, 128 to 256 tokens a reply:

Clients One at a time (--no-batch) Batched, exact Batched, --batch-bf16
1 547 tok/s 579 tok/s 557 tok/s
2 496 875 890
4 524 1,251 1,228
8 528 1,520 2,016
16 527 1,594 2,218

Mean latency at 8 clients drops from 1.7 s to 0.9 s (0.7 s with --batch-bf16), at 16 from 3.1 s to 1.4 s.

With Qwen's recommended sampling (temperature 0.6, top-p 0.95, top-k 20), exact: 315 tok/s for one client and 866 at 8, against 290 at any count one at a time, after a rewrite of the top-p filter (it ranked and hashed the whole 248k vocabulary each token; it now ranks only the top-k survivors, with the same draws). The softmax over the whole vocabulary that remained has gone too: with top-k up to 256, the sampler finds the k largest logits and the softmax's denominator in vectorised passes (skipping blocks more than 30 below the largest, under float rounding of the sum) and gives a probability only to the survivors; top-p and the draw then run over those, in the same order and with the same full-vocabulary normalisation, so the draws match the whole-vocabulary path (Sampler.SampleWholeVocabulary, held to it seed for seed in SamplerTopKTests). On a 248k vocabulary a draw takes 64 µs instead of 1,099 µs. An Entail adapter's choice no longer walks the vocabulary with two set lookups per token, nor sums its softmax in scalar doubles: on Qwen 3.5 4B, choosing a sampled token went from ~1,150 µs to 120-330 µs of a ~7 ms step, and in an agent's tool calls from ~2,350 µs to 340-880 µs. The engine alone (amql-cli bench <container> --batch 8) does 668 tok/s at 1 sequence and 2,256 at 8, 3,577 with tensor-core batches.

Prompt prefixes are reused. An agent's calls share all but their last few hundred tokens: Hydra sends an 18k-token system prompt and tool list, and each call adds a reply and a tool result. Qwen 3.5 4B prefills such a prompt in 1.5-2.9 s on an RTX 5090, which was half of every call. So the scheduler keeps finished sequences, each with its prompt and the recurrent state saved at that prompt's mark (GpuEngine.Mark). A new prompt that agrees with a kept one up to its mark rewinds that sequence there (GpuEngine.Rewind: the Gated DeltaNet state and conv history are copied back, and the KV entries before the mark were never overwritten) and prefills only the rest.

  • The mark is at the prompt's second-last <|im_start|>. The last opens the reply's turn. The message before it is the newest, and an agent may move it: Hydra sends its notes as a user message after the newest message, so in the next call that position holds the reply instead. Everything before the mark is the same from one call to the next.

  • What it saves: replaying eight calls of a Hydra turn on the 4B, prefill went from 1.5-2.0 s to 125-212 ms for every call after the first (17-20k tokens reused of 18-21k), and a 64-token reply from 2.2-2.8 s to 0.8 s.

  • Kept by time and memory, not by count. Every finished sequence is kept, so any number of conversations pick up where they left off, until it has sat unused for --kv-idle seconds (default 300) or the device needs the memory. By default the cache is dynamic: it grows into whatever GPU memory is free beyond --kv-gpu-reserve GiB kept for active work, and releases least-recently-used sequences as active work takes it — so a server with memory to spare (a DGX) keeps many more prompts warm, and one under load gives the memory back. The reserve defaults to a quarter of the memory free once the model loaded, at least 1 GiB and at most 4 GiB. A fixed 4 GiB kept nothing for Qwen4-35B-A3B on a 32 GB card, which has about 2 GB free after loading, so every turn read its whole conversation again. A request that needs more memory than is free still evicts kept prefixes first. A kept sequence also drops its verify snapshots (several copies of every Gated DeltaNet layer's state, most of a hybrid model's sequence) until it generates again.

    Time to first token for Qwen4-35B-A3B (NVFP4 GPTQ) on an RTX 5090, streaming, before and after that change:

    Request Before After
    Short question, new conversation 95 ms 63 ms
    Next turn of a short conversation 98 ms 40 ms
    Next turn after an 8K-token history 1,163 ms 54 ms
    8K-token prompt, new conversation 1,144 ms 1,076 ms
    holds its KV cache at its capacity: about 2.3 GiB at 32k positions on the 4B (KV is f32, 64 KiB a token, plus
    the drafter's 8 KiB), 150 MiB for a 1.7k-token prompt on the 0.8B. --kv-idle 0 keeps them until the memory
    is needed.
  • Numerics: a rewound sequence gives exactly the logits it gave at the mark, steps after it included (tested on plain and Gated DeltaNet models). A prompt prefilled in two pieces rather than one agrees with the one-piece prefill to f32 rounding in exact mode. In the default BF16 mode the split moves rounding, as any change of chunk boundaries does, so greedy replies can part on a near-tie (three of eight in the replay above, with similar wording).

  • --no-prefix-reuse prefills every prompt whole. AMQL_SERVER_TIMING=1 logs each admission's prompt, reused tokens and prefill time, and how far the prompt agrees with each kept sequence.

  • AMQL_SERVER_RAW=1 logs every reply as the model wrote it, special tokens included, to stderr.

Paging prompt state to disk (off by default). With --kv-disk, a kept sequence that leaves GPU memory (idle, over the budget, or at shutdown) is written to disk first, and a later prompt that starts the same way loads it back instead of prefilling. It works for any model the GPU engine batches: what is written is exactly what GpuEngine.Rewind needs (GpuEngine.SaveMark): the prompt's tokens up to its mark, every attention layer's KV rows before the mark, the recurrent state and conv history saved there, and the MTP drafter's cache and pending state. Rows after the mark are left out. GpuEngine.RestoreMark builds a new sequence from it that carries on bit for bit as the one saved, drafter included (KvPagingTests).

  • Each model has its own folder: kv-cache in its container by default (the NVFP4/MXFP4 copy has its own), --kv-dir DIR for DIR/<model id>, or "kv_dir" per model in --config (which turns the disk tier on for that model). Every file records the model's fingerprint, a hash of its engine geometry, prefill precision and container files, and one that does not match is deleted when found, so a rebuilt container never loads stale state. Files left from an earlier run are loaded at start when they are still in date.
  • Limits: --kv-disk-budget GB per model (default 1), oldest deleted first; a state larger than the budget is not written (a 1.7k-token prompt on the 0.8B is 65 MiB, on the 4B 64 KiB a token, so 1 GiB holds ~15k tokens). --kv-expire S deletes a state that long after its last use (default 1800; 0 never). Prompts saved before fewer than 512 tokens are not written: they prefill faster than they load.
  • Off the batch: the write runs in the background, and the read runs on the request's thread before it joins the batch, so other replies keep stepping. A state is taken (its file deleted) when it is loaded; it is written again with its newer mark when that sequence leaves GPU memory. A state still being written can be taken from memory.
  • Measured on the 0.8B, a 1,707-token conversation idle for 5 s: paged out to a 65 MiB file, loaded back with 43 tokens left to prefill (99 ms for the whole 40-token reply against 39 ms from GPU memory), and the reply the same as the one picked up from GPU memory. Larger models and longer prompts gain the most: the 4B prefills an 18k-token prompt in 1.5-2.9 s, against ~1.2 GB to read back.
  • Privacy: the files hold the conversation in a recoverable form. Keep the folder on a disk only the server's account can read; deleting a file on an SSD does not erase its blocks.
  • A distributed model (clusters) pages too: kv_disk in GET /v1/models/{id} is true when it has a disk tier. Each node writes its own part of the state (its heads' KV, its linear-attention heads' state and conv history) to its own disk, and the model's folder holds the coordinator's record of where (the nodes, the plan's fingerprint, each node's bytes). A node's parts go in a folder per membership under its own KV folder (<--kv-dir>/_cluster-pages, or amql-tp-pages under the temp folder without --kv-dir; tp-worker --page-dir), removed when the membership ends; a restarted node removes its stale folders at the next join for the same coordinator and model, and any left over a day at start. The disk budget counts every node's bytes, and so does the GPU budget (a kept sequence's memory on every node). A restore first asks every node whether it holds its part whole under the same plan, and is refused (the prompt is prefilled) naming the node that does not, before any node changes; a node failing during the restore itself fails the cluster as a failed step does. The records name the cluster's formation, so those of an earlier formation are deleted at load (their pages went with its memberships), and kept sequences are not paged at shutdown (the pages would go with the release). See Tensor parallelism.

The log (stderr) names each page-out, restore, expiry and release.

Device memory. Keep the GPU's memory clear of other models. With three other models loaded beside the 4B (and LM Studio and a game on the same card, 28.5 of 32.6 GB in use), the same 18k-token prefill took 32.6 s instead of 2.9 s: its scratch buffers no longer fit, and the driver paged device memory to the host.

Decisions

The body and response are TypeSafe's, answered by the same engine as amql-cli decide — see decision-models-von.md. Invalid requests are 422: an OpenAI-shaped error on /v1, { "code": 422, "message": …, "data": null } on /api/v1/decisions.

Embeddings

input may be a string, an array of strings, an array of token ids, or an array of token-id arrays. Text is tokenised as HF's tokenizer(text) does (post-processor template included) and truncated to the context. The container's recorded pooling (mean, last or cls) runs over the post-final-norm hidden states, then L2-normalises if recorded. encoding_format: "base64" returns little-endian float32 bytes. dimensions must equal the hidden size — the container records no Matryoshka truncation, so none is invented. Usage counts prompt tokens.

Chat completions and responses

Messages are rendered by the container's own chat template (below) and tokenised without extra special tokens, as apply_chat_template does.

  • Content: strings or arrays of text parts (text, input_text, output_text); developer is a system message; the Responses API's instructions is a system message placed first.
  • Sampling: temperature (0 = greedy; default 1), top_p, top_k (an extension; 0 = off), seed, stop (up to 4 strings, never streamed past), max_tokens / max_completion_tokens / max_output_tokens (default --max-tokens, bounded by the context). --temperature, --top-p and --top-k set the defaults for requests that leave them out. Generation stops at the tokens named by generation_config.json's eos_token_id, the tokenizer's eos_token, and the tokens the template ends a turn with, after words and after calls. Other sampling fields (penalties, min_p) are ignored.
  • Text is decoded from the accumulated bytes at every step, so a character split across tokens is sent once, whole.
  • Logprobs (chat, not streamed): logprobs: true and top_logprobs (1-20, default 5) give each token's logprob and its top alternatives. return_tokens_as_token_ids: true (as vLLM has it) writes every token as token_id:N, so two replies can be compared token by token where their text cannot (a byte-level piece decodes to U+FFFD on its own).
  • Thinking is on when chat_template_kwargs.enable_thinking is true; else when reasoning_effort (chat) or reasoning.effort (Responses) is anything but none/minimal; else when the server runs with --think. The thinking block comes back apart from the answer: reasoning_content on the chat message (and in stream deltas), a reasoning output item with reasoning_text in Responses. Sent back on a later turn (reasoning_content on an assistant message, or a reasoning input item), it is rendered as the template renders it. The other chat_template_kwargs, and reasoning_effort, are passed to the template.
  • Finish: stop, length or tool_calls for chat; Responses reports completed, or incomplete with incomplete_details.reason: "max_output_tokens".
  • Streaming: chat sends chat.completion.chunk deltas (role first, finish_reason last, a usage chunk with stream_options.include_usage) and data: [DONE]. Responses sends response.created, response.in_progress, then for each output item response.output_item.added, response.content_part.added, its deltas (response.reasoning_text.delta, response.output_text.delta, or response.function_call_arguments.delta), their .done, response.content_part.done, response.output_item.done, and finally response.completed or response.incomplete, each with a sequence_number. Nothing is sent before it is certain: text that could begin </think> or a call waits for the next token.
  • Refused (400, OpenAI error shape), rather than silently ignored: legacy functions, n > 1, audio and other content parts, images where the model reads none, tool types other than functions, and the Responses API's conversation.
  • vote (an extension): see Fork and vote.

Chat templates

A model is served by the template it ships (chat_template.jinja, or chat_template in tokenizer_config.json), run by AMQL's own Jinja interpreter. It keeps to transformers' rules (trimmed blocks, tojson, raise_exception, strftime_now). On 23 models' templates, 966 conversations came out exactly as transformers renders them. What a template raises is the request's 400.

No family is named in the code. When a model loads, the server renders probe conversations and compares what comes out to learn:

from
What opens and closes thinking, and the empty block that stands for none an assistant message with reasoning; the prompt with thinking on and off
What ends a turn, opens the next and opens a tool's result conversations with one more message each
Whether tools, calls, results and images are written at all; what is not is refused the same conversations with and without them
How calls are written calls with no arguments, one, two and a number, and two calls in one turn

Calls come in four forms:

Form Example Models
JSON object <tool_call>{"name": "f", "arguments": {"k": "v"}}</tool_call>, [TOOL_CALLS]f[ARGS]{"k": "v"} Qwen 3, Granite, Mellum, Mistral
Parameters one by one <function=f><parameter=k>v</parameter></function>, <param name="k">v</param>, <arg_key>k</arg_key><arg_value>v</arg_value> Qwen 3.5 and later, Nemotron, MiniCPM, GLM
Python call <|tool_call_start|>[f(k='v')]<|tool_call_end|> LFM 2.5
Object with marked strings <|tool_call>call:f{k:<|"|>v<|"|>}<tool_call|> Gemma 4

A call may also be a message of its own whose header names the tool before the call's mark, the name written again inside (<|message_model|>f<|content_invoke_tool_json|>{"name":"f","args":{…}}, Inkling 2). The form is learned from what follows the header's name; the name is kept out of the reply until the mark says it was a call, and a token that ends every message is not taken for the end of a reply of calls.

Each form is checked by writing calls with the template, reading them back and holding them to their tools: on the models' own templates, and for Mistral's and GLM's on templates cut down to the same form. Live, on 32 tool tests each (one call, several, loops, forced, streamed, with thinking and without): Qwen 3.5 4B 32, Gemma 4 26B 31, MiniCPM5 2B 31.

The log says at load whether a model serves tools, and why not when it does not. Refused: a template that writes no calls or no results (Gemma 3, Phi-3), and calls that start with no mark of their own (gpt-oss's, which start in the middle of a header). LFM 2.5 1.2B's template writes strings between quotes with nothing escaped, so a call whose text holds a quote before a comma or a bracket cannot be read for certain.

A conversation is rendered as transformers would render it, with three exceptions. A result that names no call answers the calls in order. What was said along with a call is written before it where the template would put it after the call's results. And a reply that goes on from an image in a tool result, with thinking off, starts with the empty thinking block.

Calls held to the tools

A small model writes calls the harness cannot run: a parameter the tool does not have (edit_file with content), an array parameter whose JSON does not parse, a tool that does not exist. So once a reply opens a call (outside thinking), the rest of it is held to the request's tools by the same constrained decoding as structured output, until it closes. In the form Qwen 3.5 writes, and likewise in the others:

  • <function=NAME> names a declared tool; each <parameter=K> is one of its parameters, not given yet; </function> comes only once every required parameter is there.
  • A string parameter (or an untyped one) is free text up to </parameter>; a string enum is one of its values, bare; any other type (array, object, integer, number, boolean) is JSON its schema allows, then </parameter>.
  • Calls the model writes are therefore always ones the harness can parse: on a random model forced to call a tool (tool_choice: required), every reply is a call with the declared name and typed, parseable arguments.

--free-tool-calls turns it off.

What a schema says in words. Some rules a schema states only in its descriptions, and a small model breaks every one: Hydra's edit_file edits mark find, find_lines, replace and replace_lines "(replace_text only)", and three pairs "set one or the other, never both", and in one session Qwen 3.5 0.8B sent op: replace with find/replace, then replace beside replace_lines, and was refused each time. So in an object with a required string enum (the edit's op), a property whose description says it is only for some of the enum's values ("(replace_text only)", "insert_* only", "only for replace/delete") is offered only after the enum has one of them, and of two properties a description says to set "X or Y, never both", only one may be written. Descriptions without such words change nothing.

Mentioned tools. Told "write a new version from scratch with create_file (overwrite true), no need to read the old one", the 0.8B read the file and patched it with edit_file, whose anchors it cannot write. So the first call after the user's message, when the message names tools (as whole words, not in a clause that says not to: "no need to", "don't use"), names the first of them, provided the model gives it 1e-4 of its probability. Later calls are the model's own: there it is working from results, and a redirect turned a reply that meant to read the file it had to fix into another build. Replayed, the step that had begun with read_file began with create_file and a whole program. --no-mention-rule turns it off with the parameter rule.

Tried and dropped: copying the task. Given the code to write ("sum new FileInfo(f).Length over Directory.EnumerateFiles(folder, …)"), the 0.8B wrote new FileInfo(folder) and an invented .FileList. A prior that, where the reply ended with a stretch of the user's message, gave the stretch's next tokens a share of the probability (kNN-LM style, λ 0.5) did not pay. At a 16-character match it never acted, because the reply leaves the user's words before copying that much. At 10 characters with an absolute floor (0.1%) it pulled the user's prose into the code (foreach (…) print the name and bytes / 1048576.0 formatted with …). With a floor relative to the model's first choice it was safe but sampled programs built 2/8 times with it and 3/8 without. The mistake is in the model's plan, not in drifting from text it is copying, so the code was removed.

Mentioned parameters. A small model plans in words and then writes the call by habit: asked to replace a file that exists, Qwen 3.5 0.8B said "I'll overwrite it", the tool answered "Pass overwrite: true", the user said so too, and still, measured, it chose content over overwrite at 0.995 to 0.005, and after content closed the call at 0.999, so the call failed the same way every time. So where a call can open a parameter, an optional parameter not given yet that the current task names, as a whole word, in the user's latest message, a tool result since, or the reply's own thinking, is opened next, provided the model gives the way there at least 1e-4 of its probability. Its value is still the model's, under the grammar. In the agent session it took create_file … overwrite: true from failing five times in a row to succeeding first time. A tool result counts only where it tells the call what to pass ("Pass overwrite: true", "set 'force' to true"): results name many fields ("handle": "bg-95c9") and warn about some ("'handle' means poll or stop"), and those are not hints. --no-mention-rule turns it off.

Announced calls. A reply with tools on offer that ends, outside thinking and outside a code block, on a colon after saying it is about to act ("Now let me build it:", "I'll run the tests:") has promised a call; ending the turn there leaves the harness nothing to run, and a small model then claims the build succeeded. So there the call opens, when the model gives the way to <tool_call> at least 1e-4 of its probability. A colon after anything else ("Here's what was done:") introduces what follows, so the reply may not end on it but no call is forced: forcing one there sent the agent round again, re-running a program it had just run. --no-announce-rule turns it off.

Copied line decoration. A harness may show a file with each line marked (L42:a3f9c1│code); a small model that reads a file and writes it back copies the marks with the code, and every line fails to build (Hydra's agent did exactly this, then copied the copy). So the server learns the decoration from the request's own tool results (a line start up to a separator, with a varying number or hash, on 80%+ of a result's lines; no harness is named in the code) and, in a call's string value where 80%+ of the lines carry it, removes it, along with the result's header lines copied above it. The shorter forms the model also writes (L42:code, the hash dropped) and a copy of a copy (marked twice) are removed too. Values that merely contain a mark or two are left alone. The log says when it acts.

The model is also shown the results without the decoration: a 0.8B model read L4:e3b0c4│ on a blank line as a missing line, listed 18 lines of a sound file as missing and patched them one by one; shown the same file plain, it restated the six requirements of the task and wrote the program. A JSON result is written back compactly with its text unescaped; one with nothing decorated is sent as it came. Hiding the marks has a cost when the harness takes them back, as anchors an edit names lines by (L42:a3f9c1): the model can only guess them. On the coding benchmark Kaja-Ink wrote L1:a1b2c3d4e5f6 and L5:0a1b2c3d…, and every anchored edit failed. So once a call in the conversation has passed a value shaped like a mark (a learned decoration without its separator, a guessed hash included, or a short line that opens with one, such as L1:namespace Calendar;), the results are shown with their marks. --keep-line-marks always shows the results as they came.

Repeated calls. At temperature 0 a small model copies its own previous call from the conversation: it ran the program, got the output, and ran it again, and again. A call (tool and arguments, key order ignored) that has already been made at least twice, whose latest result is one it returned before (numbers and hashes such as build ids and durations ignored; not only the time before, since a harness may answer a re-read with "unchanged since your last read", so the file and that note take turns, and the model read one file eight times), is not made again. The reply is generated again from what it said before the call, after a lead-in that says why. A harness may write a call back with its numbers as strings ({"test_suite_id":"1"} for 1), so a string holding a number or a boolean compares as that literal.

  • The request has other tools: they stay open and only the repeated call's tool is withheld ("That read_file call has already returned the same result twice, so I will not make it again: its result is above. Next step:"). An agent moves on only through its next call. With every call closed, Kaja-Ink, which had re-read a file it meant to edit, described the edit in prose. The harness then asked it to continue, and it copied that stalled reply, lead-in and all, until the episode ended. On the coding benchmark this ended 6 of the 9 unresolved tasks.
  • It has none: calls are closed (the call's markup cannot be written as text either), and the lead-in is "…so instead of making it again, here is where things stand:". After a run the agent then reports the output; after an edit, where the build stands. An earlier lead-in, "here is what it showed", led it to paste an old version of the file as if the edit had returned it.

--allow-repeated-calls turns it off.

Stalls (off by default). An agent can read, list and search for a whole run and never make the edit: on the coding benchmark Kaja-Ink did this on calendar-recurrence. Each call is a little different, so the repeated-call guard never sees a repeat. Nothing here knows what a tool does, so a call is judged by what it brought. It brought something new when its result differs from the last result of the same call (a build that now fails differently, a file read again after an edit), or when its result holds at least two words seen nowhere before in the user's turn. Words in any call's arguments count as seen, so a search that echoes its pattern, or an edit that echoes its code, adds nothing. Numbers and hashes are ignored, and a JSON result is read by its keys and strings, unescaped. With --stall-rule K:

  • K calls in a row bring nothing new. A reply whose first call is to a tool those calls used is generated again with those tools (and any with a stale call) withheld, after "My last K calls have brought nothing new, so I will not make another read_file call: I will act on what I have found. Next step:". The tools that went unused are what is left. Where every tool on offer went round in the streak, nothing is withheld.
  • 2K calls in a row. A reply that makes any call is generated again with calls closed, after "…so instead of making another, here is where things stand:". The turn goes back to the client, and the client's next user message starts a new turn, with a new count.

The count runs over the user's current turn (see "The user's turn" below). A harness that answers a reply without calls with a user message ("Continue with the tools") starts a new turn there, so the count starts again.

Checking before finishing (off by default). An agent can edit several files and end its turn without building, leaving code that does not compile (expression-parser and ledger-transfers on the coding benchmark). Which tools change things and which check them is the client's to say, not the server's to guess. --check-before-finish AFTER:CHECK[:FINISH[:MAX]] (repeatable), or a request's check_before_finish, gives the relation. The request's field is a string in the same form, an object {"after", "check", "finish", "max"}, or an array of either, and it replaces the server's ([] for none). Each part is a pattern over tool names, with | between alternatives and * for any run of characters:

amql-server … --check-before-finish "edit_file|create_file:run_build|run_tests:report_completion"

After a call matching AFTER, with no call matching CHECK since, in the user's current turn, a reply that would end the turn is generated again. Ending means a reply with no call, or one whose first call matches FINISH (an agent's "report completion" tool). What it said stands. It goes on after "Before I finish, I will check my changes:" with a call written for it: to the one CHECK tool on offer, or, when several match, to whichever of them the model chooses. Only those tools are open, and the arguments are the model's own, under the tools' grammar.

  • Bounded. Each forced call is a CHECK call, so the relation holds again until the next AFTER call: the rule cannot fire twice for one change. It does not require the check to pass, only that it ran. It steers a turn at most MAX times (default 3), counted by its lead-in in the turn's assistant messages, and then lets the turn end.
  • What it leaves alone: a reply cut off by the token limit, stopped by the loop guard or by a request's stop string, ended inside its thinking, or left with fewer than 128 tokens of its limit; a request whose tool_choice names the call; a FINISH call that is not the reply's first call (calls before it have been sent already); and the tools the request does not offer. A check made through some other tool (a build run in a terminal) does not count.

Both rules regenerate the reply the way the repeated-call guard does. The refused call is never sent, and the client sees one reply: what the model said, the lead-in, and the next call. Neither acts in a model whose calls open only at the start of a reply (a bare JSON object), since no lead-in could come first. The log says when each acts (stall: …, check before finish: …).

A call where the name comes first. Inkling opens a call by ending its message (<|end_message|>) and then naming the tool. A reply that announces an action ("Let me write the new Csv.cs:") may not end on the colon, but that token's text is empty, and a token with no text was never allowed. So the one token that opens the call was ruled out: Kaja-Ink wrote "OK" in its place, then ended its turn or made some other call. Where the name comes first, the message's end is allowed there now.

Seen values. Asked to read the file that a listing showed as src/RecurrenceRule.cs, Kaja-Ink wrote src/Recur-Ink.cs. The copy prior (--copy-prior) favours text already in the conversation inside a call's value. It changed nothing measurable, because it only nudges. So a client can name string arguments that must be a value already seen:

{"seen_values": {"read_file": ["path"], "edit_file": ["path"]}}

--seen-values read_file:path,edit_file:path sets the same for every request that does not give the field. It is off by default. A request's {} or null turns it off. Such an argument may then only be a path made of names that the conversation's user messages and tool results hold, as the model is shown them:

  • A word is a run of text with no blank space in it, as the copy prior reads one. Quotes, brackets, braces, < > , ; | =, and a colon with no slash after it cut a word further, so src/a.cs:12 gives src/a.cs. Markdown's * and a sentence's closing . : ! ? are trimmed. A result that is JSON is read as its strings, unescaped.
  • A name is a part of a word between / and \.
  • The value is names joined by single slashes or backslashes, which may also lead or end it, up to 400 characters. A whole path that was seen is admitted. So is a file a tree listing shows only under its directory (src/, then RecurrenceRule.cs indented below it). A name never seen cannot be written.

The names are kept in a trie (sorted, walked by binary search) inside the same grammar that holds the call. In JSON, an escape stands for the character it writes (\/, \\, s), and the closing quote comes only where a name is whole. Written bare between parameter marks, the value closes at the parameter's close in the same way. The other forms are held the same way.

  • What is held. Only the arguments named, and only plain strings (not an enum, an array or an object). A tool that creates a file stays free.
  • No dead ends. With no names seen yet, or no tool named in the request, nothing is held.
  • The bound. At most 4,096 distinct names are kept, the latest first, counted from the end of the conversation back. Past that, a name that only an early message held can no longer be written.
  • Needs the call grammar. --free-tool-calls turns this off too.

swe-bench run --seen-values sends the field for the benchmark's own read_file and edit_file.

The user's turn. The rules that read "the user's message" take the turn as beginning at the user's own message: user messages straight after it (a harness's retrieved notes and hints) belong to it, and a user message after a tool result (a harness's "[System] same action 3 times") is a note inside the turn, not a new one. When Hydra moved its notes into a message of their own after the user's, the task the user gave had vanished from "the newest user message", and the first call went back to reading the file. The mentioned-tool rule reads the user's own message only, since the notes name tools too ("tool:edit_file (graph proximity 0.45)").

Continuing a reply

continue_final_message: true (vLLM's name) on chat completions treats the last message, an assistant message with text, as the start of the reply: the prompt is the conversation's generation prompt followed by that text, and the model carries on from it. The reply holds only the continuation. With logprobs, it shows what a model would write at any point of a reply, which is how the call habits above were measured.

The thinking budget

A small reasoning model often has its answer long before it stops thinking, and a reply that runs out of tokens while still thinking has no answer at all. --thinking-budget N (or "thinking_budget" in a model's config, or in the request, top level or in chat_template_kwargs) closes the block after N thinking tokens, at the end of the line, and lets the answer follow. It closes earlier when the reply's own max_tokens would leave too little room: a quarter of the limit, at most 512 tokens, is kept. 0, the default, is no limit. On 80 held-out hard problems Qwen 3.5 4B got 60 thinking without a limit and 80 with a budget of 1,536 (79 at 2,048 and 3,072; see Reasoning). It applies to free text only; structured output never thinks.

Fork and vote

Single greedy runs of a small model swing by a task or two on a benchmark, and sampling several whole replies and taking the majority answer (self-consistency) helps but costs the replies over again. Most of a reasoning reply is its reasoning, so --vote K (off by default; "vote": K in a request, or {"answers": K, "temperature": T}, or 0 to turn the server's off) reasons once and votes on the answers:

  • Where the reasoning closes (the template's close token has been run, and whatever a thinking budget wrote after it), the reply pauses. Its sequence is forked K−1 times (GpuEngine.Fork: a device copy of the KV rows up to there, the recurrent state and conv history, nothing recomputed), and the forks join the batch as answers of their own. The reply goes on as answer 0, exactly as it would have without a vote (greedy, or sampled as the request asked); the others are sampled at --vote-temperature (0.6), with top-p 0.95 and top-k 20 unless the request narrows its own, each from a seed of its own. Entail adapters come along: each fork's copy reads the prompt and the reasoning as the reply's did.
  • The cost is about one answer's steps, not K replies: the answers step together, and a batch step reads each weight once for up to 8 rows. Each fork holds a copy of the prefix's KV cache while it runs (32 KiB a token on Qwen 3.5 4B at FP16), and a reply that reaches its fork waits there until the batch has rows for all K answers; meanwhile no new request is admitted. When the device cannot hold the copies, kept sequences are let go first, then the vote runs with fewer answers, or none.
  • Choosing. Answers are free text, so each is keyed by what it commits to: the last \boxed{}, else the last line that gives an answer (Answer: 12, **Final answer:** B, The answer is 12.), else its last line with a letter or digit. A number there decides (the last, read as entail bench reads one: thousands separators dropped, 12.0 is 12), so "42", "The total is 42 apples." and \boxed{42} agree; otherwise the line itself, in lower case, emphasis and trailing punctuation removed ("B", "B." and "b" agree). An answer cut at the token limit abstains. The largest group of two or more wins, a tie going to the group that holds answer 0, and the group's answer 0 or its first is returned. When no two agree, answer 0 is returned: a vote never does worse than the reply alone where nothing agrees. Long free text rarely agrees word for word, so there the vote mostly returns answer 0; it pays on answers that end in a short result.
  • Streaming. The reasoning streams as it comes. The answer cannot go before the vote is in, so after the reasoning a client sees nothing for the answers' time, then the chosen answer whole, in one or a few content deltas (response.output_text.delta on Responses), then the finish and usage as usual.
  • Usage counts every sampled token: the reasoning, answer 0 and every other answer. It carries the vote as an extension, in usage.vote (chat, and the usage chunk with stream_options.include_usage) and in the Responses usage: answers, agreed (low agreement is itself a signal: the model was unsure), abstained, chosen (0 is the reply's own), key (what they agreed on, as compared), answer_tokens (the other answers' tokens) and note. The log says the same: vote: reasoning closed after 812 tokens; 5 answers from it, then vote: 4 of 5 answers agree on "#42"; answer 0 returned, 96 tokens for the other answers.
  • Not run (one answer, and usage.vote says why in note, with answers: 1): a reply that does not reason or chooses not to; tools on offer (an answer may be a call, and calls are not voted on, so an agent's turns are answered once); structured output; a forced call (tool_choice); logprobs; a template whose thinking close is not one token; no tokens left for an answer; and a model the server does not batch (--no-batch, the CPU, models run by visits, which carry their state in slots that are not forked).
  • amql-cli entail bench runs in-process, without the server; scripts/vote/vote_bench.py sends the cases it writes (--write-cases) to the server with and without "vote" and scores them as it does.

The loop guard

A small model can fall into repeating itself: the same line of a file, again and again, until the token limit, which at a long agent context (47k tokens, ~140 tok/s) is minutes of nothing visible, since text inside an open call is only sent once the call closes. The server watches each reply's own tail: once one stretch (up to 256 tokens) has repeated back to back at least 4 times and 192 tokens in all, a reply outside thinking ends there (length / incomplete; an open call comes back as text and is never run), and thinking is closed instead so the answer can follow. Only the reply is read, never the prompt, so copying a path or command from the conversation is never taken for a loop (what broke no-copy); lines that vary, even by one token, are not a loop either. A counting loop is the exception: lines that differ only in a number or a hash (the model writing L2196:c74105│ //, L2197:c74105│ //, … for 32,000 tokens) are a loop once that has held for 16 rounds and 512 tokens, far longer than a numbered list. A reply returned whole (not streamed) that the guard stopped comes back as its first round, finished (stop / completed), since it said what it had to say once and a client that sees length asks for more. The log says when it acts. Hydra's request that looped on one this.Controls.Add(...) line for 32,000 tokens now ends after 424, in 4.7 s. --no-loop-guard turns it off; structured output is exempt (its grammar bounds it).

Contrastive context decoding

A small model often answers from memory against what it was shown: given a file called RecurrenceRule.cs it writes another name, given a document it states a figure from training. Contrastive context decoding (off by default) runs the reply twice in step, once on the prompt and once on the prompt without its context, and sharpens the difference:

logits = (1 + a) * with - a * without      over the tokens plausible with the context

A token the context makes likelier than the model would say anyway is boosted; one it would have said without the context is damped. Only tokens whose probability with the context is at least a fraction (default 0.1) of the top token's can be chosen, so the subtraction never promotes a token that is unlikely in its own right. No training, and nothing about a model: what the context is, the request says.

  • What the context is: "context_contrast" in the request: true (the server's settings), a strength (0.5), false or 0 (off, over a server default), or an object: {"alpha": 0.5, "messages": ["tool", 3, -1], "mode": "blank", "plausibility": 0.1, "thinking": false}. messages names roles (tool, user, system, assistant) and indices into the request's messages (negative from the end), so a client marks the documents it retrieved by where it put them. blank (the default) keeps each such message and empties it, so a call still has its result and the template renders the same turns; drop leaves it out (if the template refuses that, it is blanked instead). The second prompt is the same conversation rendered by the same template with the same tools, thinking switch and started reply. --contrast A turns it on for every chat request, --contrast-messages tool,0 sets what the context is (default: every tool result), --contrast-mode and --contrast-plausibility the rest. A strength of 0.5 is a start; 1 is strong.
  • Where it acts: the two logits are combined first, and everything after reads the combined row as it would the model's: the n-gram and copy priors, Entail adapters, the sampler, and the grammar of a tool call or a structured reply, which still decides what may be written. Where the grammar allows no token the contrast left plausible, that token is chosen from the model's own logits (the log counts these). Forced text (a required call's opening, a closing think tag) is written as it is.
  • Not a call's opening or structure: whether to make a call, and how it is written (the tool's name, the parameter names, the markup), are decisions about acting, not about what the context says, so those steps are taken on the model's own logits and only free text and the values inside a call's arguments are contrasted. Whether a call opens is not known before the token is chosen, so where the model's own first choice would begin a call's opening, or the opening is under way, that step is not contrasted; inside a call, a step is contrasted only while the call is in a value and the model's own first choice keeps it there (the token that closes a value is the model's). In a call written as one object, only string values count as values here; numbers and booleans are the model's own.
  • Only the answer, by default: the reasoning is the model's own working, and contrasting it costs a row for every thinking token. The second sequence does not step while the reply thinks; when the answer begins, the thinking is read into it in one prefill. --contrast-thinking ("thinking": true) contrasts the thinking too.
  • Cost: the second sequence is another row of the batch (a contrasted reply counts as two of the 8), stepping in the same pass: on the 0.8B two rows cost about 1.3x one. Its prompt is prefilled with prefix reuse like any other (an agent's next call finds the last call's state without its context, kept as any finished sequence is, in the same GPU budget), so after the first call of a conversation it costs what the conversation added. Each step also combines the two rows over the vocabulary on the CPU. A contrasted answer does not speculate: drafts are verified on one sequence, so it gives up the 1.4-1.65x of speculative decoding; the reply's thinking, which is not contrasted, still speculates while it runs alone, and the speculative step ends where the answer begins. The log says so. Expect a lone contrasted answer at roughly half to three quarters of its plain speed on a model with a drafter.
  • Runs plain, and says why in the log, when nothing is left to take out (no message matches, or the prompt comes out the same), the prompt has images, requests are not batched (--no-batch, the CPU, or an engine that runs one sequence at a time, as looped depth does), or the second sequence cannot be set up (no memory for it).
  • Where it can hurt: it pushes the reply towards what the context changes and away from what the model knows regardless. A right answer the context does not mention (a language keyword, a library's usual API, the wording of a reply) is damped as "memory"; at a high strength the reply can lean on the context's words where its own were better, or repeat the context where it should answer. Keep the context to what the reply is to follow (tool results, retrieved documents), not the user's question or the system prompt.
  • The log: contrast: a=0.5 against the prompt with 3 messages blanked, 18234 -> 12001 tokens (11800 reused); the answer only; speculation while it thinks, none in the answer (two sequences) when a reply starts, and contrast: 212 of 260 tokens contrasted, the top token changed at 9 when it ends. Both counts are of the reply's tokens (the step that ends it is not one), and the line adds how many steps were left to the model's own logits because they open or shape a call.

amql-cli distil copy --contrast A measures the effect without the server: it scores replies that must repeat names from the prompt under the contrast, against the prompt with those names taken out (see Checking that an edit still copies).

Structured output

response_format (chat: {"type":"json_schema","json_schema":{"name","schema","strict"}} or {"type":"json_object"}) and text.format (Responses: {"type":"json_schema","name","schema","strict"} or {"type":"json_object"}) hold the reply to JSON by constrained decoding: at every token only those that keep the reply a value the schema allows can be drawn (the request's own temperature, top-p and top-k over just those), and the reply can end only where the value is complete. So the reply always parses and follows the schema, whatever the model would have written; a token limit can still cut a long one short (length / incomplete).

  • The schema subset enforced: type and type lists (["string","null"]), properties in their declared order (an optional one may be left out, a required one may not), required, no undeclared properties, items, enum, const, maxLength, anyOf/oneOf (merged), and $ref into the schema's own $defs/definitions. Other keywords (pattern, minimum, minItems …) are not enforced; a remote $ref is a 400. json_object takes any object.
  • Bounded: whitespace between tokens is limited (24 characters in a row) and a string without maxLength to 8,000 characters, so a reply cannot spin forever on either.
  • The model is told: the schema is appended to the system message ("Respond with a single JSON value … that follows this JSON Schema"), so a small model knows what it is writing; the constraint only decides what it may write. A structured reply has no thinking block and no tool calls.
  • Cost: the 256 likeliest tokens are checked against the grammar each step, the whole vocabulary only when none fits; works in batches too. Hydra's 7,000-token transcript assessment comes back in 0.8 s.

Tools (function calling)

Where the template writes tools, calls and results, requests may carry tools: chat's {"type":"function","function":{name, description, parameters}}, rendered exactly as the client sent them, or the Responses API's flat {"type":"function", name, description, parameters}.

  • Calls in the reply become tool_calls (chat, finish_reason: "tool_calls") or function_call output items (Responses), each with a call_… id and its arguments as a JSON object string. A parameter is read as the type its schema gives it — integer, number, boolean, object or array — and a value that does not read as that type stays a string for the client to report. Text the model writes after its last call is dropped, as the template asks; a call that never closed (the token limit cut it off) is returned as content, never as a call. In a stream, each call is sent whole once it closes.
  • History: assistant messages with tool_calls and tool messages (chat), or function_call and function_call_output items (Responses), are rendered as the template renders them.
  • tool_choice: auto (default); none leaves the tools out of the prompt; required writes a call's opening for the model, and a named function writes the whole opening of its call, so the model can only continue a call — after its thinking block when it thinks. A function the request does not offer is a 400.
  • parallel_tool_calls: false keeps the first call, and stops generating once it closes.
  • previous_response_id: responses are kept in memory (the newest 512, unless "store": false), so a request can continue one without resending it; the earlier response's instructions are not carried over, as in OpenAI's API. An unknown id is a 404 previous_response_not_found.

Images

A chat model whose container carries a vision tower this build runs (Gemma 4's) reads images: images is true in /v1/models. Chat's {"type":"image_url","image_url":{"url":"data:image/png;base64,…","detail":"auto"}} and the Responses API's {"type":"input_image","image_url":"data:…"} go in user messages and tool results. PNG and JPEG are read, and only data: URLs: the server fetches nothing on a client's behalf. A request may be 256 MB. See gemma-4.md.

Entail adapters

--adapter [id=]<dir>[,<dir>…] runs Entail adapters beside a chat model (id= picks one model; a bare list goes to every chat model). Each rules on the next token as the reply is generated — the model's weights are never changed — so a program such as stop-circling (close the thinking block once the model repeats itself, see entail-reasoning.md) works through the API as it does in amql-cli entail bench. While an adapter is speaking, logprobs still describe the model's own distribution. Not every program suits an agent: no-copy, which rules out the token that would continue a run already written three times, broke Hydra's tool calls. The working directory D:\Temp\ModelTest appeared three times in the conversation, so it ruled out Test and the model listed D:\Temp\Model; replayed without it, the same request gives the right path. Serve agents with stop-circling alone, which acts only inside the thinking block.

A container may carry its own adapters (amql-cli attach <container> --adapter <dir>,…, in adapters/). A model given no adapters, by --model or by a --config entry with no "adapters", runs those, in the order the container lists them; "adapters": [] runs none, and a name in "adapters" that is no folder is one of the container's own ("adapters": ["stop-circling"]). Adapters read an image's tokens as tokens they do not know, so images and adapters run together.

dotnet bin/win-x64/Release/amql-server.dll --model qwen=<qwen3.5-0.8b container> --think \
    --adapter qwen=<adapters>/stop-circling

Verification

tests/Amql.Tests/ServerTests.cs, against goldens from transformers and the Von SDK:

  • chat rendering equals HF apply_chat_template with Qwen3.5's real template (6 conversations, thinking on and off, a history turn with a think block, non-ASCII text);
  • greedy generation equals transformers' generate token for token on a GatedDeltaNet + attention model;
  • embeddings equal transformers' mean-pooled, normalised hidden states (1e-5);
  • decisions return the SDK's answers, on /v1 and in the jevai envelope;
  • streamed and non-streamed chat produce the same text; the Responses event sequence; base64 embeddings; the refusals; the API key.

tests/Amql.Tests/ServerToolTests.cs, for tools and reasoning:

  • prompts with tools, calls, parallel calls, tool results, reasoning and history turns equal HF apply_chat_template with Qwen3.5's template (6 conversations, from fixtures/make_tool_chat_golden.py);
  • a reply splits into reasoning, content and typed calls, and fed one character at a time gives the same result without ever sending part of a marker; a cut-off call is content; without tools a <tool_call> is text;
  • calls held to the tools (ToolCallConstraintTests, ServerToolTests): an agent harness's create_file and edit_file calls accepted however split, and refused for an unknown tool or parameter, a parameter given twice, a required one missing, a trailing comma or wrong type in a JSON value, a value outside a string enum, or anything but the close after a value; a random model's forced calls always name the tool with typed arguments; the way to an optional parameter from every point a parameter can open; continue_final_message's prompt;
  • structured output (JsonConstraintTests, ServerToolTests): Hydra's assessment schema accepted however a reply is split and refused for a skipped required property, an early close, an undeclared property, a value outside an enum, a wrong type, a bad escape, text after the value or a code fence; numbers end only when whole; a random model's replies, sampled at temperature 1 with thinking asked for, parse and follow the schema on chat and Responses, on the managed path and the GPU engine;
  • batching: 14 concurrent requests per model (more than a batch, greedy and sampled, thinking on and off, with and without an Entail adapter) equal the same requests one at a time, on the managed path and on the GPU engine (fixtures/qwen-lm-engine, a tiny Qwen3.5 the engine runs); a client that goes away leaves the batch while the others finish; GpuBatchTests hold batched engine logits to each sequence alone on four families;
  • several models: the listing and its defaults, /v1/models/{id}, per-model defaults and request overrides, answers from two models at once equal to their answers alone (this caught the shared device buffers), and the config file;
  • fork and vote (AnswerVoteTests): answers keyed by what they commit to (boxed, an answer line, the last line; numbers and words), the majority over the reply's own answer, ties, the fallback when nothing agrees, cut answers abstaining, the vote field and its refusals. GpuEngine.Fork and the scheduler's side have no test without a device;
  • over HTTP: tool turns reach the prompt token for token, a named tool_choice starts the call, thinking returns reasoning_content, Responses take function items and continue a stored response, and a streamed reasoning item opens and closes.

tests/Amql.Tests/AgentRulesTests.cs, for the stall and check-before-finish rules: what counts as new (a first read, a changed result; not a re-read, nor a search that echoes its pattern over lines already seen), when a streak withholds its tools and when it closes calls, the relation's two forms and its patterns, when a check is owed, and the bound on how often a turn is steered. The regeneration itself is the repeated-call guard's and is not run against a model there.

tests/Amql.Tests/ServerModelRegistryTests.cs, for models at run time and clusters (on the CPU, the tiny fixtures, an in-memory cluster backend that records its calls): a model added by PUT loads on its first request and unloads freeing its engines; "load": true, replaced settings; four concurrent requests wait for one load, with loading visible meanwhile; a failed load reported and tried again; an unload waits for a request in flight, which keeps working on its engines, and a request arriving meanwhile loads the model again; if_idle refused while busy; start models are the same registry; the API key on management routes; every cluster route 501 without an engine; a distributed model formed at load with the given nodes, capacities, context and key, built over the cluster's session, released at unload, local again without its distribution; a cluster that ends leaving its model failed with the reason and the next request forming it again; a cluster that cannot form; keys set, listed by name and absent from every report; memberships listed and left; room for a join taken from the least recently used idle local model, never a busy or distributed one; the config file's distribution.

Not yet checked on a GPU: that unloading a model on a CUDA build returns its device memory. The check: start a server with --model on a container the GPU engine runs, note the device's used memory (nvidia-smi --query-gpu=memory.used --format=csv), POST /v1/models/{id}/unload, and read it again; then load and unload a few times and see that it does not grow.