Phase 03/Alternative engines/Structured output, sampling and tool-call decoding
PHASE 03 · Alternative engines

Structured output, sampling and tool-call decoding

0%
9 h6 subtopics3 lessons · 1 required
In plain English

At every step a language model produces a score for each of roughly 150,000 possible next words, and a small piece of code called the sampler picks one. Sampling settings such as temperature decide how adventurous that pick is. Structured output goes further and forbids some choices entirely. If a program needs the answer as a form with fixed fields, the server checks a rulebook (a grammar or JSON schema) at every step and crosses out every word that would break the form, so the model can only write valid output. It is like a crossword with the black squares already drawn. The solver still chooses the letters, but the shape is fixed. Tool calls work the same way; the model writes a function name and arguments in a strict format and the server parses them out. This topic covers how these rulebooks are enforced quickly enough that they do not slow the server.

Why it matters

Structured output and tool calls are what turn a chat model into something an application can rely on, and they sit inside the hottest loop of the engine, because the sampler runs once per token for every request. A slow grammar check or a synchronous CPU step here can cut throughput in half, so engines invest heavily in compiled grammars, precomputed token masks and asynchronous sampling.

Hiring signal

Fireworks lists "fully asynchronous low-latency sampling integrated with structured outputs" as an example project for its performance team, and Baseten's inference performance role expects you to productionize guided generation for structured outputs inside the runtime alongside quantization and speculative decoding.

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, CoreWeave, Crusoe, Databricks, ElevenLabs, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Implement temperature, top-k, top-p, min-p and repetition penalty on raw logits and verify them against a reference implementation.
  • Explain how a JSON schema or regex is compiled into a finite state machine and how per-state token masks are built over the vocabulary.
  • Implement a logit processor that enforces a JSON schema and measure its per-step overhead.
  • Compare the design and cost of Outlines, XGrammar and llguidance and explain where each spends its time.
  • Parse tool calls from model output into validated function name and arguments, and describe how engines expose this through the chat API.
  • Benchmark constrained versus unconstrained decoding in vLLM and attribute the overhead to grammar compilation versus per-step masking.

Key concepts

Logits and the sampler
The unnormalized score per vocabulary entry produced each step; the sampler applies processors, softmax and a random draw to pick one token.
Temperature
Divides logits before softmax; below 1 sharpens the distribution toward the argmax, above 1 flattens it.
Top-k and top-p (nucleus) sampling
Keep only the k highest-probability tokens, or the smallest set whose probabilities sum to p, and renormalize.
Min-p
Keep tokens whose probability is at least min_p times the top token's probability; adapts the cutoff to the step's confidence.
Logit processor
A function applied to the logits before sampling that can add penalties or set disallowed tokens to minus infinity.
Constrained (guided) decoding
Masking every token that would make the output invalid under a grammar, regex or JSON schema, so the output is valid by construction.
Token mask and FSM state
For each state of the compiled grammar automaton, a bitmask over the vocabulary of tokens allowed next; the mask lookup is what runs per step.
Token-boundary problem
Grammars are defined over characters but models emit multi-character tokens, so the compiler must map every token to the character transitions it causes.
Grammar compilation cost
The one-time work to turn a schema into masks; it adds to TTFT unless cached, and is the main cost difference between libraries.
Tool-call parsing
Extracting function name and JSON arguments from model output in a model-specific format (Hermes, Llama 3, Mistral) and returning them as structured API fields.

Subtopics

  1. 1. Sampling parameters and processors

    Order of operations in the sampler; temperature, top-k, top-p, min-p, repetition and presence penalties; greedy as a special case; why sampling is a per-token hot path.

  2. 2. From schema to automaton

    JSON schema to regex to finite state machine; tokenizer vocabulary mapped onto FSM transitions so each state has a precomputed allowed-token set.

  3. 3. Outlines, XGrammar and llguidance

    Outlines precomputes dense per-state masks from regex FSMs; XGrammar uses a pushdown automaton with context-independent token caching for recursive grammars; llguidance uses an Earley parser with lexer-level masks.

  4. 4. Where the cost goes

    Grammar compile time versus per-step mask time; CPU-side mask computation blocking the GPU; mask application as a fused GPU kernel; overlapping mask computation with the forward pass.

  5. 5. Tool calling end to end

    Tool schemas in the chat template, model-specific call formats, parsers in vLLM and SGLang, streaming partial tool calls, and validating arguments against the declared schema.

  6. 6. Structured output in the engines

    response_format and guided_json in vLLM, json_schema and regex in SGLang, backend selection flags, and failure modes such as schema features a backend does not support.

Resources

documentation
paper
repo

Hands-on lessons

L1

Write a JSON-schema logit processor and measure its overhead on CPU

CPU · your Macnotebook150 minrequired

Goal · A transformers LogitsProcessor that forces Qwen2.5-0.5B-Instruct to emit JSON matching a fixed schema, with a measured per-step cost for a naive and a precomputed-mask implementation.

  1. 1pip install torch transformers jsonschema interegular; load Qwen/Qwen2.5-0.5B-Instruct (or gpt2 if memory is tight) in float32 and pick a schema with three fields, for example name (string), age (integer 0-120) and tags (list of strings).
  2. 2Hand-write a regex that matches exactly the JSON documents your schema allows (fixed key order, no whitespace) and compile it to a finite state machine with interegular.
  3. 3Build the vocabulary map once; for every token id, decode it to text and record, for each FSM state, which next state it leads to (or that it is invalid). Store the result as a dict from state to a boolean mask tensor over the vocabulary and cache it to disk.
  4. 4Implement a naive processor that at each step decodes the top-512 candidate tokens, appends each to the partial output and tests the string against the FSM; mask the rest to minus infinity.
  5. 5Implement the precomputed processor that tracks the current FSM state and indexes the mask dict; apply it with logits.masked_fill_.
  6. 6Generate 50 outputs with model.generate for each processor (temperature 0.7, max_new_tokens 64) and validate every output with jsonschema; count failures for an unconstrained baseline too, treating markdown fences or trailing prose as failures.
  7. 7Time the processor call itself with time.perf_counter inside __call__ and accumulate per step; report mean added ms per decode step for each processor.
  8. 8Write three sentences on where the remaining per-step cost comes from and how a GPU engine would hide it.
Deliverable
A notebook with both processors, the validation counts for baseline, naive and precomputed, and a table of added ms per decode step.
Check
Both constrained processors produce 50 of 50 schema-valid outputs while the unconstrained baseline fails at least once; the precomputed mask adds under 2 ms per step on CPU and the naive processor costs at least 10x more per step.
L2

Benchmark guided decoding in vLLM on a T4

Colab T4 · freeexperiment90 minoptional

Goal · A table of TTFT, TPOT and output tokens per second for unconstrained, JSON-schema-constrained and regex-constrained requests against vLLM, with the overhead attributed to compile versus per-step cost.

  1. 1In Colab start vllm serve Qwen/Qwen2.5-0.5B-Instruct --dtype half --max-model-len 2048 and confirm the log names the structured-output backend (xgrammar by default in recent versions).
  2. 2Reuse bench.py from p3-benchmarking-engines-l1; add a flag that attaches response_format with type json_schema and your schema from lesson l1 to every request.
  3. 3Run 100 requests at concurrency 16 unconstrained, then constrained with one shared schema, then constrained with 100 distinct schemas (vary a field name per request) to defeat the grammar cache.
  4. 4Record TTFT p50/p99, TPOT p50 and total output tokens per second for each of the three runs; validate every constrained output with jsonschema.
  5. 5Compare the shared-schema and distinct-schema TTFT: the difference is grammar compilation; compare TPOT: the difference is per-step masking.
  6. 6If your vLLM version exposes a backend flag (for example --structured-outputs-config or --guided-decoding-backend), rerun the distinct-schema case with a second backend such as outlines or guidance and add a row.
Deliverable
A results table with the three (or more) rows and a short paragraph attributing overhead to compile versus per-step work.
Check
Zero schema failures in the constrained runs; distinct-schema TTFT p50 is higher than shared-schema TTFT p50; constrained TPOT is within 25 percent of unconstrained TPOT at concurrency 16.
Fallback
Run the same comparison against the transformers processors from lesson l1 on CPU at concurrency 1 and report compile time (building the mask dict) separately from per-step time.
L3

Sampling from scratch and tool-call parsing

CPU · your Macnotebook90 minoptional

Goal · Your own temperature, top-k, top-p and min-p implementations verified against transformers, plus a parser that turns Qwen2.5 tool-call output into validated function calls.

  1. 1Write sample(logits, temperature, top_k, top_p, min_p) in PyTorch that returns the filtered log-probabilities and a sampled token.
  2. 2Verify top-k and top-p against transformers' TopKLogitsWarper and TopPLogitsWarper on 1,000 random logit vectors of size 151,936 (Qwen vocabulary) by comparing the kept-token sets with torch.equal.
  3. 3Measure the entropy of the filtered distribution for temperatures 0.2, 0.7, 1.0 and 1.5 on real Qwen2.5-0.5B logits for one prompt and plot it.
  4. 4Define two tool schemas (get_weather with a city argument, search with query and k arguments) and pass them through tokenizer.apply_chat_template with tools=; inspect the rendered prompt.
  5. 5Generate 20 responses to prompts that require a tool and write a parser for the Hermes-style <tool_call> JSON blocks the model emits; validate arguments against the tool schema with jsonschema.
  6. 6Report how many of the 20 responses parsed and validated, and classify each failure (malformed JSON, wrong function name, missing argument).
