Module contents
Stage 9 of 9Advanced 110 min

Server, constrained outputs and final benchmark

Wrap the engine in a chat-compatible HTTP server with streaming, cancellation and automaton-constrained decoding, then benchmark latency, throughput, memory and agent performance against references.

After this lesson you can

  • Implement a server with event streaming and request cancellation.
  • Implement an automaton-derived token mask and precompute vocabulary transitions.
  • Run the project 5 agent against the custom server without changing its code.
  • Publish a latency, throughput and memory report against reference implementations.

Before you start

An engine is also a protocol

The continuous batching scheduler accepts work and manages caches, but a client does not speak to its internal structures. It needs an interface that converts messages to tokens, delivers fragments in order and finishes or cancels the request. That conversion is part of correctness: a fast response that loses a tool call or fails to free pages on disconnect is not a correct response.

A server compatible with a chat API declares which subset it implements: route, supported fields, response format and errors. Compatibility does not follow from a route name. For example, the p05-l06 agent uses Ollama’s /api/chat and /api/tags, with tool_calls; it does not automatically consume /v1/chat/completions. Running it unchanged also needs an adapter for that protocol, including model identity and tool semantics. An incorrect chat template can turn the same message list into a different prompt and change output even with the same model.

Serving architecture separates network transport from the engine maintaining requests and caches. The agent loop may request tools repeatedly, and its calling protocol links each result to the conversation. The API must not turn those objects into opaque text when the client expects structured fields.

On the OpenAI-compatible chat route, streaming uses SSE events with data: and a blank-line delimiter, as specified by the event standard. Native Ollama API streaming uses newline-delimited JSON: the adapter must distinguish formats. An event can span multiple network packets, so the client must assemble bytes rather than assume every read is an event. A finish field distinguishes token limit, stop and error. Disconnect triggers cancellation; the scheduler removes the request and frees pages after any kernel still reading them completes. Blocking inference must not monopolize the asynchronous loop: a dedicated worker can receive work and return events with explicit GPU and cache ownership.

The lifecycle has four stages: validate and tokenize the request, admit it to the scheduler, emit zero or more fragments and close with a reason. An invalid request must fail before cache reservation; an admitted request must retain identity as batch composition changes. If a client disconnects after two tokens, those two are already observable and must not be re-emitted during release or recomputation. GPU operations still using a page must finish before it returns to the pool: cancelling a Python task does not automatically stop an already-launched kernel.

A simple architecture assigns engine ownership to one thread and communicates requests through a queue. The network thread waits for events without heavy computation; the engine thread handles admissions, steps and cancellations. Queues must preserve each request ID even when several share a decode step. If a client leaves, the server communicates cancellation to the cache owner and waits for in-flight work to finish safely. A mock-engine test can verify disconnect protocol but does not prove a CUDA implementation frees memory correctly.

Returning a page to the pool lets another request reuse it; it does not mean the CUDA allocator immediately returns memory to the operating system. Record occupied and free pages as well as process-reserved memory. A cancellation test should check that the request disappears, its pages become available and another request can complete, including when disconnect occurs during a long prefill.

Compatibility includes negative cases. An unknown field or unimplemented option must be rejected or documented, not silently ignored as if applied. A tool call must retain name, arguments and its link to the later result; text-only output loses that structure. The template must delimit roles and special tokens of the specific model, including the assistant-response marker, as in chat templates. Changing model or tokenizer requires checking the template again.

A mask that consumes complete tokens

Finite-state constrained decoding maintains state qq after emitted text. For each vocabulary token, simulate all of its bytes or characters from qq: discard it if any transition fails; allow it if the destination can still reach acceptance. Transitions can be precomputed per state and token, as in the index of Willard and Louf. Apply the mask to logits before sampling and update state with the chosen token.

A regular expression can be compiled to a deterministic finite automaton for its language. Constrained decoding adds a sampler layer that translates symbol transitions into token transitions. Special tokens need separate treatment because their meaning need not match their visible characters.

Write δ∗(q,t)\delta^*(q,t) for the extended transition consuming every symbol of token tt. Define it recursively by δ∗(q,ϵ)=q\delta^*(q,\epsilon)=q and δ∗(q,ct)=δ∗(δ(q,c),t)\delta^*(q,ct)=\delta^*(\delta(q,c),t) when the first transition exists. The table stores T[q,i]=δ∗(q,ti)T[q,i]=\delta^*(q,t_i) or an invalid marker. If the destination cannot reach acceptance, that entry is also discarded. Before softmax put −∞-\infty in discarded logits; zero is insufficient because zero can exceed valid negative logits.

