Topic 5
Where structure comes from
AI Engineering (Ch. 2, "Structured Outputs") lists where in the stack you can push a model towards a format: prompting, post-processing, test time compute, constrained sampling and finetuning. The first three, it says, "are more like bandages"; "for intensive treatment, you need constrained sampling and finetuning."
- Prompting: instructions and examples (the earlier pages). No guarantee, and "a few percentage points of invalid model outputs can still be unacceptable for many applications."
- Post-processing: a script fixes the mistakes the model keeps making. LinkedIn's defensive YAML parser took correct YAML outputs from 90% to 99.99% (Bottaro and Ramgopal, 2020, as cited). It only works when mistakes are small and easy to fix.
- Test time compute: keep generating until an output fits.
- Constrained sampling: at each step, remove the tokens the format doesn't allow, then sample from the rest.
- Finetuning on examples in your format: "the most effective and general approach", much more reliable than prompting but still no guarantee. A classifier head can guarantee one of the classes.
Predict first
Scroll sideways to see the whole diagram
GPT-2 scores every token in its vocabulary. Left alone, its most likely next token is “ about”, not a planet.
Text version
- GPT-2 scores every token in its vocabulary. Left alone, its most likely next token is “ about”, not a planet.
- Constrained sampling filters the scores before sampling: tokens the format doesn't allow are removed. A grammar decides what is allowed at each step.
- Only planet names can come out now, and their probabilities are rescaled to sum to 1. The output is always a valid label, but greedy decoding picks “ Earth” (24.8%) over “ Jupiter” (23.7%). The constraint fixes the form, not the content.
Real next-token logits of gpt2 (transformers 5.20.2) for “The largest planet in our solar system is”, from lib/labs/data/sampling.json; probabilities at temperature 1, computed by constrain() in lib/labs/structured.ts.
The scores are GPT-2's real logits from Module 01's sampling lesson; we applied the filter to those recorded scores rather than rerunning the model. For JSON the filter is a grammar ("after { you can't have another { unless it's part of a string"). The book's costs: every format needs its own grammar, building one is nontrivial, and checking it can add latency.
Quick check