distributors-grammar
Copyright(C) 2026 - Eitan Chatav
LicenseBSD-style (see the file LICENSE)
MaintainerEitan Chatav <eitan.chatav@gmail.com>
Stabilityprovisional
Portabilitynon-portable
Safe HaskellNone
LanguageHaskell2010

Control.Lens.Grammar.Decoding

Description

A language model generates text a piece at a time: given the pieces so far, it weighs each piece of its vocabulary, & ending, & a decoder chooses one. Grammar-constrained decoding masks those weights, so that only pieces which continue a word of a grammar's language may be chosen, & ending only at a word of the language, so the generated text always parses. See Willard & Louf, Efficient Guided Generation for Large Language Models.

A Grammar is a decoder's constraint, as it's a parser, & a printer, & a Transducer, by transducerG, whose Charts are the states of the constraint, scanned a token at a time. decodeG decodes a syntax value, parsing the text which it masks its predictor to generate.

Pieces & tokens

A language model's vocabulary is not its grammar's tokens: models generate pieces of text, by sub-word tokenizers such as byte-pair encoding, each piece a string of many characters, which needn't align with a grammar's lexemes. A Vocabulary is the strings of tokens which its pieces stand for, indexed by position, as a model indexes its vocabulary, & a piece is allowed where a Chart scans its whole string. Masking a vocabulary is thus composing a grammar with the detokenizer, the monoid homomorphism from strings of pieces to strings of tokens, whose inverse image of a context-free language is context-free. See Koo, Liu & He, Automata-based constraints for language model decoding.

allowedPieces scans a vocabulary's pieces together, by a trie, so pieces which share a prefix share its scanning, & a prefix which is a dead end prunes every piece which begins with it.

Many strings of pieces stand for the same text, but a model is trained on only one of them, its tokenizer's canonical one, & weighs the others poorly. A mask allows them all, which can steer a model to text it would've tokenized differently. See Beurer-Kellner, Fischer & Vechev, Guiding LLMs The Right Way: Fast, Non-Invasive Constrained Generation, & Vieira et al., From Language Models over Tokens to Language Models over Characters.

Opportunistic masking

Masking a whole vocabulary each step costs a scan of its trie, while a model usually weighs most what the grammar allows anyway. So decode first lets its Chooser choose from the unmasked weights, & only masks when the choice isn't allowed, choosing again from the masked weights. This decodes exactly as masking each step would: a greedy choice which is allowed is the masked weights' greatest; & a sampled choice is sampled from the masked weights, as a piece i of weight p_i, out of an allowed total of Z, is chosen first with probability p_i, & else, with probability 1 - Z, then with p_i / Z, in all p_i / Z.

Masking is not conditioning

Masking a model's weights a piece at a time decodes from a different distribution than the model's, conditioned on generating a word of the language: masking can't see that an allowed piece leads only to words the model weighs poorly. Decoding from the conditional distribution is intractable in general, & approximated by importance sampling & sequential Monte Carlo. See Park et al., Grammar-Aligned Decoding, & Loula et al., Syntactic and Semantic Control of Large Language Models via Sequential Monte Carlo.

Predictors

A Predictor is any function from the pieces so far to Weights, in a monad, so a language model is wrapped as a predictor by calling it, in IO, & keeping its prompt in a closure; its logits l_i are weights exp l_i, & its end-of-sequence piece is endWeight.

Synopsis

Decoding

decodeG Source #

Arguments

:: (Categorized token, Monad m) 
=> Chooser m 
-> Predictor m 
-> Vocabulary token 
-> Int

the most pieces to generate

-> Grammar token a 
-> m (Either (Decoded token) a) 

Decode a syntax value of a Grammar, from a Predictor, by a Chooser, in at most a given number of pieces, parsing the text it decodes, or returning it, unless it Finished.

>>> let vocab = vocabulary ["tr", "ue", "true", "false", "f"]
>>> let uniform _ = pure (Weights (IntMap.fromList [(i, 1) | i <- [0 .. 4]]) 1)
>>> runIdentity (decodeG greedy uniform vocab 10 boolG)
Right True

decode Source #

Arguments

:: (Categorized token, Monad m) 
=> Chooser m 
-> Predictor m 
-> Vocabulary token 
-> Int

the most pieces to generate

-> Transducer token 
-> m (Decoded token) 

Decode text of a Transducer's language, from a Predictor, by a Chooser, in at most a given number of pieces. Each step, the predictor weighs the pieces of a Vocabulary, & ending; the chooser chooses among them, masked to what the grammar allows; & a chosen piece is scanned, by the Chart of the text so far.

>>> let vocab = vocabulary ["tr", "ue", "true", "false", "f"]
>>> let et = transducerG @Char boolG
>>> let uniform _ = pure (Weights (IntMap.fromList [(i, 1) | i <- [0 .. 4]]) 1)
>>> runIdentity (decode greedy uniform vocab 10 et)
Finished "true"
>>> evalStateT (decode sampled uniform vocab 10 et) (mkStdGen 1)
Finished "false"