Deliverable
A notebook with the sampler tests, the entropy plot and the tool-call parse report.
Check
Kept-token sets match transformers on all 1,000 vectors for top-k and top-p; entropy rises monotonically with temperature; at least 16 of 20 tool calls parse and validate, with every failure classified.

Build your own

Build your own constrained decoder

PythonCPU · your Mac~8 h

From a regex or JSON schema to a per-step token mask, via a finite-state machine over bytes and a vocabulary trie, plugged into generation as a logit processor and timed against Outlines and XGrammar.

The real thing: github.com/mlc-ai/xgrammar ↗

How you know a stage passes

Write tests/test_constrained.py first. Early stages compare your automaton with Python's re.fullmatch on string corpora; middle stages generate with Qwen2.5-0.5B-Instruct on CPU and assert that 100 percent of outputs match the regex or validate against the schema with jsonschema; late stages are timing tests with a budget. Run `pytest -q`; a stage passes when its tests pass and earlier tests still pass.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01a regex to FSM compiler
    Compile a regex subset (literals, classes, quantifiers, alternation, groups) into a deterministic FSM over bytes, using interegular or your own Thompson construction plus subset construction.
    test · For 5 regexes and 50 strings each, accepts(s) equals bool(re.fullmatch(pattern, s)) on all 250 cases.
  2. 02token-level transitions
    For each FSM state, compute the set of vocabulary tokens whose bytes can be consumed from that state and the resulting state, cached per state.
    test · For the Qwen2.5 vocabulary every allowed token leads to a live state, no live state has an empty allowed set, and the precompute time for a phone-number regex is printed.
  3. 03a logit processor
    A transformers LogitsProcessor that sets disallowed token logits to -inf and advances the FSM state per sequence after each sampled token, handling EOS only in accepting states.
    test · 100 of 100 greedy and sampled generations with Qwen2.5-0.5B match a phone-number regex, while the unconstrained baseline fails on at least one of the same prompts.
  4. 04JSON schema to regex
    Translate a JSON schema subset (object with required keys, string, integer, number, boolean, enum, array of primitives) into a regex that your compiler accepts.
    test · 50 generations for each of 3 schemas all json.loads and validate with jsonschema, and the generated regex for a 3-key object is under 1 KB.
  5. 05a vocabulary trie fast path
    Build a byte trie over the vocabulary so the allowed set for a state is found by walking the trie against the FSM instead of scanning all 150k tokens.
    test · Per-state mask computation is at least 10x faster than the scan, and the allowed sets from both methods are identical on 100 random reachable states.
  6. 06measure against the real libraries
    Time per-step mask application and one-off compile for your decoder, Outlines and XGrammar on the same schema and model.
    test · README has a table of compile time and per-step overhead for the three; your per-step overhead after precompute is under 2 ms on your CPU, with the actual number reported.

Knowledge check

QWhy can constrained decoding slow a server even though masking logits is a cheap tensor operation?

The mask must be computed per request per step from the grammar state, often on the CPU; if that work is synchronous it stalls the GPU step for the whole batch, and compiling a new grammar adds to TTFT.

QWhat is the token-boundary problem in grammar-constrained decoding?

Grammars are written over characters but the model emits multi-character tokens, so the compiler must determine for each token whether the whole string it adds is consistent with the grammar from the current state.

QHow does XGrammar reduce per-step cost for recursive grammars like JSON?

It classifies most tokens as context-independent for a given automaton state and caches their mask, so only the small context-dependent remainder is checked at run time against the pushdown automaton stack.

QWhat does min-p do that top-p does not?

Min-p sets the cutoff relative to the top token's probability, so it keeps more candidates when the model is uncertain and fewer when it is confident, instead of a fixed cumulative mass.

QWhere does tool-call parsing live in an engine, and why is it model-specific?

In the API layer after detokenization (with streaming-aware partial parsing); each model family was trained to emit a different call format (Hermes tags, Llama 3 headers, Mistral tokens), so the parser must match the chat template.

Completion

  • All 6 subtopics marked done
  • All 1 required lessons done
  • All subtopics marked completed.
  • Lesson l1 notebook saved with 50 of 50 valid outputs for both processors and the per-step overhead table.
  • Can explain, with a drawing, how a schema becomes per-state token masks and where the compile and per-step costs land in the serving pipeline.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →