15  Constrained decoding

You will learn:

A model that writes a program can write one that does not run: a stray word, a missing parenthesis, a code fence. Chapters Chapter 3 and Chapter 4 stopped short of fixing this. A grammar does: at every step, it lists the tokens that can continue a valid program, and the decoder gives every other token probability zero. The model still chooses, among the tokens that are allowed. This chapter runs the grammar on the untuned and the fine-tuned model, with the DSL and with Python.

15.1 The grammars

The DSL grammar is that of Chapter 3 in the EBNF of the xgrammar library. The Python grammar describes the forms that to_python writes (Chapter 14): assignments to v<k>, then ans = …, with numbers, names, the operators + - * / ** > and parentheses. It is narrower than the safe evaluator, so a model that follows it cannot leave the evaluator’s subset. Each has a bounded variant that limits a number to the digits the gold programs use: a grammar guarantees syntax and not termination, and with an unbounded number rule a model can keep writing digits up to the generation limit.

Code
from convfinqa import grammars

print(grammars.python_grammar().strip())
root       ::= (assignment "\n")* final
assignment ::= "v" [0-9]+ " = " comparison
final      ::= "ans = " comparison
comparison ::= sum (" > " sum)?
sum        ::= product ((" + " | " - ") product)*
product    ::= power ((" * " | " / ") power)*
power      ::= atom (" ** " atom)?
atom       ::= number | "-" number | "v" [0-9]+ | "(" comparison ")" | "(-" number ")"
number     ::= [0-9]+ ("." [0-9]+)? | "." [0-9]+
Code
import pandas as pd
from transformers import AutoTokenizer

from convfinqa.artifacts import artifact, get
from convfinqa.constrained import compile_grammar, grammar_accepts
from convfinqa.dsl import python_format

tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-4B-Instruct-2507")
dsl = compile_grammar(tok, grammars.dsl_grammar(), vocab_size=151936)
py = compile_grammar(tok, grammars.python_grammar(), vocab_size=151936)