Proof

By induction, after each token the state is the one reached by reading the concatenation of all emitted tokens. The base case is the initial state. In the inductive step, applying δ∗\delta^* to the entire token text adds exactly its symbols to the prior reading. If EOS is emitted, the rule requires acceptance, so the concatenation belongs to the language. The proof does not guarantee that EOS is reached or a valid token exists in every state: a vocabulary may be unable to express a continuation even if one exists as a character sequence.

∎
InteractiveOne token can cross several characters

Prefix: ∅

Mask over vocabulary:

{ ✓"ok" ×: ×true ×false ×} ×{"ok": ✓true} ×x ×

EOS is forbidden until an accepting state is reached.

Path
0
StatePrefix
Valid tokens2
Switch the path and move the step. The vocabulary is small and the language contains only two JSON documents. Observe the compound token and when generation can end.

The example has exactly two documents: {"ok":true} and {"ok":false}. The automaton is a trie of their prefixes; every state is coaccessible because every prefix belongs to a complete word. For an arbitrary DFA, compute coaccessibility by reverse traversal from final states, since an existing transition may lead to a dead end. End of sequence (EOS) is allowed only at acceptance and is not treated as repeatable empty text.

A real tokenizer’s strings are not always complete Unicode characters: a token can end midway through a UTF-8 sequence. A safe design uses bytes and a byte automaton, or includes incremental decoder state. Special tokens are not ordinary text. A regular expression restricts a particular regular language; a general JSON schema with arbitrary nesting or cross-field semantic constraints does not simply reduce to a finite DFA. A grammar or bounded subset is needed, and final object validation remains necessary.

