Repository navigation
Conversation
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
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WcUfd6dEu7UMpc8162pvCw
Contributor
|
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.DecodingVocabulary: 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 sameScan(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 aPredictor(the indices of the pieces so far →Weightson pieces and ending, in any monad) and aChooser(greedy, orsampledby aRandomGen). Decoding returnsFinished,StuckorTruncated.decodeGparses what finishes.decodelets 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. Forgreedy, an allowed argmax is also the masked argmax. Forsampled, 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:
Control.Lens.Grammar.MachineChart**s, scanned a token at a time:startChart,scanChart,scanChartMany,chartExpects,chartAccepts,chartLength. Also exports theScans tokens share:chartScan,nullScan,scanChartBy.=~,expectNextandparseForestnow scan charts. The rescanningprefixGen, with its own copy of the scan loop, is removed.scanClassOptions(behindlanguageSample) sharesscanItemswithscanChartBy.Tests (
test/Properties/Decoding.hs, +49)Over the json, arith, semver, sexpr, lambda and regex example grammars:
parseGfully parses;chartExpectsis exactly the tokensscanChartscans;expectNextagrees with an incrementally scanned chart;allowedPiecesagrees with brute force;decodeGparses exactly when decoding finishes;expectNexthad no tests before.test/Examples/Vocabulary.hsholds the shared vocabularies, predictor and reference decoder for the tests and benchmarks.Benchmarks (
decodinggroup, JSON example)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 jsonGrammarcosts ~120 ms per call, even on"\"abc\"", andtransducerG 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 asnotOneOf (['\0' .. '\x1F'] <> "\"\\").Predictorby calling it (llama.cpp, an ONNX session, an HTTP server that returns logits) with weightsexp logitand its end-of-sequence piece asendWeight. Hosted APIs that don't expose logits can't be masked this way.distributors-grammar.cabalby hand to matchpackage.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