diff --git a/distributors-grammar/CHANGELOG.md b/distributors-grammar/CHANGELOG.md index 77257c43..bab98a86 100644 --- a/distributors-grammar/CHANGELOG.md +++ b/distributors-grammar/CHANGELOG.md @@ -2,6 +2,22 @@ ## Unreleased +- `Control.Lens.Grammar.Decoding`, grammar-constrained decoding of + language models: a `Predictor` weighs a `Vocabulary`'s pieces & ending, + a `Chooser`, `greedy` or `sampled`, chooses among them, masked to what + a grammar allows, & `decodeG` parses the text it decodes. Pieces are + strings of tokens, misaligned with a grammar's lexemes as sub-word + tokenizers' are, & `allowedPieces` masks a vocabulary by a trie, sharing + the chart which tokens that scan alike reach: masking 50,000 pieces in a + JSON string costs ~12ms. `decode` masks opportunistically, only when its + chooser's unmasked choice isn't allowed, decoding exactly as masking every + step would, & ~2x faster on the JSON example. +- `Control.Lens.Grammar.Machine` exports the `Chart`s of Earley's algorithm, + scanned a token at a time, by `startChart`, `scanChart`, `chartExpects` & + `chartAccepts`, & by the `Scan`s which tokens share, `chartScan` & + `scanChartBy`. `=~`, `expectNext` & `parseForest` scan charts, & the + rescanning `prefixGen` is removed: asking `chartExpects` after each token of + a growing prefix is ~70x faster than `expectNext` of each prefix. - Token classes test their sets of tokens logarithmically, by `Set`, in `tokenClass`'s default & in `oneOf` & `notOneOf` of predicates, rather than linearly by `Foldable`: parsing the JSON example, whose characters diff --git a/distributors-grammar/README.md b/distributors-grammar/README.md index 82fda1a5..cffabcf8 100644 --- a/distributors-grammar/README.md +++ b/distributors-grammar/README.md @@ -6,5 +6,7 @@ Grammars by the profunctor algebra of [distributors](https://hackage.haskell.org/package/distributors): one grammar parses, prints, generates & describes its language, -as a regular expression or a Backus-Naur form. +as a regular expression or a Backus-Naur form, +& constrains a language model to generate it, +in "Control.Lens.Grammar.Decoding". Start at "Control.Lens.Grammar". diff --git a/distributors-grammar/bench/Main.hs b/distributors-grammar/bench/Main.hs index dd3cc2f2..b79e8aae 100644 --- a/distributors-grammar/bench/Main.hs +++ b/distributors-grammar/bench/Main.hs @@ -11,7 +11,9 @@ module Main (main) where import Control.Lens import Control.Lens.Grammar import Control.Lens.Comonocle (_BoundedEnum, indexComonocle) -import Control.Monad (unless) +import Control.Lens.Grammar.Decoding +import Control.Monad (replicateM, unless) +import qualified Data.IntMap.Strict as IntMap import Data.List (intercalate) import Test.Tasty.Bench @@ -22,6 +24,7 @@ import Examples.Json import Examples.Lambda import Examples.SemVer import Examples.SExpr +import Examples.Vocabulary main :: IO () main = do @@ -32,6 +35,7 @@ main = do , backends "example" examples , pure statics , pure optics + , pure decodings ] defaultMain groups @@ -184,3 +188,42 @@ optics = bgroup "optic" where ints = [1 .. size] ords = take size (cycle [LT, EQ, GT]) + +-- | Grammar-constrained decoding of the JSON example: asking what's +-- expected next, masking vocabularies, & decoding from a predictor. +decodings :: Benchmark +decodings = bgroup "decoding" + [ bench "expectNext each prefix" $ + whnf (\s -> length [() | n <- [0 .. length s], tokenClass (expectNext et (take n s)) '1']) prefix + , bench "chartExpects each prefix" $ + whnf (\s -> length [() | chart <- charts s, tokenClass (chartExpects chart) '1']) prefix + , bgroup "allowedPieces" + [ bench (vname <> "/" <> cname) $ whnf (IntMap.size . allowedPieces vocab) chart + | (vname, vocab) <- [("examples", examplesVocab), ("50k", largeVocab)] + , (cname, chart) <- states + ] + , bench "decode greedy" $ + whnf (\seeds -> sum [ len (runIdentity (decode greedy (predictor seed) examplesVocab 60 et)) | seed <- seeds ]) [1 .. 10] + , bench "maskedDecode greedy" $ + whnf (\seeds -> sum [ len (runIdentity (maskedDecode greedy (predictor seed) examplesVocab 60 et)) | seed <- seeds ]) [1 .. 10] + , bench "transducerG json" $ whnf (IntMap.size . transducerRelations . transducerG @Char) jsonGrammar + ] + where + et = transducerG @Char jsonGrammar + prefix = take 300 ("[" <> intercalate "," + (replicate 20 "{\"a\":[1,2,3],\"b\":\"text\",\"c\":true,\"d\":null}") <> "]") + charts = catMaybes . scanl (\chart x -> chart >>= scanChart x) (Just (startChart et)) + examplesPieces = vocabularyOf (map snd jsonExamples) + examplesVocab = vocabulary examplesPieces + -- a vocabulary the size of a sub-word tokenizer's, of 50,653 pieces + largeVocab = vocabulary (replicateM 3 "abcdefghijklmnopqrstuvwxyz0123456789\"") + states = + [ (name, chart) + | (name, text) <- [("start", ""), ("in string", "{\"a\":\"te"), ("after number", "[1,2")] + , Just chart <- [scanChartMany text (startChart et)] + ] + predictor seed = randomPredictor 0.2 seed (length examplesPieces) + len = \case + Finished w -> length w + Stuck w -> length w + Truncated w -> length w diff --git a/distributors-grammar/distributors-grammar.cabal b/distributors-grammar/distributors-grammar.cabal index cae63344..7eb8a529 100644 --- a/distributors-grammar/distributors-grammar.cabal +++ b/distributors-grammar/distributors-grammar.cabal @@ -30,6 +30,7 @@ library exposed-modules: Control.Lens.Grammar Control.Lens.Grammar.BackusNaur + Control.Lens.Grammar.Decoding Control.Lens.Grammar.Machine Control.Lens.Grammar.RegEx Control.Lens.Grammar.Symbol @@ -176,6 +177,8 @@ test-suite test Examples.RegString Examples.SemVer Examples.SExpr + Examples.Vocabulary + Properties.Decoding Properties.Kleene Properties.Varifocal Paths_distributors_grammar @@ -251,6 +254,7 @@ benchmark core Examples.Lambda Examples.SemVer Examples.SExpr + Examples.Vocabulary hs-source-dirs: bench test diff --git a/distributors-grammar/package.yaml b/distributors-grammar/package.yaml index c29da918..69927874 100644 --- a/distributors-grammar/package.yaml +++ b/distributors-grammar/package.yaml @@ -117,6 +117,7 @@ benchmarks: - Examples.Lambda - Examples.SemVer - Examples.SExpr + - Examples.Vocabulary ghc-options: - -O2 - -rtsopts diff --git a/distributors-grammar/src/Control/Lens/Grammar/Decoding.hs b/distributors-grammar/src/Control/Lens/Grammar/Decoding.hs new file mode 100644 index 00000000..9c69c4bf --- /dev/null +++ b/distributors-grammar/src/Control/Lens/Grammar/Decoding.hs @@ -0,0 +1,381 @@ +{- | +Module : Control.Lens.Grammar.Decoding +Description : grammar-constrained decoding of next-piece predictors +Copyright : (C) 2026 - Eitan Chatav +License : BSD-style (see the file LICENSE) +Maintainer : Eitan Chatav +Stability : provisional +Portability : non-portable + +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] +(https://arxiv.org/abs/2307.09702). + +A `Grammar` is a decoder's constraint, as it's a parser, & a printer, +& a t'Transducer', by `transducerG`, whose t'Chart's 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 t'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 t'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] +(https://arxiv.org/abs/2407.08103). + +`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] +(https://arxiv.org/abs/2403.06988), & Vieira et al., +[From Language Models over Tokens to Language Models over Characters] +(https://arxiv.org/abs/2412.03719). + +==== 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 t'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] +(https://arxiv.org/abs/2405.21047), & Loula et al., +[Syntactic and Semantic Control of Large Language Models via Sequential Monte Carlo] +(https://arxiv.org/abs/2504.13139). + +==== Predictors + +A t'Predictor' is any function from the pieces so far to t'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`. +-} + +module Control.Lens.Grammar.Decoding + ( -- * Decoding + decodeG + , decode + , Decoded (..) + -- * Predictors + , Predictor + , Weights (..) + -- * Choosers + , Chooser + , greedy + , sampled + -- * Vocabularies + , Vocabulary + , vocabulary + , vocabularyPiece + , vocabularySize + , allowedPieces + ) where + +import Control.Lens.Grammar +import Control.Monad.State (StateT, state) +import qualified Data.IntMap.Lazy as LazyIntMap +import qualified Data.IntMap.Strict as IntMap +import Data.IntMap.Strict (IntMap) +import qualified Data.IntSet as IntSet +import Data.IntSet (IntSet) +import qualified Data.Map.Strict as Map +import Data.Map.Strict (Map) +import Data.Maybe (fromMaybe) +import System.Random (RandomGen, randomR) + +-- $setup +-- >>> import Control.Lens (only) +-- >>> import Control.Lens.Grammar +-- >>> import Control.Monad.State (evalStateT) +-- >>> import Data.Functor.Identity (runIdentity) +-- >>> import qualified Data.IntMap.Strict as IntMap +-- >>> import System.Random (mkStdGen) +-- >>> :{ +-- let boolG :: Grammar Char Bool +-- boolG = orP [only True >? terminal "true", only False >? terminal "false"] +-- :} + +{- | The weights a t'Predictor' puts on its next choice: +on each piece of its t'Vocabulary', by index, & on ending. +Weights are nonnegative & needn't sum to one; a piece missing +from `pieceWeights` has no weight. +-} +data Weights = Weights + { pieceWeights :: IntMap Double + , endWeight :: Double + } deriving stock (Eq, Show) + +{- | A next-piece predictor, which weighs what comes next, +given the indices of the pieces so far. +-} +type Predictor m = [Int] -> m Weights + +{- | A decoder's choice, among t'Weights', of the index of a piece, +or `Nothing`, to end. A t'Chooser' should only choose what has weight. +-} +type Chooser m = Weights -> m (Maybe Int) + +{- | The text a decoder generates, by how it stopped. -} +data Decoded token + = 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 + deriving stock (Eq, Ord, Show, Read) + +{- | 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 +-} +greedy :: Applicative m => Chooser m +greedy (Weights pieces end) = pure (IntMap.foldlWithKey' heavier Nothing pieces') + where + pieces' = IntMap.filter (> max 0 end) pieces + heavier best i w = case best of + Just j | pieces' IntMap.! j >= w -> best + _ -> Just i + +{- | 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] +-} +sampled :: (RandomGen g, Monad m) => Chooser (StateT g m) +sampled (Weights pieces end) = do + r <- state (randomR (0, total)) + pure (pick r) + where + end' = max 0 end + pieces' = IntMap.toList (IntMap.filter (> 0) pieces) + total = end' + sum (map snd pieces') + pick r + | r < end' || null pieces' = Nothing + | otherwise = go (r - end') pieces' + go _ [(i, _)] = Just i + go r ((i, w) : rest) + | r < w = Just i + | otherwise = go (r - w) rest + go _ [] = Nothing + +{- | 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. +-} +data Vocabulary token = Vocabulary + { vocabularyPieces :: IntMap [token] + , vocabularyTrie :: Trie token + } + +-- A trie of a vocabulary's pieces, by their tokens, +-- with the indices of the pieces which end at each node. +data Trie token = Trie IntSet (Map token (Trie token)) + +{- | A t'Vocabulary' of pieces, indexed by position. -} +vocabulary :: Ord token => [[token]] -> Vocabulary token +vocabulary pieces = Vocabulary + { vocabularyPieces = IntMap.fromList indexed + , vocabularyTrie = foldl' insert (Trie IntSet.empty Map.empty) indexed + } + where + indexed = [(i, piece) | (i, piece) <- zip [0 ..] pieces, not (null piece)] + insert (Trie ends next) (i, piece) = case piece of + [] -> Trie (IntSet.insert i ends) next + x : xs -> Trie ends (Map.alter (Just . grow) x next) + where grow sub = insert (fromMaybe (Trie IntSet.empty Map.empty) sub) (i, xs) + +{- | The string of tokens a piece stands for, by index. -} +vocabularyPiece :: Vocabulary token -> Int -> Maybe [token] +vocabularyPiece vocab i = IntMap.lookup i (vocabularyPieces vocab) + +{- | The number of nonempty pieces in a t'Vocabulary'. -} +vocabularySize :: Vocabulary token -> Int +vocabularySize = IntMap.size . vocabularyPieces + +{- | The pieces of a t'Vocabulary' which a t'Chart' scans, by index, +with the t'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] +-} +allowedPieces + :: Categorized token + => Vocabulary token -> Chart token -> IntMap (Chart token) +allowedPieces vocab chart0 = fst (walk (vocabularyTrie vocab) 0 (IntMap.empty, memo0)) + where + memo0 = Memo (IntMap.singleton 0 chart0) IntMap.empty Map.empty + + walk (Trie _ next) chartId accMemo = Map.foldlWithKey' step accMemo next + where + step (acc, memo) x sub@(Trie ends next') = case scanned chartId x memo of + (Nothing, memo') -> acc `seq` (acc, memo') + (Just (chartId', chart'), memo') -> + let acc' = IntSet.foldl' (\m i -> IntMap.insert i chart' m) acc ends + in if Map.null next' + then acc' `seq` (acc', memo') + else walk sub chartId' (acc', memo') + + -- the chart a chart is scanned to by a token, remembered by token, + -- & numbered by scan, so tokens which scan a chart alike share it + scanned chartId x memo = case Map.lookup x table of + Just next -> (next, memo) + Nothing -> (next, memo' + { memoNext = IntMap.insert chartId (Map.insert x next table) (memoNext memo') }) + where + chart = memoCharts memo IntMap.! chartId + scan = chartScan x chart + (next, memo') + | nullScan scan = (Nothing, memo) + | otherwise = case Map.lookup (chartId, scan) (memoScanned memo) of + Just chartId' -> (Just (chartId', memoCharts memo IntMap.! chartId'), memo) + Nothing -> + let + chartId' = IntMap.size (memoCharts memo) + chart' = fromMaybe (error "allowedPieces: an empty scan") + (scanChartBy scan chart) + in + ( Just (chartId', chart') + , memo + { memoCharts = LazyIntMap.insert chartId' chart' (memoCharts memo) + , memoScanned = Map.insert (chartId, scan) chartId' (memoScanned memo) + } + ) + where + table = IntMap.findWithDefault Map.empty chartId (memoNext memo) + +-- The charts `allowedPieces` reaches, numbered: tokens which scan +-- a chart alike reach the same chart, which is scanned & closed once. +data Memo token = Memo + { memoCharts :: IntMap (Chart token) + -- ^ lazily, so a chart's only closed once a piece is scanned from it + , memoNext :: IntMap (Map token (Maybe (Int, Chart token))) + -- ^ the chart, & its number, a chart is scanned to by a token, + -- by the chart's number + , memoScanned :: Map (Int, Scan) Int + -- ^ the number of the chart a chart is scanned to by a scan + } + +{- | Decode text of a t'Transducer''s language, from a t'Predictor', +by a t'Chooser', in at most a given number of pieces. +Each step, the predictor weighs the pieces of a t'Vocabulary', & +ending; the chooser chooses among them, masked to what the grammar +allows; & a chosen piece is scanned, by the t'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 "" +-} +decode + :: (Categorized token, Monad m) + => Chooser m + -> Predictor m + -> Vocabulary token + -> Int {- ^ the most pieces to generate -} + -> Transducer token + -> m (Decoded token) +decode choose predict vocab bound et = go 0 [] [] (startChart et) + where + go n pieces chunks chart + | n >= bound = pure (Truncated text) + | otherwise = do + weights <- predict (reverse pieces) + choice <- choose weights + case choice of + Nothing | chartAccepts chart, endWeight weights > 0 -> pure (Finished text) + Just i + | Just piece <- vocabularyPiece vocab i + , Just chart' <- scanChartMany piece chart -> + go (n + 1) (i : pieces) (piece : chunks) chart' + -- the unmasked choice isn't allowed, so mask & choose again + _ -> do + let + allowed = allowedPieces vocab chart + masked = Weights + { pieceWeights = IntMap.filter (> 0) + (IntMap.intersectionWith const (pieceWeights weights) allowed) + , endWeight = if chartAccepts chart then max 0 (endWeight weights) else 0 + } + if IntMap.null (pieceWeights masked) && endWeight masked <= 0 + then pure (Stuck text) + else do + choice' <- choose masked + case choice' of + Nothing | endWeight masked > 0 -> pure (Finished text) + Just i + | Just chart' <- IntMap.lookup i allowed + , Just piece <- vocabularyPiece vocab i -> + go (n + 1) (i : pieces) (piece : chunks) chart' + _ -> pure (Stuck text) + where + text = concat (reverse chunks) + +{- | Decode a syntax value of a `Grammar`, from a t'Predictor', +by a t'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 +-} +decodeG + :: (Categorized token, Monad m) + => Chooser m + -> Predictor m + -> Vocabulary token + -> Int {- ^ the most pieces to generate -} + -> Grammar token a + -> m (Either (Decoded token) a) +decodeG choose predict vocab bound grammar = do + decoded <- decode choose predict vocab bound (transducerG grammar) + pure $ case decoded of + Finished word | (a, []) : _ <- parseG grammar word -> Right a + _ -> Left decoded diff --git a/distributors-grammar/src/Control/Lens/Grammar/Machine.hs b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs index d2f702bb..2fbf8531 100644 --- a/distributors-grammar/src/Control/Lens/Grammar/Machine.hs +++ b/distributors-grammar/src/Control/Lens/Grammar/Machine.hs @@ -19,6 +19,18 @@ module Control.Lens.Grammar.Machine , unreachableRules , Transducer (..) , TransducerStep (..) + -- * Chart + , Chart + , startChart + , scanChart + , scanChartMany + , Scan + , chartScan + , nullScan + , scanChartBy + , chartExpects + , chartAccepts + , chartLength ) where import Control.Lens @@ -45,9 +57,7 @@ class Matching word pattern | pattern -> word where -- instances instance Categorized token => Matching [token] (Transducer token) where - word =~ et = acceptsChart n chart - where - (n, chart) = prefixGen et word + word =~ et = maybe False chartAccepts (scanChartMany word (startChart et)) instance Categorized token => Matching [token] (Bnf (RegEx token)) where word =~ bnf = word =~ transducer bnf @@ -246,7 +256,7 @@ parseForest {- ^ parse forest & remaining unparsed tokens -} parseForest et word = (concat (itemForests Set.empty Nothing 0 acceptedLen 0), drop acceptedLen word) where - (n, chart) = prefixGen et word + Chart _ n chart = scanChartLongest word (startChart et) relations = transducerRelations et acceptedLen = maximum (0 : [j | j <- [0 .. n], acceptsChart j chart]) @@ -345,42 +355,123 @@ parseForest et word = (concat (itemForests Set.empty Nothing 0 acceptedLen 0), d | subtrees <- itemForests guards' (Just name) start end finalState ] -prefixGen - :: Categorized token - => Transducer token - -> [token] - -> (Int, IntMap (IntMap IntSet)) -prefixGen et word = go 0 (initialChart et) word - where - go j chart [] = (j, chart) - go j chart (x : xs) - | IntMap.null scanned = (j + 1, closed) - | otherwise = go (j + 1) closed xs - where - scanned = scanFrom j x chart - closed = closeChartAt et (j + 1) (IntMap.insert (j + 1) scanned chart) - - scanFrom j input chart = IntMap.foldrWithKey advance IntMap.empty eJ - where - eJ = IntMap.findWithDefault IntMap.empty j chart - advance s origs acc = case IntMap.lookup s (transducerRelations et) of - Just (TransitionTokenClass cls ds) | tokenClass cls input -> - IntSet.foldr - (\d -> IntMap.insertWith IntSet.union d origs) acc ds - _ -> acc - {- | What token is expected next? The scanner frontier, `expectNext` returns the t'TokenClass' that can be scanned next after the given input prefix. A `falseP` result means the current chart has no scanner transitions, i.e. the prefix is a dead end for recognition. + +`expectNext` scans its whole prefix each time it's run; +to ask after each token of a growing prefix, as a decoder does, +scan a t'Chart' a token at a time, by `scanChart`, & ask `chartExpects`. -} expectNext :: Categorized token => Transducer token -> [token] {- ^ prefix -} -> TokenClass token -expectNext et word = anyP fst (scanClassOptions et n chart) +expectNext et word = maybe falseP chartExpects (scanChartMany word (startChart et)) + +{- | The Earley chart of a prefix of tokens scanned by a t'Transducer': +the sets @E_0, …, E_n@ of Earley items, a state & the position it started +at, which the prefix @x_1 … x_n@ reaches. See Earley, +[An efficient context-free parsing algorithm] +(https://doi.org/10.1145/362007.362035). + +A t'Chart' is a prefix's state of recognition, scanned incrementally, +a token at a time, by `scanChart`, which costs as much as closing one +set of items, rather than rescanning the prefix. Charts persist, so +one chart can be scanned by many different tokens, as a decoder does +to mask a vocabulary of pieces by a grammar. +-} +data Chart token = Chart (Transducer token) !Int (IntMap (IntMap IntSet)) + +{- | The number of tokens a t'Chart' has scanned. -} +chartLength :: Chart token -> Int +chartLength (Chart _ n _) = n + +{- | The t'Chart' of the empty prefix. -} +startChart :: Transducer token -> Chart token +startChart et = Chart et 0 (initialChart et) + +{- | Scan a token into a t'Chart', or fail when the prefix with it +is a dead end, which no word of the language starts with, +provided that each of the grammar's rules matches some word. +-} +scanChart :: Categorized token => token -> Chart token -> Maybe (Chart token) +scanChart x chart = scanChartBy (chartScan x chart) chart + +{- | The scanner transitions out of a t'Chart''s last set of items +which a token passes. Tokens with equal t'Scan's scan a chart alike, +so a chart need be scanned once for each t'Scan', by `scanChartBy`, +rather than once for each token, as +`Control.Lens.Grammar.Decoding.allowedPieces` does. +A t'Scan' is of the chart it's taken of, & no other. +-} +newtype Scan = Scan IntSet + deriving newtype (Eq, Ord, Show) + +{- | The t'Scan' of a token, of a t'Chart'. -} +chartScan :: Categorized token => token -> Chart token -> Scan +chartScan x (Chart et j chart) = Scan (IntSet.fromDistinctAscList + [ s + | s <- IntMap.keys (chartAt j chart) + , Just (TransitionTokenClass cls ds) <- [IntMap.lookup s (transducerRelations et)] + , not (IntSet.null ds) + , tokenClass cls x + ]) + +{- | Does a t'Scan' pass no transitions, so that its token is a dead end? -} +nullScan :: Scan -> Bool +nullScan (Scan ss) = IntSet.null ss + +{- | Scan a t'Chart' by a t'Scan' of it, as `scanChart` scans it by any +token of that t'Scan'. The scanned chart's closure is lazy, so that +it's only closed when it's scanned in turn, or asked of. +-} +scanChartBy :: Scan -> Chart token -> Maybe (Chart token) +scanChartBy (Scan ss) (Chart et j chart) + | IntSet.null ss = Nothing + | otherwise = Just (Chart et (j + 1) (scanItems et j ss chart)) + +-- Advance the items of the scanner states of E_j over a token, +-- to E_(j+1), & close it. +scanItems + :: Transducer token -> Int -> IntSet -> IntMap (IntMap IntSet) -> IntMap (IntMap IntSet) +scanItems et j ss chart = + closeChartAt et (j + 1) (IntMap.insert (j + 1) (IntSet.foldr advance IntMap.empty ss) chart) where - (n, chart) = prefixGen et word + eJ = chartAt j chart + advance s acc = case (IntMap.lookup s (transducerRelations et), IntMap.lookup s eJ) of + (Just (TransitionTokenClass _ ds), Just origs) -> + IntSet.foldr (\d -> IntMap.insertWith IntSet.union d origs) acc ds + _ -> acc + +{- | Scan tokens into a t'Chart', in order, or fail at a dead end. -} +scanChartMany + :: Categorized token => [token] -> Chart token -> Maybe (Chart token) +scanChartMany word chart0 = foldl' (\chart x -> chart >>= scanChart x) (Just chart0) word + +-- Scan the longest prefix of tokens which isn't a dead end. +scanChartLongest :: Categorized token => [token] -> Chart token -> Chart token +scanChartLongest word chart = case word of + x : xs | Just chart' <- scanChart x chart -> scanChartLongest xs chart' + _ -> chart + +{- | The t'TokenClass' of tokens which `scanChart` scans, the disjunction +of the classes of the scanner transitions out of the chart's last set. +-} +chartExpects :: Categorized token => Chart token -> TokenClass token +chartExpects (Chart et j chart) = anyP id (Set.fromList + [ cls + | s <- IntMap.keys (chartAt j chart) + , Just (TransitionTokenClass cls _) <- [IntMap.lookup s (transducerRelations et)] + ]) + +{- | Is a t'Chart''s prefix a word of the language? -} +chartAccepts :: Chart token -> Bool +chartAccepts (Chart _ j chart) = acceptsChart j chart + +chartAt :: Int -> IntMap (IntMap IntSet) -> IntMap IntSet +chartAt = IntMap.findWithDefault IntMap.empty {- | Rule names that can never be entered from the start @@ -475,20 +566,15 @@ scanClassOptions -> IntMap (IntMap IntSet) -> [(TokenClass token, IntMap (IntMap IntSet))] scanClassOptions et j chart = - [ (cls, closeChartAt et (j + 1) (IntMap.insert (j + 1) scanned chart)) - | (cls, scanned) <- Map.toAscList grouped + [ (cls, scanItems et j ss chart) + | (cls, ss) <- Map.toAscList grouped ] where - grouped = IntMap.foldrWithKey advance Map.empty eJ - eJ = IntMap.findWithDefault IntMap.empty j chart - - advance s origs acc = case IntMap.lookup s (transducerRelations et) of - Just (TransitionTokenClass cls ds) -> - Map.insertWith (IntMap.unionWith IntSet.union) cls scanned acc - where - scanned = IntSet.foldr - (\d -> IntMap.insertWith IntSet.union d origs) IntMap.empty ds - _ -> acc + grouped = Map.fromListWith IntSet.union + [ (cls, IntSet.singleton s) + | s <- IntMap.keys (chartAt j chart) + , Just (TransitionTokenClass cls _) <- [IntMap.lookup s (transducerRelations et)] + ] closeChartAt :: Transducer token diff --git a/distributors-grammar/test/Examples/Vocabulary.hs b/distributors-grammar/test/Examples/Vocabulary.hs new file mode 100644 index 00000000..14c13867 --- /dev/null +++ b/distributors-grammar/test/Examples/Vocabulary.hs @@ -0,0 +1,62 @@ +-- | Vocabularies & predictors, to decode the example grammars by, +-- & a reference decoder which masks its predictor every step. +module Examples.Vocabulary + ( vocabularyOf + , randomPredictor + , maskedDecode + ) where + +import Control.Lens.Grammar +import Control.Lens.Grammar.Decoding +import Data.Functor.Identity (Identity (..)) +import qualified Data.IntMap.Strict as IntMap +import Data.List (nub, tails) +import System.Random (mkStdGen, randoms) + +-- | A vocabulary of pieces like a sub-word tokenizer's: every token +-- of some words, & a few more, & the substrings of the words of +-- two to five tokens, with some junk. +vocabularyOf :: [String] -> [String] +vocabularyOf ws = nub $ + map pure (nub (concat ws <> " ;#")) + <> [ piece | w <- ws, t <- tails w, n <- [2 .. 5], let piece = take n t, length piece == n ] + <> ["#junk", ";;", " "] + +-- | A deterministic predictor over a vocabulary of a given size, which +-- weighs pieces pseudo-randomly, by a seed & the pieces so far, +-- with a given share of the weights zero. +randomPredictor :: Double -> Int -> Int -> Predictor Identity +randomPredictor zeros seed size pieces = Identity (Weights weights end) + where + gen = mkStdGen (foldl (\h i -> h * 1000003 + i + 1) seed pieces) + draws = take (size + 1) (randoms gen :: [Double]) + weights = IntMap.fromList + [ (i, if d < zeros then 0 else d) | (i, d) <- zip [0 .. size - 1] draws ] + end = last draws + +-- | Decoding which masks every step, the reference `decode` is +-- tested against, & benchmarked against. +maskedDecode + :: Monad m + => Chooser m -> Predictor m -> Vocabulary Char -> Int + -> Transducer Char -> m (Decoded Char) +maskedDecode chooser predict vocab bound et = go 0 [] [] (startChart et) + where + go n pieces chunks chart + | n >= bound = pure (Truncated text) + | otherwise = do + weights <- predict (reverse pieces) + let + allowed = allowedPieces vocab chart + masked = Weights + (IntMap.filter (> 0) (IntMap.intersectionWith const (pieceWeights weights) allowed)) + (if chartAccepts chart then max 0 (endWeight weights) else 0) + if IntMap.null (pieceWeights masked) && endWeight masked <= 0 + then pure (Stuck text) + else chooser masked >>= \case + Nothing -> pure (Finished text) + Just i -> case (IntMap.lookup i allowed, vocabularyPiece vocab i) of + (Just chart', Just piece) -> go (n + 1) (i : pieces) (piece : chunks) chart' + _ -> pure (Stuck text) + where + text = concat (reverse chunks) diff --git a/distributors-grammar/test/Main.hs b/distributors-grammar/test/Main.hs index 68902791..c95ef12d 100644 --- a/distributors-grammar/test/Main.hs +++ b/distributors-grammar/test/Main.hs @@ -19,6 +19,7 @@ import Examples.LenVec import Examples.RegString import Examples.SemVer import Examples.SExpr +import Properties.Decoding import Properties.Kleene import Properties.Varifocal @@ -38,6 +39,7 @@ main = hspec $ do describe "leftGrammar" $ testCfg True leftExamples leftGrammar describe "parseForest" parseForestTests describe "Parsector try rollback" tryRollbackTests + describe "Decoding" decodingProperties describe "Kleene" kleeneProperties describe "Varifocal" varifocalProperties diff --git a/distributors-grammar/test/Properties/Decoding.hs b/distributors-grammar/test/Properties/Decoding.hs new file mode 100644 index 00000000..3ca4f31a --- /dev/null +++ b/distributors-grammar/test/Properties/Decoding.hs @@ -0,0 +1,190 @@ +module Properties.Decoding (decodingProperties) where + +import Control.Lens.Grammar +import Control.Lens.Grammar.Decoding +import Control.Monad (forM_) +import Control.Monad.State (evalState, State) +import Data.Either (isRight) +import Data.Functor.Identity (Identity (..)) +import qualified Data.IntMap.Strict as IntMap +import Data.List (inits, nub) +import qualified Data.Map.Strict as Map +import Data.Map.Strict (Map) +import Data.Maybe (isJust) +import System.Random (StdGen, mkStdGen) +import Test.Hspec +import Test.Hspec.QuickCheck (modifyMaxSuccess, prop) +import Test.QuickCheck (choose, conjoin, counterexample, forAll, (===)) +import qualified Test.QuickCheck as QC + +import Examples.Arithmetic +import Examples.Json +import Examples.Lambda +import Examples.SemVer +import Examples.SExpr +import Examples.Vocabulary + +-- | A grammar under test, with words of its language, from which +-- an alphabet & a vocabulary are drawn, & how many times to test +-- properties which parse, as some grammars parse slowly: parseG +-- builds the JSON example's class of over a million tokens each run. +data Subject = forall a. Subject String (Grammar Char a) [String] Int + +subjects :: [Subject] +subjects = + [ Subject "json" jsonGrammar (map snd jsonExamples) 20 + , Subject "arith" arithGrammar (map snd arithExamples) 100 + , Subject "semver" semverGrammar (map snd semverExamples) 100 + , Subject "sexpr" sexprGrammar (map snd sexprExamples) 100 + , Subject "lambda" lambdaGrammar (map snd lambdaExamples) 100 + , Subject "regex" regexGrammar (map snd regexExamples') 100 + ] + where + regexExamples' = [((), s) | s <- ["a|b", "(ab)*c", "[a-z]+", "x?y"]] + +alphabetOf :: [String] -> String +alphabetOf ws = nub (concat ws <> " ;#") + +parses :: Grammar Char a -> String -> Bool +parses grammar w = not (null [() | (_, "") <- parseG grammar w]) + +decodingProperties :: Spec +decodingProperties = do + forM_ subjects $ \(Subject name grammar examples parsings) -> describe name $ do + let + parsing = modifyMaxSuccess (const parsings) + et = transducerG grammar + alphabet = alphabetOf examples + pieces = vocabularyOf examples + vocab = vocabulary pieces + -- words of the language, & strings of its alphabet, mostly not + wordsG = QC.elements examples + stringsG = QC.listOf (QC.elements alphabet) + candidatesG = QC.oneof [wordsG, stringsG, mutate =<< wordsG] + mutate w = do + i <- choose (0, length w) + c <- QC.elements alphabet + pure (take i w <> [c] <> drop (i + 1) w) + + parsing $ prop "a chart accepts the words parseG fully parses" $ + forAll candidatesG $ \w -> + maybe False chartAccepts (scanChartMany w (startChart et)) === parses grammar w + + prop "a chart expects exactly the tokens it scans" $ + forAll wordsG $ \w -> conjoin + [ counterexample (show (prefix, x)) $ + tokenClass (chartExpects chart) x === isJust (scanChart x chart) + | prefix <- inits w + , Just chart <- [scanChartMany prefix (startChart et)] + , x <- alphabet + ] + + prop "expectNext agrees with an incrementally scanned chart" $ + forAll candidatesG $ \w -> + expectNext et w + === maybe falseP chartExpects (scanChartMany w (startChart et)) + + prop "allowedPieces are the pieces a chart scans whole" $ + forAll wordsG $ \w -> conjoin + [ counterexample (show prefix) $ + IntMap.keys (allowedPieces vocab chart) + === [ i | (i, piece) <- zip [0 ..] pieces + , isJust (scanChartMany piece chart) ] + | prefix <- inits w + , Just chart <- [scanChartMany prefix (startChart et)] + ] + + parsing $ prop "sampling finishes at words of the language, & truncates at their prefixes" $ + \seed -> forAll (choose (1, 60)) $ \bound -> + let + predictor = randomPredictor 0.2 seed (length pieces) + decoded = evalState (decode sampled (lift' predictor) vocab bound et) (mkStdGen seed) + in counterexample (show decoded) $ case decoded of + Finished w -> parses grammar w + Truncated w -> isJust (scanChartMany w (startChart et)) + Stuck w -> isJust (scanChartMany w (startChart et)) + + prop "decoding by positive weights is stuck only where no piece is allowed" $ + \seed -> forAll (choose (1, 60)) $ \bound -> + let + predictor = randomPredictor 0 seed (length pieces) + decoded = evalState (decode sampled (lift' predictor) vocab bound et) (mkStdGen seed) + in counterexample (show decoded) $ case decoded of + Stuck w -> case scanChartMany w (startChart et) of + Just chart -> IntMap.null (allowedPieces vocab chart) && not (chartAccepts chart) + Nothing -> False + _ -> True + + prop "greedy decoding with opportunistic masking is decoding with a mask every step" $ + \seed -> forAll (choose (1, 60)) $ \bound -> + let predictor = randomPredictor 0.2 seed (length pieces) + in runIdentity (decode greedy predictor vocab bound et) + === runIdentity (maskedDecode greedy predictor vocab bound et) + + parsing $ prop "decodeG parses exactly when decoding finishes" $ + \seed -> forAll (choose (1, 60)) $ \bound -> + let + predictor = randomPredictor 0.2 seed (length pieces) + decoded = runIdentity (decode greedy predictor vocab bound et) + typed = runIdentity (decodeG greedy predictor vocab bound grammar) + in isRight typed === isFinished decoded + + describe "sampling with opportunistic masking" $ + it "samples as masking every step does" $ do + let + et = transducerG @Char smallG + vocab = vocabulary smallPieces + predictor = randomPredictor 0.2 11 (length smallPieces) + runs = 6000 :: Int + empirical = frequencies + [ evalState (decode sampled (lift' predictor) vocab 20 et) (mkStdGen seed) + | seed <- [1 .. runs] ] + exact = maskedProbabilities predictor vocab 20 et + forM_ (Map.toList exact) $ \(decoded, p) -> + Map.findWithDefault 0 decoded empirical `shouldSatisfy` (\q -> abs (q - p) < 0.03) + Map.keysSet empirical `shouldSatisfy` (`all'` (`Map.member` exact)) + where + lift' :: Predictor Identity -> Predictor (State StdGen) + lift' predictor = pure . runIdentity . predictor + isFinished = \case + Finished _ -> True + _ -> False + all' xs p = all p xs + +-- | A small language, with words which share prefixes, & pieces +-- which cross its words' parts. +smallG :: Grammar Char () +smallG = orP [terminal "true", terminal "truth", terminal "false", terminal "fa"] + +smallPieces :: [String] +smallPieces = ["t", "r", "u", "e", "h", "f", "a", "l", "s", "tr", "ue", "true", "th", "fa", "lse", "false"] + +frequencies :: Ord a => [a] -> Map a Double +frequencies xs = Map.map (/ fromIntegral (length xs)) (Map.fromListWith (+) [(x, 1) | x <- xs]) + +-- | The exact distribution of decoding by sampling from masked weights +-- every step, by enumerating every choice. +maskedProbabilities + :: Predictor Identity -> Vocabulary Char -> Int -> Transducer Char + -> Map (Decoded Char) Double +maskedProbabilities predict vocab bound et = + Map.fromListWith (+) (go 0 [] [] (startChart et) 1) + where + go n pieces chunks chart p + | n >= bound = [(Truncated text, p)] + | total <= 0 = [(Stuck text, p)] + | otherwise = + [(Finished text, p * end / total) | end > 0] + <> concat + [ go (n + 1) (i : pieces) (piece : chunks) chart' (p * w / total) + | (i, w) <- IntMap.toList ws + , Just chart' <- [IntMap.lookup i allowed] + , Just piece <- [vocabularyPiece vocab i] + ] + where + text = concat (reverse chunks) + weights = runIdentity (predict (reverse pieces)) + allowed = allowedPieces vocab chart + ws = IntMap.filter (> 0) (IntMap.intersectionWith const (pieceWeights weights) allowed) + end = if chartAccepts chart then max 0 (endWeight weights) else 0 + total = end + sum ws