CASES = {
    "subtract(5, 3), divide(#0, 3)": dsl,
    "subtract(5, 3), divide(#0, 3) because": dsl,
    "```add(1, 2)```": dsl,
    "ans = (5 - 3) / 3": py,
    "v0 = 5 - 3\nans = v0 / 3": py,
    "ans = round(2.567, 1)": py,
    "```python\nans = 1 + 2\n```": py,
    "The answer is ans = 2": py,
}
pd.DataFrame([
    {
        "text": text.replace("\n", "; "),
        "grammar": "DSL" if g is dsl else "Python",
        "accepted": grammar_accepts(g, text),
    }
    for text, g in CASES.items()
]).set_index("text")
grammar accepted
text
subtract(5, 3), divide(#0, 3) DSL True
subtract(5, 3), divide(#0, 3) because DSL False
```add(1, 2)``` DSL False
ans = (5 - 3) / 3 Python True
v0 = 5 - 3; ans = v0 / 3 Python True
ans = round(2.567, 1) Python False
```python; ans = 1 + 2; ``` Python False
The answer is ans = 2 Python False

15.2 One decoding step

The mask is a list of the tokens that may come next. To see it, we feed a prefix to the grammar and ask which of the model’s 151,936 output tokens remain possible.

Code
import torch
import xgrammar as xgr

VOCAB = 151936


def allowed_tokens(compiled, prefix: str) -> list[int]:
    """The ids of the tokens that may follow `prefix` under the grammar."""
    matcher = xgr.GrammarMatcher(compiled, terminate_without_stop_token=True)
    assert prefix == "" or matcher.accept_string(prefix)
    mask = xgr.allocate_token_bitmask(1, VOCAB)
    matcher.fill_next_token_bitmask(mask)
    logits = torch.zeros(1, VOCAB)
    xgr.apply_token_bitmask_inplace(logits, mask)
    return torch.nonzero(torch.isfinite(logits[0])).flatten().tolist()


STEPS = {
    "start of the answer": "",
    "after `subtract(`": "subtract(",
    "after `subtract(5, 3), `": "subtract(5, 3), ",
}
step_ids = {name: allowed_tokens(dsl, prefix) for name, prefix in STEPS.items()}
pd.DataFrame([
    {
        "position": name,
        "tokens allowed": len(ids),
        "a few of them": " ".join(repr(tok.decode([i])) for i in ids[:12]),
    }
    for name, ids in step_ids.items()
]).set_index("position")
tokens allowed a few of them
position
start of the answer 39 '-' '.' '0' '1' '2' '3' '4' '5' '6' '7' '8' '9'
after `subtract(` 19 '#' '-' '.' '0' '1' '2' '3' '4' '5' '6' '7' '8'
after `subtract(5, 3), ` 26 'a' 'd' 'e' 'g' 'm' 's' 'ex' 'ad' 'div' 'add' ...
Code
#HEAVY
# the first token of the untuned model's answer to the first turn of the
# first conversation, without examples and without a grammar
first = next(get("untuned_val_e0p_0_pred").jsonl("predictions.jsonl"))
first_token = tok.encode(first["output"], add_special_tokens=False)[0]
assert first_token not in step_ids["start of the answer"]
assert len(step_ids["start of the answer"]) < 100

At the start of an answer, 39 tokens are allowed: digits, a minus sign, a point, and the first letters of the operators and of const_. The untuned model’s own first token for the first turn, without examples, is ‘```’, the start of a code fence. It is not among them.

NoteUnder the hood: what the processor does to the logits

The model produces one score (logit) per token. Before the next token is chosen, the processor sets the score of every token that the grammar does not allow to minus infinity. After the softmax those tokens have probability zero and the others share the whole probability between them, in the proportions the model gave them. Greedy decoding then picks the allowed token with the highest score. The model’s preferences among valid continuations are untouched, and this is why a grammar can only repair syntax: it never makes the model prefer the correct operation.

The matcher keeps the parse state, so the mask is recomputed after every token. xgrammar prechecks the tokens whose validity does not depend on the parse stack and checks only the others at run time (Dong et al. 2024).

15.3 The code

A run with a grammar is the run without one, with the logits processor added: the same prompts, the same greedy decoding, one prompt at a time. convfinqa.constrained_eval holds the generator. The name of a run says which bound the number rule has (free or bounded). The runs without a grammar are the ones of Chapter 11, Chapter 14 and Chapter 12, and are not repeated.

Code
@artifact(
    "constrained_untuned_{split}_{variant}_{seed}_{mode}_{bounds}",
    deps=["train_val_split", "eval_turns", "example_sets"],
    files=["configs/baseline.json"],
    heavy=True,
)
def build_constrained_untuned(
    out, deps, files, *, split: str, variant: str, seed: int, mode: str,
    bounds: str
):
    """Generate the untuned model's DSL answer for every turn, under the DSL
    grammar.

    Args:
        out: Output directory; `predictions.jsonl` is written to it.
        deps: The conversations and the example sets.
        files: `configs/baseline.json` (the model, the system messages).
        split: `val`, or `dev` once `configs/FROZEN` exists.
        variant: A prompt variant of `convfinqa.prompts.VARIANTS`.
        seed: The example set; 0 for a variant with no examples.
        mode: `gold` or `pred`, the history of the earlier turns.
        bounds: `free` or `bounded`, the number rule of the grammar.
    """
    import json
    import time

    from convfinqa.constrained_eval import generate_with_grammar
    from convfinqa.grammars import dsl_grammar
    from convfinqa.prompts import parse_variant
    from convfinqa.tuned_eval import split_conversations

    cfg = files["configs/baseline.json"].json()
    n_examples, kind = parse_variant(variant)
    if n_examples == 0 and seed != 0:
        raise ValueError(
            "a variant with no examples has no example set: use seed 0"
        )
    if bounds not in ("free", "bounded"):
        raise ValueError(f"bounds must be 'free' or 'bounded', not {bounds!r}")
    convs = split_conversations(
        split,
        list(deps["train_val_split"].jsonl("val.jsonl")),
        list(deps["eval_turns"].jsonl("dev.jsonl")),
    )
    examples = []
    if n_examples:
        wanted = deps["example_sets"].json(
            "sets.json"
        )["sets"][str(seed)][:n_examples]
        pool = {
            c["id"]: c
            for c in deps["train_val_split"].jsonl("train_fit.jsonl")
        }
        examples = [pool[i] for i in wanted]
    start, done = time.perf_counter(), 0
    with open(out / "predictions.jsonl", "w") as f:
        def sink(row):
            nonlocal done
            f.write(json.dumps({
                k: v for k, v in row.items() if k != "seconds"
            }) + "\n")
            f.flush()
            done += 1
            if done % 50 == 0:
                print(
                    f"{done} turns, {time.perf_counter() - start:.0f} s",
                    flush=True
                )

        generate_with_grammar(
            cfg, convs, examples, system=cfg["system"][kind],
            grammar=dsl_grammar(bounds == "bounded"),
            max_new_tokens=cfg["max_new_tokens"], mode=mode, sink=sink,
        )
    print(f"done: {done} turns in {time.perf_counter() - start:.0f} s")


@artifact(
    "constrained_python_untuned_{split}_{variant}_{seed}_{mode}_{bounds}",
    deps=["train_val_split", "eval_turns", "example_sets"],
    files=["configs/baseline.json"],
    heavy=True,
)
def build_constrained_python_untuned(
    out, deps, files, *, split: str, variant: str, seed: int, mode: str,
    bounds: str
):
    """Generate the untuned model's Python answer for every turn, under the Python
    grammar.

    Args:
        out: Output directory; `predictions.jsonl` is written to it.
        deps: The conversations and the example sets.
        files: `configs/baseline.json` (the model).
        split: `val`, or `dev` once `configs/FROZEN` exists.
        variant: `e0` (no examples) or `e3` (three examples).
        seed: The example set; 0 for `e0`.
        mode: `gold` or `pred`, the history of the earlier turns.
        bounds: `free` or `bounded`, the number rule of the grammar.
    """
    import json
    import time

    from convfinqa.constrained_eval import generate_with_grammar
    from convfinqa.grammars import python_grammar
    from convfinqa.python_eval import (
        MAX_NEW_TOKENS, SYSTEM_PYTHON, python_conversation
    )
    from convfinqa.tuned_eval import split_conversations

    cfg = files["configs/baseline.json"].json()
    if variant not in ("e0", "e3"):
        raise ValueError(f"variant must be 'e0' or 'e3', not {variant!r}")
    n_examples = int(variant[1:])
    if n_examples == 0 and seed != 0:
        raise ValueError(
            "a variant with no examples has no example set: use seed 0"
        )
    if bounds not in ("free", "bounded"):
        raise ValueError(f"bounds must be 'free' or 'bounded', not {bounds!r}")
    convs = split_conversations(
        split,
        list(deps["train_val_split"].jsonl("val.jsonl")),
        list(deps["eval_turns"].jsonl("dev.jsonl")),
    )
    examples = []
    if n_examples:
        wanted = deps["example_sets"].json(
            "sets.json"
        )["sets"][str(seed)][:n_examples]
        pool = {
            c["id"]: c
            for c in deps["train_val_split"].jsonl("train_fit.jsonl")
        }
        examples = [pool[i] for i in wanted]
    start, done = time.perf_counter(), 0
    with open(out / "predictions.jsonl", "w") as f:
        def sink(row):
            nonlocal done
            f.write(json.dumps({
                k: v for k, v in row.items() if k != "seconds"
            }) + "\n")
            f.flush()
            done += 1
            if done % 50 == 0:
                print(
                    f"{done} turns, {time.perf_counter() - start:.0f} s",
                    flush=True
                )

        generate_with_grammar(
            cfg, [python_conversation(c) for c in convs],
            [python_conversation(c) for c in examples],
            system=SYSTEM_PYTHON, grammar=python_grammar(bounds == "bounded"),
            max_new_tokens=MAX_NEW_TOKENS, mode=mode, sink=sink,
        )
    print(f"done: {done} turns in {time.perf_counter() - start:.0f} s")


@artifact(
    "constrained_tuned_{split}_{run}_{seed}_{mode}_{bounds}",
    deps=[
        "lora_{run}_{seed}", "train_config_{run}",
        "train_val_split", "eval_turns",
    ],
    heavy=True,
)
def build_constrained_tuned(
    out, deps, *, split: str, run: str, seed: int, mode: str, bounds: str
):
    """Generate the DSL adapter's answer for every turn, under the DSL grammar.

    Args:
        out: Output directory; `predictions.jsonl` is written to it.
        deps: The adapter, its settings and the conversations.
        split: `val`, or `dev` once `configs/FROZEN` exists.
        run: The training run (`main`).
        seed: The training seed of the adapter.
        mode: `gold` or `pred`, the history of the earlier turns.
        bounds: `free` or `bounded`, the number rule of the grammar.
    """
    import json
    import time

    from convfinqa.constrained_eval import generate_with_grammar
    from convfinqa.formatting import SYSTEM_PROMPT
    from convfinqa.grammars import dsl_grammar
    from convfinqa.tuned_eval import MAX_NEW_TOKENS, split_conversations

    cfg = deps[f"train_config_{run}"].json("config.json")
    if bounds not in ("free", "bounded"):
        raise ValueError(f"bounds must be 'free' or 'bounded', not {bounds!r}")
    convs = split_conversations(
        split,
        list(deps["train_val_split"].jsonl("val.jsonl")),
        list(deps["eval_turns"].jsonl("dev.jsonl")),
    )
    start, done = time.perf_counter(), 0
    with open(out / "predictions.jsonl", "w") as f:
        def sink(row):
            nonlocal done
            f.write(json.dumps({
                k: v for k, v in row.items() if k != "seconds"
            }) + "\n")
            f.flush()
            done += 1
            if done % 50 == 0:
                print(
                    f"{done} turns, {time.perf_counter() - start:.0f} s",
                    flush=True
                )

        generate_with_grammar(
            cfg, convs, [], system=SYSTEM_PROMPT,
            grammar=dsl_grammar(bounds == "bounded"),
            max_new_tokens=MAX_NEW_TOKENS, mode=mode,
            adapter=deps[f"lora_{run}_{seed}"].path / "adapter", sink=sink,
        )
    print(f"done: {done} turns in {time.perf_counter() - start:.0f} s")

The outputs are scored as before: the DSL runs by the executor, the Python runs by the safe evaluator.

Code
@artifact(
    "scores_constrained_untuned_{split}_{variant}_{seed}_{mode}_{bounds}",
    deps=[
        "constrained_untuned_{split}_{variant}_{seed}_{mode}_{bounds}",
        "eval_turns",
    ],
)
def build_scores_constrained_untuned(
    out, deps, *, split: str, variant: str, seed: int, mode: str, bounds: str
):
    """Execute and score the outputs of `constrained_untuned_…`."""
    import json

    from convfinqa.evaluate import score_rows, summarize
    from convfinqa.program_match import add_program_match

    name = f"constrained_untuned_{split}_{variant}_{seed}_{mode}_{bounds}"
    rows = list(deps[name].jsonl("predictions.jsonl"))
    turns = list(deps["eval_turns"].jsonl(f"{split}_turns.jsonl"))
    scores = add_program_match(score_rows(rows, turns), rows, turns)
    (out / "scores.jsonl").write_text(
        "".join(json.dumps(s) + "\n" for s in scores)
    )
    (out / "summary.json").write_text(
        json.dumps(summarize(scores), indent=2)
    )


@artifact(
    "scores_constrained_tuned_{split}_{run}_{seed}_{mode}_{bounds}",
    deps=[
        "constrained_tuned_{split}_{run}_{seed}_{mode}_{bounds}", "eval_turns",
    ],
)
def build_scores_constrained_tuned(
    out, deps, *, split: str, run: str, seed: int, mode: str, bounds: str
):
    """Execute and score the outputs of `constrained_tuned_…`."""
    import json

    from convfinqa.evaluate import score_rows, summarize
    from convfinqa.program_match import add_program_match

    name = f"constrained_tuned_{split}_{run}_{seed}_{mode}_{bounds}"
    rows = list(deps[name].jsonl("predictions.jsonl"))
    turns = list(deps["eval_turns"].jsonl(f"{split}_turns.jsonl"))
    scores = add_program_match(score_rows(rows, turns), rows, turns)
    (out / "scores.jsonl").write_text(
        "".join(json.dumps(s) + "\n" for s in scores)
    )
    (out / "summary.json").write_text(
        json.dumps(summarize(scores), indent=2)
    )


@artifact(
    "scores_constrained_python_untuned_{split}_{variant}_{seed}_{mode}_{bounds}",
    deps=[
        "constrained_python_untuned_{split}_{variant}_{seed}_{mode}_{bounds}",
        "eval_turns",
    ],
)
def build_scores_constrained_python_untuned(
    out, deps, *, split: str, variant: str, seed: int, mode: str, bounds: str
):
    """Execute and score the outputs of `constrained_python_untuned_…`."""
    import json

    from convfinqa.evaluate import summarize
    from convfinqa.python_eval import score_python_rows

    name = f"constrained_python_untuned_{split}_{variant}_{seed}_{mode}_{bounds}"
    rows = list(deps[name].jsonl("predictions.jsonl"))
    turns = list(deps["eval_turns"].jsonl(f"{split}_turns.jsonl"))
    scores = score_python_rows(rows, turns)
    (out / "scores.jsonl").write_text(
        "".join(json.dumps(s) + "\n" for s in scores)
    )
    (out / "summary.json").write_text(
        json.dumps(summarize(scores), indent=2)
    )

15.4 The same prompt, with the grammar off and on

Validation turns only (Chapter 10), predicted history, greedy, one attempt, an invalid answer counts as wrong. Each row is one prompt run twice, with the same decoding and the grammar on or off, on the same turns, so the difference is paired. The grammar is the unbounded one (free); Section 15.8 compares it with the bounded one.

Code
#HEAVY
import re

from convfinqa.stats import bootstrap_accuracy, paired_difference

SYSTEMS = {
    "untuned DSL": (
        get("scores_untuned_val_e3p_0_pred"),
        get("scores_constrained_untuned_val_e3p_0_pred_free"),
    ),
    "untuned Python": (
        get("scores_python_untuned_val_e3_0_pred"),
        get("scores_constrained_python_untuned_val_e3_0_pred_free"),
    ),
    "fine-tuned DSL": (
        get("scores_tuned_val_main_0_pred"),
        get("scores_constrained_tuned_val_main_0_pred_free"),
    ),
}
off = {k: list(v[0].jsonl("scores.jsonl")) for k, v in SYSTEMS.items()}
on = {k: list(v[1].jsonl("scores.jsonl")) for k, v in SYSTEMS.items()}
off_sum = {k: v[0].json("summary.json") for k, v in SYSTEMS.items()}
on_sum = {k: v[1].json("summary.json") for k, v in SYSTEMS.items()}
off_ci = {k: bootstrap_accuracy(v) for k, v in off.items()}
on_ci = {k: bootstrap_accuracy(v) for k, v in on.items()}
gain = {k: paired_difference(on[k], off[k]) for k in SYSTEMS}
n_val = off_sum["untuned DSL"]["n"]
assert all(s["n"] == n_val for s in [*off_sum.values(), *on_sum.values()])

pct = lambda x: f"{100 * x:.1f}%"
pts = lambda x: f"{100 * x:+.1f}"
rows = []
for k in SYSTEMS:
    for label, ci, summary in [
        ("off", off_ci, off_sum), ("on", on_ci, on_sum)
    ]:
        rows.append({
            "system": k,
            "grammar": label,
            "accuracy": pct(ci[k]["accuracy"]),
            "95% interval": f"[{pct(ci[k]['low'])}, {pct(ci[k]['high'])}]",
            "invalid": pct(summary[k]["invalid_rate"]),
            "hit the limit": pct(summary[k]["truncated"] / n_val),
        })
pd.DataFrame(rows).set_index(["system", "grammar"])
accuracy 95% interval invalid hit the limit
system grammar
untuned DSL off 57.2% [53.1%, 61.2%] 16.4% 1.5%
on 60.4% [56.2%, 64.5%] 1.3% 0.6%
untuned Python off 64.5% [60.2%, 68.6%] 8.9% 1.4%
on 68.4% [64.3%, 72.2%] 0.0% 0.0%
fine-tuned DSL off 83.7% [79.7%, 87.4%] 0.0% 0.0%
on 83.8% [79.8%, 87.5%] 0.0% 0.0%
Code
#HEAVY
# the grammar removes invalid answers from the untuned models ...
for k in ["untuned DSL", "untuned Python"]:
    assert on_sum[k]["invalid_rate"] < off_sum[k]["invalid_rate"], k
assert on_sum["fine-tuned DSL"]["invalid_rate"] \
    <= off_sum["fine-tuned DSL"]["invalid_rate"]
# ... but the untuned models gain less than half of what they stop getting
# wrong by being invalid; the fine-tuned model gains nothing worth the name
for k in ["untuned DSL", "untuned Python"]:
    assert gain[k]["low"] > 0, k
    dropped = off_sum[k]["invalid_rate"] - on_sum[k]["invalid_rate"]
    assert gain[k]["difference"] < dropped / 2, k
assert gain["fine-tuned DSL"]["difference"] < 0.01
pd.DataFrame([
    {
        "system": k,
        "grammar on − off (points)": pts(gain[k]["difference"]),
        "95% paired interval":
            f"[{pts(gain[k]['low'])}, {pts(gain[k]['high'])}]",
        "invalid answers removed (points)":
            f"{100 * (off_sum[k]['invalid_rate'] - on_sum[k]['invalid_rate']):.1f}",
    }
    for k in SYSTEMS
]).set_index("system")
grammar on − off (points) 95% paired interval invalid answers removed (points)
system
untuned DSL +3.3 [+1.7, +5.1] 15.0
untuned Python +3.8 [+2.2, +5.7] 8.9
fine-tuned DSL +0.1 [+0.0, +0.3] 0.0

The grammar takes the invalid rate of the untuned DSL from 16.4% to 1.3%, and that of untuned Python from 8.9% to 0.0%. Accuracy rises by +3.3 points for the DSL and +3.8 for Python, and both paired intervals exclude zero. That is less than half of the invalid output that disappeared, so most of the turns the grammar rescues are valid programs that are still wrong. The fine-tuned model has almost no invalid answers to start with (0.0% without the grammar, 0.0% with it), and the grammar moves its accuracy by +0.1 points.

15.4.1 Number turns and program turns

A number turn is one whose gold program is a single number from the page; a program turn has operations (Chapter 2).

Code
#HEAVY
KINDS = ["number", "program"]
by_kind = {
    (k, state): summary[k]["by_number_turn"]
    for k in SYSTEMS
    for state, summary in [("off", off_sum), ("on", on_sum)]
}
pd.DataFrame([
    {
        "system": k,
        "kind of turn": kind,
        "turns": by_kind[(k, "off")][kind]["n"],
        "grammar off": pct(by_kind[(k, "off")][kind]["accuracy"]),
        "grammar on": pct(by_kind[(k, "on")][kind]["accuracy"]),
    }
    for k in SYSTEMS
    for kind in KINDS
]).set_index(["system", "kind of turn"])
turns grammar off grammar on
system kind of turn
untuned DSL number 398 78.9% 79.9%
program 727 45.3% 49.8%
untuned Python number 398 82.2% 83.4%
program 727 54.9% 60.1%
fine-tuned DSL number 398 86.2% 86.2%
program 727 82.4% 82.5%
Code
#HEAVY
def kind_gain(k, kind):
    return (
        by_kind[(k, "on")][kind]["accuracy"]
        - by_kind[(k, "off")][kind]["accuracy"]
    )


for k in ["untuned DSL", "untuned Python"]:
    assert kind_gain(k, "program") > kind_gain(k, "number") > 0, k

For both untuned systems the gain is larger on program turns (+4.5 points for the DSL, +5.2 for Python) than on number turns (+1.0 and +1.3). A number turn is a single number and has almost no syntax to get wrong; a program has brackets, commas and references to earlier steps.

15.5 What the grammar cannot fix

How far does an untuned model with the best prompt and a grammar get towards the fine-tuned one? The grammar only repairs syntax, so there is a ceiling: an untuned model whose every invalid answer became a correct one would score its accuracy plus its invalid rate.

Code
#HEAVY
tuned_off = off_ci["fine-tuned DSL"]["accuracy"]
tuned_on = on_ci["fine-tuned DSL"]["accuracy"]
gap = {}
for k in ["untuned DSL", "untuned Python"]:
    start = off_ci[k]["accuracy"]
    gap[k] = {
        "ceiling": start + off_sum[k]["invalid_rate"],
        "with grammar": on_ci[k]["accuracy"],
        "total gap": tuned_off - start,
        "closed": (on_ci[k]["accuracy"] - start) / (tuned_off - start),
    }
    assert gap[k]["ceiling"] < tuned_off, k
vs_tuned = paired_difference(
    on["fine-tuned DSL"], on["untuned DSL"]
)
assert vs_tuned["low"] > 0
pd.DataFrame([
    {
        "system": k,
        "no grammar": pct(off_ci[k]["accuracy"]),
        "ceiling": pct(g["ceiling"]),
        "with grammar": pct(g["with grammar"]),
        "fine-tuned, no grammar": pct(tuned_off),
        "share of the gap closed": pct(g["closed"]),
    }
    for k, g in gap.items()
]).set_index("system")
no grammar ceiling with grammar fine-tuned, no grammar share of the gap closed
system
untuned DSL 57.2% 73.5% 60.4% 83.7% 12.4%
untuned Python 64.5% 73.4% 68.4% 83.7% 19.9%

For the DSL, the ceiling is 73.5%, below the fine-tuned model’s 83.7%; for Python it is 73.4%. Even a grammar that made every invalid answer correct could not reach the fine-tuned model. The grammar closes 12.4% of the gap for the DSL and 19.9% for Python (the Python gap is measured against the same fine-tuned DSL model). With the grammar on both, the fine-tuned DSL model is +23.4 points ahead of the untuned one (interval [+19.7, +27.1]).

What is left is choosing the operations and the numbers. In the error kinds of Chapter 11, the untuned DSL with the grammar still has 260 turns with different operations from the gold program, 79 with the same operations and different numbers, and 91 with the same shape and a different answer. The fine-tuned model has 62, 73 and 47. The classifier compares the operations first, so a turn with the wrong operations and the wrong numbers is counted once, as wrong operations. What fine-tuning changes most is the first of these.

15.6 Description or enforcement?

The plain system message names no syntax rules for the DSL; the description message spells them out. They are two ways to tell the model the syntax, and the grammar is a third. The 2×2 below, with three examples, separates them.

Code
#HEAVY
CELLS = {
    ("plain", "off"): get("scores_untuned_val_e3p_0_pred"),
    ("plain", "on"): get("scores_constrained_untuned_val_e3p_0_pred_free"),
    ("description", "off"): get("scores_untuned_val_e3d_0_pred"),
    ("description", "on"): get("scores_constrained_untuned_val_e3d_0_pred_free"),
}
cell = {k: list(h.jsonl("scores.jsonl")) for k, h in CELLS.items()}
cell_sum = {k: h.json("summary.json") for k, h in CELLS.items()}
cell_ci = {k: bootstrap_accuracy(v) for k, v in cell.items()}
enforce = {
    p: paired_difference(cell[(p, "on")], cell[(p, "off")])
    for p in ["plain", "description"]
}
describe = {
    g: paired_difference(cell[("description", g)], cell[("plain", g)])
    for g in ["off", "on"]
}
for p in enforce:
    assert enforce[p]["low"] > 0, p
# the two intervals for the grammar's gain overlap
assert (
    enforce["plain"]["low"] < enforce["description"]["high"]
    and enforce["description"]["low"] < enforce["plain"]["high"]
)
# with the grammar on, the description is the lower of the two prompts
assert describe["on"]["high"] < 0
assert (
    cell_sum[("description", "on")]["by_kind"]["bad_reference"]
    > cell_sum[("plain", "on")]["by_kind"]["bad_reference"]
)
pd.DataFrame([
    {
        "system message": p,
        "grammar": g,
        "accuracy": pct(cell_ci[(p, g)]["accuracy"]),
        "invalid": pct(cell_sum[(p, g)]["invalid_rate"]),
    }
    for (p, g) in CELLS
]).set_index(["system message", "grammar"])
accuracy invalid
system message grammar
plain off 57.2% 16.4%
on 60.4% 1.3%
description off 55.3% 17.1%
on 57.2% 5.3%

The grammar helps with either message: +3.3 points with the plain one (interval [+1.7, +5.1]) and +2.0 with the description ([+0.9, +3.1]). The two intervals overlap, so this run does not show that the gain differs. Changing the plain message for the description changes accuracy by -1.9 points without a grammar ([-3.9, +0.1]) and by -3.2 with one ([-5.7, -0.9]). With the description the grammar brings the invalid rate from 17.1% to 5.3%, against 16.4% to 1.3% with the plain message. What remains with the description is mostly references to steps that do not exist (bad_reference: 58 turns, against 10 with the plain message), which no grammar of this kind rules out. So the description does not make the grammar redundant, and the grammar does not make the description worth having: with the grammar on, the description is the lower of the two.

15.7 Without examples

The three-example prompts show the format twice over: in the examples, and in the model’s own earlier answers when they are valid. The prompt with no examples (e0p, the training prompt) shows it in neither. Without a grammar, the model with its own history is at the floor (Section 14.5).

Code
#HEAVY
E0 = {
    "grammar off, predicted history": get("scores_untuned_val_e0p_0_pred"),
    "grammar on, predicted history": get(
        "scores_constrained_untuned_val_e0p_0_pred_free"
    ),
    "grammar off, gold history": get("scores_untuned_val_e0p_0_gold"),
}
e0 = {k: list(h.jsonl("scores.jsonl")) for k, h in E0.items()}
e0_sum = {k: h.json("summary.json") for k, h in E0.items()}
first_turn = lambda rows: [r for r in rows if r["turn"] == 0]
follow_up = lambda rows: [r for r in rows if r["turn"] > 0]
acc = lambda rows: sum(r["correct"] for r in rows) / len(rows)
e0_gain = paired_difference(
    e0["grammar on, predicted history"], e0["grammar off, predicted history"]
)
off_first = acc(first_turn(e0["grammar off, predicted history"]))
on_first = acc(first_turn(e0["grammar on, predicted history"]))
on_follow = acc(follow_up(e0["grammar on, predicted history"]))
gold_follow = acc(follow_up(e0["grammar off, gold history"]))
assert e0_gain["low"] > 0.1
assert on_first > 10 * off_first
assert on_follow < gold_follow
pd.DataFrame([
    {
        "run": k,
        "all turns": pct(acc(rows)),
        "first turns": pct(acc(first_turn(rows))),
        "follow-ups": pct(acc(follow_up(rows))),
        "invalid": pct(e0_sum[k]["invalid_rate"]),
        "hit the limit": pct(e0_sum[k]["truncated"] / n_val),
    }
    for k, rows in e0.items()
]).set_index("run")
all turns first turns follow-ups invalid hit the limit
run
grammar off, predicted history 0.3% 0.7% 0.1% 99.2% 32.9%
grammar on, predicted history 20.8% 16.3% 22.5% 0.0% 27.9%
grammar off, gold history 28.1% 0.7% 38.3% 64.3% 15.7%

With the grammar, the untuned model with no examples goes from 0.3% to 20.8%, a change of +20.5 points (interval [+17.6, +23.5]). The first turn has no history, so its change is the effect of the grammar alone: from 0.7% to 16.3%. The grammar is the only thing here that tells the model what an answer looks like, and it is enough for some answers.

The follow-up turns reach 22.5% with the grammar and the model’s own history. With the gold history and no grammar they reach 38.3%. The two runs differ in the history (valid but mostly wrong, against correct) and in the grammar, so this does not separate what each contributes.

Many of these answers do not stop: 27.9% of the turns hit the generation limit, with digits that keep coming. That is what the bounded grammar is for.

15.8 Bounding the numbers

A grammar guarantees syntax, not termination. The bounded variant allows at most the digits that the gold programs use (ten before the point, four after it), so a run of digits must end.

Code
#HEAVY
BOUNDS = {
    "untuned DSL, three examples": (
        get("scores_constrained_untuned_val_e3p_0_pred_free"),
        get("scores_constrained_untuned_val_e3p_0_pred_bounded"),
    ),
    "untuned DSL, no examples": (
        get("scores_constrained_untuned_val_e0p_0_pred_free"),
        get("scores_constrained_untuned_val_e0p_0_pred_bounded"),
    ),
}
free = {k: list(v[0].jsonl("scores.jsonl")) for k, v in BOUNDS.items()}
bounded = {k: list(v[1].jsonl("scores.jsonl")) for k, v in BOUNDS.items()}
free_sum = {k: v[0].json("summary.json") for k, v in BOUNDS.items()}
bounded_sum = {k: v[1].json("summary.json") for k, v in BOUNDS.items()}
bound_gain = {k: paired_difference(bounded[k], free[k]) for k in BOUNDS}
for k in BOUNDS:
    assert not bound_gain[k]["excludes_zero"], k
    assert (
        bounded_sum[k]["truncated"] < free_sum[k]["truncated"]
    ), k
assert bounded_sum["untuned DSL, no examples"]["truncated"] == 0
pd.DataFrame([
    {
        "run": k,
        "free": pct(free_sum[k]["accuracy"]),
        "bounded": pct(bounded_sum[k]["accuracy"]),
        "bounded − free (points)": pts(bound_gain[k]["difference"]),
        "95% paired interval":
            f"[{pts(bound_gain[k]['low'])}, {pts(bound_gain[k]['high'])}]",
        "hit the limit, free": free_sum[k]["truncated"],
        "hit the limit, bounded": bounded_sum[k]["truncated"],
    }
    for k in BOUNDS
]).set_index("run")
free bounded bounded − free (points) 95% paired interval hit the limit, free hit the limit, bounded
run
untuned DSL, three examples 60.4% 60.5% +0.1 [+0.0, +0.3] 7 3
untuned DSL, no examples 20.8% 21.0% +0.2 [-0.4, +0.8] 314 0

The bounded grammar cuts the turns that hit the limit (314 to 0 with no examples), and accuracy does not change: the paired intervals include zero in both rows. So the unbounded grammar was not hiding accuracy, and the numbers in the rest of the chapter are those of the unbounded one. The bounded grammar is the safer one to use when a run must end, and costs nothing here.

15.9 The time it takes

Code
#HEAVY
def log_seconds(handle):
    text = (handle.path / "build.log").read_text()
    return int(re.findall(r"done: \d+ turns in (\d+) s", text)[-1])


def tokens(handle):
    return sum(r["new_tokens"] for r in handle.jsonl("predictions.jsonl"))


RUNS = {
    "untuned DSL": (
        get("untuned_val_e3p_0_pred"),
        get("constrained_untuned_val_e3p_0_pred_free"),
    ),
    "untuned Python": (
        get("python_untuned_val_e3_0_pred"),
        get("constrained_python_untuned_val_e3_0_pred_free"),
    ),
    "fine-tuned DSL": (
        get("tuned_val_main_0_pred"),
        get("constrained_tuned_val_main_0_pred_free"),
    ),
}
timing = {
    k: {
        "off": (log_seconds(a), tokens(a)),
        "on": (log_seconds(b), tokens(b)),
    }
    for k, (a, b) in RUNS.items()
}
# the logs count whole seconds from separate sessions: a tie can come out a second
# either way, so the claim is "not noticeably longer", not "never longer"
assert all(t["on"][0] <= 1.05 * t["off"][0] for t in timing.values())
assert all(t["on"][1] <= t["off"][1] for t in timing.values())
pd.DataFrame([
    {
        "system": k,
        "seconds, off": t["off"][0],
        "seconds, on": t["on"][0],
        "tokens generated, off": f"{t['off'][1]:,}",
        "tokens generated, on": f"{t['on'][1]:,}",
    }
    for k, t in timing.items()
]).set_index("system")
seconds, off seconds, on tokens generated, off tokens generated, on
system
untuned DSL 1994 1924 19,408 17,251
untuned Python 2502 1899 27,626 16,779
fine-tuned DSL 1308 1309 16,535 16,532

These are the durations that the build logs of the runs report, and they do not isolate the cost of the grammar. The runs were made in separate sessions, and the runs without a grammar generated at least as many tokens (invalid answers can run on). What the table can say is that no run with the grammar took noticeably longer than the run without it (the largest ratio of the time with the grammar to the time without is 1.00). The overhead of the grammar is not measured in this book.

15.10 Discussion

A grammar fixes the form and leaves the content, and the results above are what that looks like. Two pieces of related work are worth comparing.

  • Format restrictions can hurt reasoning. Tam et al. (2024) compare language models restricted to structured output formats such as JSON or XML with free-form answers. They report a drop in reasoning ability under the restriction, larger for stricter formats. That concerns a model that reasons in the text it writes and is then made to write it in a format. Here the output is the program: there is no free text for the grammar to cut short, and the fine-tuned model does not change under the grammar. This chapter’s runs do not test their claim.
  • FinQA’s decoder was restricted too. The program generator of the original FinQA model takes its output tokens from three sources: the tokens of the question and the retrieved facts (the numbers), the special tokens of the DSL, and tokens for the results of earlier steps. At inference time it also applies masks from the grammar of the DSL at every decoding step, to keep the program well formed (Chen et al. 2021). Its output space is narrower than that of the syntax grammar of this chapter, which lets any number be written. A grammar that restricts the numbers to those of the page in the same way is not run in this book (Section 17.7).
TipFurther reading
  • Dong et al. (2024) describe xgrammar, the library used here.
  • Tam et al. (2024) study the effect of format restrictions on reasoning.

15.11 Summary

  • A grammar sets the probability of every token it does not allow to zero and leaves the rest as the model had them. At the start of a DSL answer, 39 of 151,936 tokens remain.
  • On validation turns with predicted history, the grammar takes the untuned DSL from 57.2% to 60.4% and untuned Python from 64.5% to 68.4%, and invalid answers nearly disappear. The fine-tuned model is unchanged (83.7% to 83.8%).
  • The gain is under half of the invalid output removed, and mostly on program turns. The grammar closes 12.4% of the gap between the untuned and the fine-tuned model; the ceiling is below the fine-tuned accuracy.
  • The grammar helps with the plain and the description prompt alike, and, with no examples, takes the model from the floor to 20.8%.
  • The bounded number rule removes the runaway digits and does not change accuracy.
  • These are validation results. The final results do not repeat the grammar comparison on the development data.