A predictor which only ever weighs ending, outside the language, is stuck.

>>> runIdentity (decode greedy (\_ -> pure (Weights IntMap.empty 1)) vocab 10 et)
Stuck ""

data Decoded token Source #

The text a decoder generates, by how it stopped.

Constructors

Finished [token]

chosen to end, at a word of the language

Stuck [token]

nothing allowed next has weight

Truncated [token]

out of pieces, at the bound on how many to generate

Instances

Instances details
Read token => Read (Decoded token) Source # 
Instance details

Defined in Control.Lens.Grammar.Decoding

Methods

readsPrec :: Int -> ReadS (Decoded token) #

readList :: ReadS [Decoded token] #

readPrec :: ReadPrec (Decoded token) #

readListPrec :: ReadPrec [Decoded token] #

Show token => Show (Decoded token) Source # 
Instance details

Defined in Control.Lens.Grammar.Decoding

Methods

showsPrec :: Int -> Decoded token -> ShowS #

show :: Decoded token -> String #

showList :: [Decoded token] -> ShowS #

Eq token => Eq (Decoded token) Source # 
Instance details

Defined in Control.Lens.Grammar.Decoding

Methods

(==) :: Decoded token -> Decoded token -> Bool #

(/=) :: Decoded token -> Decoded token -> Bool #

Ord token => Ord (Decoded token) Source # 
Instance details

Defined in Control.Lens.Grammar.Decoding

Methods

compare :: Decoded token -> Decoded token -> Ordering #

(<) :: Decoded token -> Decoded token -> Bool #

(<=) :: Decoded token -> Decoded token -> Bool #

(>) :: Decoded token -> Decoded token -> Bool #

(>=) :: Decoded token -> Decoded token -> Bool #

max :: Decoded token -> Decoded token -> Decoded token #

min :: Decoded token -> Decoded token -> Decoded token #

Predictors

type Predictor (m :: Type -> Type) = [Int] -> m Weights Source #

A next-piece predictor, which weighs what comes next, given the indices of the pieces so far.

data Weights Source #

The weights a Predictor puts on its next choice: on each piece of its Vocabulary, by index, & on ending. Weights are nonnegative & needn't sum to one; a piece missing from pieceWeights has no weight.

Constructors

Weights 

Instances

Instances details
Show Weights Source # 
Instance details

Defined in Control.Lens.Grammar.Decoding

Eq Weights Source # 
Instance details

Defined in Control.Lens.Grammar.Decoding

Methods

(==) :: Weights -> Weights -> Bool #

(/=) :: Weights -> Weights -> Bool #

Choosers

type Chooser (m :: Type -> Type) = Weights -> m (Maybe Int) Source #

A decoder's choice, among Weights, of the index of a piece, or Nothing, to end. A Chooser should only choose what has weight.

greedy :: Applicative m => Chooser m Source #

Choose what weighs most, preferring to end, & the least index of the pieces which weigh most.

>>> runIdentity (greedy (Weights (IntMap.fromList [(0, 1), (1, 3), (2, 3)]) 2))
Just 1

sampled :: forall g (m :: Type -> Type). (RandomGen g, Monad m) => Chooser (StateT g m) Source #

Sample in proportion to weight, by a random generator.

>>> let weights = Weights (IntMap.fromList [(0, 1), (1, 1)]) 0
>>> evalStateT (traverse (const (sampled weights)) [1 .. 8 :: Int]) (mkStdGen 7)
[Just 0,Just 1,Just 0,Just 1,Just 0,Just 0,Just 0,Just 1]

Vocabularies

data Vocabulary token Source #

A language model's vocabulary, as the strings of tokens its pieces stand for, indexed by their positions in the list vocabulary is given, from 0. The empty piece, which would generate nothing, is never allowed.

vocabulary :: Ord token => [[token]] -> Vocabulary token Source #

A Vocabulary of pieces, indexed by position.

vocabularyPiece :: Vocabulary token -> Int -> Maybe [token] Source #

The string of tokens a piece stands for, by index.

vocabularySize :: Vocabulary token -> Int Source #

The number of nonempty pieces in a Vocabulary.

allowedPieces :: Categorized token => Vocabulary token -> Chart token -> IntMap (Chart token) Source #

The pieces of a Vocabulary which a Chart scans, by index, with the Chart after each.

>>> let vocab = vocabulary ["t", "tr", "true", "fa", "false", "lse", "x"]
>>> let et = transducerG @Char boolG
>>> IntMap.keys (allowedPieces vocab (startChart et))
[0,1,2,3,4]
>>> IntMap.keys <$> (allowedPieces vocab <$> scanChartMany "fa" (startChart et))
Just [5]