Also decide what happens if the budget expires before acceptance. A partial response such as {"ok": is a valid prefix but incomplete JSON: the server must report a length limit and the client must not treat it as schema success. If all allowed logits are nonfinite, softmax defines no valid distribution; return an explicit error instead of selecting an arbitrary token. The mask only ensures membership in the implemented language, not truth or external rules absent from the automaton.

The following lab builds the table for the figure’s finite language. It is an executable mechanism test, not a server benchmark or general JSON Schema implementation.

[ ]Transitions over complete tokensBrowser
words = (b'{"ok":true}', b'{"ok":false}')
prefixes = sorted({w[:i] for w in words for i in range(len(w)+1)}, key=lambda x:(len(x),x))
state = {p:i for i,p in enumerate(prefixes)}
delta = {(state[p],c):state[p+bytes([c])] for p in prefixes for c in range(256) if p+bytes([c]) in state}
vocab = [b'{', b'"ok"', b':', b'true', b'false', b'}', b'{"ok":', b'true}', b'x']

def build_token_transitions(states, delta, vocab):
    result = {}
    for q in states:
        for token_id, token in enumerate(vocab):
            if not token:
                continue
            dest = q
            for byte in token:
                dest = delta.get((dest, byte))
                if dest is None:
                    break
            if dest is not None:
                result[q, token_id] = dest
    return result

table = build_token_transitions(range(len(prefixes)), delta, vocab)
q = state[b'']
for token in (b'{"ok":', b'false', b'}'):
    q = table[q, vocab.index(token)]
assert prefixes[q] == words[1]
assert (state[b''], vocab.index(b'x')) not in table
print('estados:', len(prefixes), 'transiciones de token:', len(table))
print('documento aceptado:', prefixes[q].decode())
print('tabla densa de 200 × 151000 enteros de 16 bits:', 200*151000*2, 'bytes')

A dense table of ∣Q∣ ∣V∣|Q|\,|V| 16-bit destinations occupies 60,400,000 bytes, about 57.60 MiB. Reserve an invalid value, check that all states fit, and account for table construction and transfer. A sparse representation stores only valid transitions, but indices and lookups also consume space; its advantage depends on density and implementation. SGLang studies compressed automata for structured generation among other optimizations.

What the report compares

An engine benchmark report fixes model and revision, tokenizer and template, precision and quantization, context and output length, sampling policy and load conditions. It compares the same prompts and budget, reports failures and cancellations rather than only successful requests, and describes warmup, device and versions. Measure time to first token, total latency, inter-token intervals, tokens and requests per second, peak memory and service-objective compliance; provide percentiles and observation counts. Load testing distinguishes open-loop arrivals from clients that wait for each response.

For the agent, a point rate does not prove equivalence. Use the same tasks and verifier on both servers, retain every failure in the denominator, and report intervals and paired results. Overlapping intervals do not prove equivalence either: fix an acceptable margin and equivalence test before observing results. Measure syntactic validity and schema compliance separately from answer correctness. A finite-sample 100% does not guarantee future validity.

Metrics have different denominators. TTFT begins when the client sends or schedules the request and ends at the first visible token; inter-token intervals exclude prefill and can be summarized per request before aggregation. Output throughput counts delivered tokens over a defined interval, while request throughput includes completed requests and should report queue draining. Peak memory requires stating whether it comes from the process allocator, whole device or operating system; these instruments are not equivalent.

A fair comparison keeps model, revision, quantization, tokenizer, template, context length, limits and sampling fixed. If one implementation uses CPU and the other GPU, the data remain valid observations of two configurations but do not isolate server cost. Retain per-request traces and record errors, cancellations, waits and warmup. Speculative decoding or weight quantization are experimental conditions, not details to change in one column without disclosure.

Using the same integer seed does not force two libraries to generate the same random sequence. They may use different generators, consume numbers in another order or round logits differently. Greedy comparison helps locate implementation differences; with sampling, retain repetitions and pair by task without treating identically named seeds as identical noise. Compare prompt IDs as well as template text: a special token or BOS added on one path changes the model’s input.

File size is not the process memory budget. A quantized GGUF file can be memory-mapped and also converted to a wider representation before execution. For Qwen2.5 3B Q4_K_M used in the project, the index declares 3397103616 values; an FP16 copy takes 2×33971036162\times3397103616 bytes, about 6.33 GiB, before caches, activations or allocator reservations. The quantized file is about 1.96 GiB. The model card states the Qwen Research license. These are storage calculations from dimensions, not measured peaks or a promise the model fits a particular GPU.

For cache, the per-token calculation for 36 layers, two KV heads, dimension 128, two K/V tensors and two bytes per value gives 36×2×2×128×2=3686436\times2\times2\times128\times2=36864 bytes. With 16-position pages, each page for a request occupies 589824 bytes. Actual reservation depends on used pages, last-page fragmentation and temporary batches; if the scheduler copies paged cache into a contiguous attention tensor, that copy also consumes memory. Report observed maximum and sampling method: two samples at start and end may miss the peak.

In an exploratory check of the pinned checkpoint, the custom CUDA engine and llama.cpp on CPU both produced 2+2 is 4. with 39 input and 8 output tokens. For Hello., both responses began alike but the reference ended earlier. This does not establish general parity: the custom engine materializes decompressed FP16 weights, llama.cpp uses quantization, and compute paths and devices differ. A custom-engine test returned a tool-parsing error and CUDA later reported an undiagnosed error; these failures are not valid final benchmark results either.

In another check of the CPU reference, closing streaming after the first fragment triggered a cancellation logged by llama.cpp and later slot release; another request received a response. That verifies that path and run, not custom CUDA-engine cancellation. The agent protocol must record timeouts too: in a partial four-run test, two one-document runs completed the task and two three-document runs timed out at the client. The remaining twelve runs of that reduced test were interrupted and excluded from any success rate.

Lab: server and reproducible comparison

The lab uses Qwen2.5-3B-Instruct-GGUF Q4_K_M at revision 7dabda4d13d513e3e842b20f0d435c732f172cbe, SHA-256 626b4a6678b86442240e33df819e00132d3ba7dddfe1cdc4fbb18e0a9615c62d. The tokenizer comes from revision aa8e72537993ba99e69dfaafa59ed015b17504d1 of Qwen2.5-3B-Instruct. Review the model-card license before using weights. The first download is about 2 GB, excluding environment and cache. The example requires Python, PyTorch with CUDA, Transformers, NumPy, gguf, FastAPI, Uvicorn, aiohttp, requests and psutil; it was tested with PyTorch 2.11.0, Transformers 5.23 and gguf 0.17.1.

Download into one folder the download script, forward pass, scheduler, DFA, server, launcher, optional probe, reference adapter and benchmark. download.py prints verified file and tokenizer paths. The GPU needs substantially more space than the file: the engine decompresses weights to FP16, uses a paged cache and batches decodes by length by copying pages to a temporary batch. It is not an optimized paged-attention kernel and does not implement every Ollama option or JSON schema.

In a terminal run python download.py and use the printed paths in python launch.py --gguf RUTA_GGUF --tokenizer RUTA_TOKENIZADOR --device cuda. The server listens only on 127.0.0.1:11434. In another terminal request GET /api/tags and compare the digest before running the p05 evaluation client: set P05_L07_DIGEST to the SHA above so the original client records actual identity. The tag accepted by this adapter is qwen2.5:3b-instruct; the digest identifies this GGUF, not Ollama’s historical digest. The agent retains its two configurations, 60 tasks and two seeds. Stop the process afterwards to release weights.

For the reference, separately start llama.cpp b9354 with the same file, total context 8192 and two slots at 127.0.0.1:11442; use --n-gpu-layers 99 --ctx-size 8192 --parallel 2 --jinja. Then run python reference.py --gguf RUTA_GGUF --tokenizer RUTA_TOKENIZADOR. The adapter verifies SHA and served path, uses the GGUF template and sends the same IDs to /completion, without adding a tool grammar unused by the custom engine. Do not run both models simultaneously on one GPU without checking memory. Sampling uses temperature and seed, top-p 1 and no repetition penalty; implementations may still consume different random numbers.

To measure, run python benchmark.py --backend propio --pid PID_DEL_MOTOR --output propio.json with the custom server and repeat with --backend llama-cpp --pid PID_DE_LLAMA --output referencia.json during the reference phase. The script warms each server and sends the same four prompts, with at most 32 tokens, first with one client and then two. It records results and failures, TTFT, latency, total duration and sampled process RSS. Retain p05 traces, protocol and versions: do not replace a failure with a later successful response.

In the measured run both used the same RTX 3060 and prompts. Medians over four requests per row are shown, not robust percentiles. The reference was measured while another campaign occupied the GPU; the custom engine was measured in a different phase. Times describe those conditions and do not isolate server cost alone.

EngineClientsTTFT (s)Latency (s)Tokens/s
Custom FP1610.1193.5928.88
Custom FP1620.2526.5799.65
llama.cpp Q410.0790.65249.38
llama.cpp Q420.2780.96766.12

The throughput denominator is wall time for the four requests, including draining; 128 tokens per row were counted and there were no errors in this sample. Sampled peak RSS of the custom process was 1.69 GB in both rows; llama.cpp used 2.39 GB with one client and 2.40 GB with two. RSS was sampled every 0.5 s, can miss peaks, excludes the proxy and is not VRAM. In the longer campaign, observed global GPU peaks were 8456 MiB for the custom phase and 7155 MiB for the reference, with other processes active: these are not exclusive per-model memory figures.

The full agent suite produced 32/120 successes with one document and 37/120 with three on the custom engine, versus 37/120 and 42/120 on the reference. Paired bootstrap by task with 10000 replicates gave custom-minus-reference differences of -4.17 percentage points in both configurations; 95% intervals were [-10.0, 1.67] and [-11.67, 2.5] points. Both exceed the preset ±5-point margin, so this sample does not demonstrate equivalence. The 240 runs per server include search, format, abstention and verdict failures.

For the bounded {"ok":true} / {"ok":false} schema, four custom-engine requests produced 4/4 valid objects; an output interrupted by length must not count as valid. The isolated tool test emitted a malformed object and the server retained it as text without inventing a call. Streaming returned a first event and a later request responded after the connection closed. These observations do not prove every schema, tool or cancellation is correct.

Exercises

Numeric
How many MiB does a dense table of 200 states by 151000 tokens occupy with a 16-bit integer per entry? Use 1 MiB = 1048576 bytes.
Quiz
Why is checking only the first character of a token insufficient?
Quiz
Which comparison best supports interpretation of differences between two servers?
Code
Implement build_token_transitions(states, delta, vocab). delta maps (state, integer byte) to destination state. Return a dictionary from (state, token index) to destination for nonempty tokens fully consumed; omit transitions that fail.
def build_token_transitions(states, delta, vocab):
  pass
Shift+Enter to run
Key idea
The token mask is an extended automaton transition; service validity also depends on protocol, cancellation and reproducible comparison under the same load.