Skip to content

Grammar-constrained decoding of language models - #38

Open
echatav wants to merge 2 commits into
json-algebrafrom
grammar-decoding
Open

echatav wants to merge 2 commits into
json-algebrafrom
grammar-decoding

Conversation

@echatav

@echatav echatav commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

Grammar-constrained decoding of language models, in a new module Control.Lens.Grammar.Decoding. One grammar now also constrains a language model to generate its language, alongside parsing, printing, generating and describing it. Stacked on #30, since the grammar package lives there.

Control.Lens.Grammar.Decoding

  • Vocabulary: a language model's pieces. Each piece is a string of grammar tokens, indexed by position as a model indexes its vocabulary. Pieces needn't align with the grammar's lexemes; sub-word tokenizers' pieces don't.
  • allowedPieces: masks a vocabulary at a chart. It walks a trie of the pieces, so pieces that share a prefix share its scanning, and a dead-end prefix prunes everything under it. Tokens with the same Scan (they pass the same scanner transitions) reach the same chart, so each distinct chart is scanned and closed once and its per-token tests are memoized. In effect, it builds a small DFA over the vocabulary for each mask.
  • decode / decodeG: decode text, or a syntax value, from a Predictor (the indices of the pieces so far → Weights on pieces and ending, in any monad) and a Chooser (greedy, or sampled by a RandomGen). Decoding returns Finished, Stuck or Truncated. decodeG parses what finishes.
  • Opportunistic masking: decode lets the chooser pick from the unmasked weights first, and builds the full mask only if that pick isn't allowed. This decodes exactly as masking every step would. For greedy, an allowed argmax is also the masked argmax. For sampled, piece i comes out with probability p_i + (1 − Z)·p_i/Z = p_i/Z. The module docs give the argument, and a test checks it against the exact distribution.

The module docs cover the literature, with links:

  • Willard & Louf on guided generation: the overall approach.
  • Koo, Liu & He: masking as composition with the detokenizer, and closure under inverse homomorphisms.
  • Beurer-Kellner et al. and Vieira et al.: canonical tokenization and its pitfalls.
  • Park et al. (grammar-aligned decoding) and Loula et al. (sequential Monte Carlo): why masking ≠ conditioning, and what approximates the conditional.

Control.Lens.Grammar.Machine

  • Exports Earley **Chart**s, scanned a token at a time: startChart, scanChart, scanChartMany, chartExpects, chartAccepts, chartLength. Also exports the Scans tokens share: chartScan, nullScan, scanChartBy.
  • Simplification: =~, expectNext and parseForest now scan charts. The rescanning prefixGen, with its own copy of the scan loop, is removed. scanClassOptions (behind languageSample) shares scanItems with scanChartBy.

Tests (test/Properties/Decoding.hs, +49)

Over the json, arith, semver, sexpr, lambda and regex example grammars:

  • a chart accepts exactly the words parseG fully parses;
  • chartExpects is exactly the tokens scanChart scans;
  • expectNext agrees with an incrementally scanned chart;
  • allowedPieces agrees with brute force;
  • sampling finishes at words of the language and truncates at prefixes of them;
  • with positive weights, decoding is stuck only where no piece is allowed;
  • greedy opportunistic masking equals masking every step;
  • decodeG parses exactly when decoding finishes;
  • sampling with opportunistic masking matches the exact enumerated distribution of masked sampling (6,000 runs, within 0.03).

expectNext had no tests before. test/Examples/Vocabulary.hs holds the shared vocabularies, predictor and reference decoder for the tests and benchmarks.

Benchmarks (decoding group, JSON example)

expectNext after each of 300 prefixes 87.0 ms
chartExpects along one incrementally scanned chart 1.08 ms (~80×)
allowedPieces, 50,653 pieces, inside a JSON string 11.2 ms (51 ms before sharing scans)
allowedPieces, 50,653 pieces, at the start / after a number 678 µs / 274 µs
allowedPieces, 471 example pieces, in a string 194 µs
10 greedy decodes, opportunistic masking 27.9 ms
10 greedy decodes, masking every step 51.4 ms

All suites pass: distributors 363 + 180 doctests; distributors-grammar 954 (was 905) + 112 doctests (was 96); distributors-json 280 + 32 doctests. These were built with GHC 9.10.3 and Debian's packages of the dependencies, because Hackage wasn't reachable from the build environment. So I haven't checked them against the stack nightly resolver.

Things I noticed but didn't change

  • parseG jsonGrammar costs ~120 ms per call, even on "\"abc\"", and transducerG jsonGrammar ~335 ms. Instantiating the polymorphic grammar rebuilds the example's class of over a million characters each time. The changelog keeps it as a deliberate stress case, so I left it alone and capped the parse-heavy JSON properties at 20 cases instead. For a real application, oneOf ['\x0020' .. '\x10FFFF'] >&< notOneOf "\"\\" is the same class as notOneOf (['\0' .. '\x1F'] <> "\"\\").
  • There are no bindings to a specific model runtime. A model is wrapped as a Predictor by calling it (llama.cpp, an ONNX session, an HTTP server that returns logits) with weights exp logit and its end-of-sequence piece as endWeight. Hosted APIs that don't expose logits can't be masked this way.
  • I edited distributors-grammar.cabal by hand to match package.yaml, because the available hpack (0.38.3) is older than the 0.39.6 that generated it. Regenerating it should be a no-op.

Generated by Claude Code

Control.Lens.Grammar.Decoding decodes text, & syntax values, of a
grammar's language from a next-piece predictor, masking its weights
to what the grammar allows:

* Vocabulary: a language model's pieces, strings of tokens misaligned
  with a grammar's lexemes as sub-word tokenizers' are, in a trie.
* allowedPieces masks a vocabulary at a chart, sharing the charts
  which tokens that scan alike reach, so each is scanned & closed once.
* decode & decodeG, by a Predictor & a Chooser, greedy or sampled,
  masking opportunistically, only when the unmasked choice isn't
  allowed, which decodes exactly as masking every step does.

Control.Lens.Grammar.Machine exports Earley Charts, scanned a token
at a time, & the Scans which tokens share; =~, expectNext &
parseForest scan charts, & the rescanning prefixGen is removed, &
scanClassOptions shares scanItems with scanChartBy.

Tests: charts against parseG, expectNext & brute force; masks against
brute force; opportunistic against always-masked decoding, greedily
& by the exact distribution of sampling. Benchmarks of masks,
incremental charts & decoding.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WcUfd6dEu7UMpc8162pvCw
@github-actions

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.2

QR code for preview link

🚀 View preview at
https://morphismtech.github.io/distributors/pr-preview/pr-38/

Built to branch gh-pages at 2026-11-27 21:49 UTC.
Preview will be ready when the GitHub Pages deployment is complete.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants