{- |
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 <eitan.chatav@gmail.com>
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
  { Weights -> IntMap Double
pieceWeights :: IntMap Double
  , Weights -> Double
endWeight :: Double
  } deriving stock (Weights -> Weights -> Bool
(Weights -> Weights -> Bool)
-> (Weights -> Weights -> Bool) -> Eq Weights
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Weights -> Weights -> Bool
== :: Weights -> Weights -> Bool
$c/= :: Weights -> Weights -> Bool
/= :: Weights -> Weights -> Bool
Eq, Int -> Weights -> ShowS
[Weights] -> ShowS
Weights -> String
(Int -> Weights -> ShowS)
-> (Weights -> String) -> ([Weights] -> ShowS) -> Show Weights
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Weights -> ShowS
showsPrec :: Int -> Weights -> ShowS
$cshow :: Weights -> String
show :: Weights -> String
$cshowList :: [Weights] -> ShowS
showList :: [Weights] -> ShowS
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 (Decoded token -> Decoded token -> Bool
(Decoded token -> Decoded token -> Bool)
-> (Decoded token -> Decoded token -> Bool) -> Eq (Decoded token)
forall token. Eq token => Decoded token -> Decoded token -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: forall token. Eq token => Decoded token -> Decoded token -> Bool
== :: Decoded token -> Decoded token -> Bool
$c/= :: forall token. Eq token => Decoded token -> Decoded token -> Bool
/= :: Decoded token -> Decoded token -> Bool
Eq, Eq (Decoded token)
Eq (Decoded token) =>
(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)
-> (Decoded token -> Decoded token -> Decoded token)
-> (Decoded token -> Decoded token -> Decoded token)
-> Ord (Decoded token)
Decoded token -> Decoded token -> Bool
Decoded token -> Decoded token -> Ordering
Decoded token -> Decoded token -> Decoded token
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
forall token. Ord token => Eq (Decoded token)
forall token. Ord token => Decoded token -> Decoded token -> Bool
forall token.
Ord token =>
Decoded token -> Decoded token -> Ordering
forall token.
Ord token =>
Decoded token -> Decoded token -> Decoded token
$ccompare :: forall token.
Ord token =>
Decoded token -> Decoded token -> Ordering
compare :: Decoded token -> Decoded token -> Ordering
$c< :: forall token. Ord token => Decoded token -> Decoded token -> Bool
< :: Decoded token -> Decoded token -> Bool
$c<= :: forall token. Ord token => Decoded token -> Decoded token -> Bool
<= :: Decoded token -> Decoded token -> Bool
$c> :: forall token. Ord token => Decoded token -> Decoded token -> Bool
> :: Decoded token -> Decoded token -> Bool
$c>= :: forall token. Ord token => Decoded token -> Decoded token -> Bool
>= :: Decoded token -> Decoded token -> Bool
$cmax :: forall token.
Ord token =>
Decoded token -> Decoded token -> Decoded token
max :: Decoded token -> Decoded token -> Decoded token
$cmin :: forall token.
Ord token =>
Decoded token -> Decoded token -> Decoded token
min :: Decoded token -> Decoded token -> Decoded token
Ord, Int -> Decoded token -> ShowS
[Decoded token] -> ShowS
Decoded token -> String
(Int -> Decoded token -> ShowS)
-> (Decoded token -> String)
-> ([Decoded token] -> ShowS)
-> Show (Decoded token)
forall token. Show token => Int -> Decoded token -> ShowS
forall token. Show token => [Decoded token] -> ShowS
forall token. Show token => Decoded token -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: forall token. Show token => Int -> Decoded token -> ShowS
showsPrec :: Int -> Decoded token -> ShowS
$cshow :: forall token. Show token => Decoded token -> String
show :: Decoded token -> String
$cshowList :: forall token. Show token => [Decoded token] -> ShowS
showList :: [Decoded token] -> ShowS
Show, ReadPrec [Decoded token]
ReadPrec (Decoded token)
Int -> ReadS (Decoded token)
ReadS [Decoded token]
(Int -> ReadS (Decoded token))
-> ReadS [Decoded token]
-> ReadPrec (Decoded token)
-> ReadPrec [Decoded token]
-> Read (Decoded token)
forall token. Read token => ReadPrec [Decoded token]
forall token. Read token => ReadPrec (Decoded token)
forall token. Read token => Int -> ReadS (Decoded token)
forall token. Read token => ReadS [Decoded token]
forall a.
(Int -> ReadS a)
-> ReadS [a] -> ReadPrec a -> ReadPrec [a] -> Read a
$creadsPrec :: forall token. Read token => Int -> ReadS (Decoded token)
readsPrec :: Int -> ReadS (Decoded token)
$creadList :: forall token. Read token => ReadS [Decoded token]
readList :: ReadS [Decoded token]
$creadPrec :: forall token. Read token => ReadPrec (Decoded token)
readPrec :: ReadPrec (Decoded token)
$creadListPrec :: forall token. Read token => ReadPrec [Decoded token]
readListPrec :: ReadPrec [Decoded token]
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 :: forall (m :: * -> *). Applicative m => Chooser m
greedy (Weights IntMap Double
pieces Double
end) = Maybe Int -> m (Maybe Int)
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ((Maybe Int -> Int -> Double -> Maybe Int)
-> Maybe Int -> IntMap Double -> Maybe Int
forall a b. (a -> Int -> b -> a) -> a -> IntMap b -> a
IntMap.foldlWithKey' Maybe Int -> Int -> Double -> Maybe Int
heavier Maybe Int
forall a. Maybe a
Nothing IntMap Double
pieces')
  where
    pieces' :: IntMap Double
pieces' = (Double -> Bool) -> IntMap Double -> IntMap Double
forall a. (a -> Bool) -> IntMap a -> IntMap a
IntMap.filter (Double -> Double -> Bool
forall a. Ord a => a -> a -> Bool
> Double -> Double -> Double
forall a. Ord a => a -> a -> a
max Double
0 Double
end) IntMap Double
pieces
    heavier :: Maybe Int -> Int -> Double -> Maybe Int
heavier Maybe Int
best Int
i Double
w = case Maybe Int
best of
      Just Int
j | IntMap Double
pieces' IntMap Double -> Int -> Double
forall a. IntMap a -> Int -> a
IntMap.! Int
j Double -> Double -> Bool
forall a. Ord a => a -> a -> Bool
>= Double
w -> Maybe Int
best
      Maybe Int
_ -> Int -> Maybe Int
forall a. a -> Maybe a
Just Int
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 :: forall g (m :: * -> *).
(RandomGen g, Monad m) =>
Chooser (StateT g m)
sampled (Weights IntMap Double
pieces Double
end) = do
  r <- (g -> (Double, g)) -> StateT g m Double
forall a. (g -> (a, g)) -> StateT g m a
forall s (m :: * -> *) a. MonadState s m => (s -> (a, s)) -> m a
state ((Double, Double) -> g -> (Double, g)
forall g. RandomGen g => (Double, Double) -> g -> (Double, g)
forall a g. (Random a, RandomGen g) => (a, a) -> g -> (a, g)
randomR (Double
0, Double
total))
  pure (pick r)
  where
    end' :: Double
end' = Double -> Double -> Double
forall a. Ord a => a -> a -> a
max Double
0 Double
end
    pieces' :: [(Int, Double)]
pieces' = IntMap Double -> [(Int, Double)]
forall a. IntMap a -> [(Int, a)]
IntMap.toList ((Double -> Bool) -> IntMap Double -> IntMap Double
forall a. (a -> Bool) -> IntMap a -> IntMap a
IntMap.filter (Double -> Double -> Bool
forall a. Ord a => a -> a -> Bool
> Double
0) IntMap Double
pieces)
    total :: Double
total = Double
end' Double -> Double -> Double
forall a. Num a => a -> a -> a
+ [Double] -> Double
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum (((Int, Double) -> Double) -> [(Int, Double)] -> [Double]
forall a b. (a -> b) -> [a] -> [b]
map (Int, Double) -> Double
forall a b. (a, b) -> b
snd [(Int, Double)]
pieces')
    pick :: Double -> Maybe Int
pick Double
r
      | Double
r Double -> Double -> Bool
forall a. Ord a => a -> a -> Bool
< Double
end' Bool -> Bool -> Bool
|| [(Int, Double)] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [(Int, Double)]
pieces' = Maybe Int
forall a. Maybe a
Nothing
      | Bool
otherwise = Double -> [(Int, Double)] -> Maybe Int
forall {t} {a}. (Ord t, Num t) => t -> [(a, t)] -> Maybe a
go (Double
r Double -> Double -> Double
forall a. Num a => a -> a -> a
- Double
end') [(Int, Double)]
pieces'
    go :: t -> [(a, t)] -> Maybe a
go t
_ [(a
i, t
_)] = a -> Maybe a
forall a. a -> Maybe a
Just a
i
    go t
r ((a
i, t
w) : [(a, t)]
rest)
      | t
r t -> t -> Bool
forall a. Ord a => a -> a -> Bool
< t
w = a -> Maybe a
forall a. a -> Maybe a
Just a
i
      | Bool
otherwise = t -> [(a, t)] -> Maybe a
go (t
r t -> t -> t
forall a. Num a => a -> a -> a
- t
w) [(a, t)]
rest
    go t
_ [] = Maybe a
forall a. Maybe a
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
  { forall token. Vocabulary token -> IntMap [token]
vocabularyPieces :: IntMap [token]
  , forall token. Vocabulary token -> Trie 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 :: forall token. Ord token => [[token]] -> Vocabulary token
vocabulary [[token]]
pieces = Vocabulary
  { vocabularyPieces :: IntMap [token]
vocabularyPieces = [(Int, [token])] -> IntMap [token]
forall a. [(Int, a)] -> IntMap a
IntMap.fromList [(Int, [token])]
indexed
  , vocabularyTrie :: Trie token
vocabularyTrie = (Trie token -> (Int, [token]) -> Trie token)
-> Trie token -> [(Int, [token])] -> Trie token
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' Trie token -> (Int, [token]) -> Trie token
forall {a}. Ord a => Trie a -> (Int, [a]) -> Trie a
insert (IntSet -> Map token (Trie token) -> Trie token
forall token. IntSet -> Map token (Trie token) -> Trie token
Trie IntSet
IntSet.empty Map token (Trie token)
forall k a. Map k a
Map.empty) [(Int, [token])]
indexed
  }
  where
    indexed :: [(Int, [token])]
indexed = [(Int
i, [token]
piece) | (Int
i, [token]
piece) <- [Int] -> [[token]] -> [(Int, [token])]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] [[token]]
pieces, Bool -> Bool
not ([token] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [token]
piece)]
    insert :: Trie a -> (Int, [a]) -> Trie a
insert (Trie IntSet
ends Map a (Trie a)
next) (Int
i, [a]
piece) = case [a]
piece of
      [] -> IntSet -> Map a (Trie a) -> Trie a
forall token. IntSet -> Map token (Trie token) -> Trie token
Trie (Int -> IntSet -> IntSet
IntSet.insert Int
i IntSet
ends) Map a (Trie a)
next
      a
x : [a]
xs -> IntSet -> Map a (Trie a) -> Trie a
forall token. IntSet -> Map token (Trie token) -> Trie token
Trie IntSet
ends ((Maybe (Trie a) -> Maybe (Trie a))
-> a -> Map a (Trie a) -> Map a (Trie a)
forall k a.
Ord k =>
(Maybe a -> Maybe a) -> k -> Map k a -> Map k a
Map.alter (Trie a -> Maybe (Trie a)
forall a. a -> Maybe a
Just (Trie a -> Maybe (Trie a))
-> (Maybe (Trie a) -> Trie a) -> Maybe (Trie a) -> Maybe (Trie a)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Maybe (Trie a) -> Trie a
grow) a
x Map a (Trie a)
next)
        where grow :: Maybe (Trie a) -> Trie a
grow Maybe (Trie a)
sub = Trie a -> (Int, [a]) -> Trie a
insert (Trie a -> Maybe (Trie a) -> Trie a
forall a. a -> Maybe a -> a
fromMaybe (IntSet -> Map a (Trie a) -> Trie a
forall token. IntSet -> Map token (Trie token) -> Trie token
Trie IntSet
IntSet.empty Map a (Trie a)
forall k a. Map k a
Map.empty) Maybe (Trie a)
sub) (Int
i, [a]
xs)

{- | The string of tokens a piece stands for, by index. -}
vocabularyPiece :: Vocabulary token -> Int -> Maybe [token]
vocabularyPiece :: forall token. Vocabulary token -> Int -> Maybe [token]
vocabularyPiece Vocabulary token
vocab Int
i = Int -> IntMap [token] -> Maybe [token]
forall a. Int -> IntMap a -> Maybe a
IntMap.lookup Int
i (Vocabulary token -> IntMap [token]
forall token. Vocabulary token -> IntMap [token]
vocabularyPieces Vocabulary token
vocab)

{- | The number of nonempty pieces in a t'Vocabulary'. -}
vocabularySize :: Vocabulary token -> Int
vocabularySize :: forall token. Vocabulary token -> Int
vocabularySize = IntMap [token] -> Int
forall a. IntMap a -> Int
IntMap.size (IntMap [token] -> Int)
-> (Vocabulary token -> IntMap [token]) -> Vocabulary token -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Vocabulary token -> IntMap [token]
forall token. Vocabulary token -> IntMap [token]
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 :: forall token.
Categorized token =>
Vocabulary token -> Chart token -> IntMap (Chart token)
allowedPieces Vocabulary token
vocab Chart token
chart0 = (IntMap (Chart token), Memo token) -> IntMap (Chart token)
forall a b. (a, b) -> a
fst (Trie token
-> Int
-> (IntMap (Chart token), Memo token)
-> (IntMap (Chart token), Memo token)
forall {p}.
Categorized p =>
Trie p
-> Int -> (IntMap (Chart p), Memo p) -> (IntMap (Chart p), Memo p)
walk (Vocabulary token -> Trie token
forall token. Vocabulary token -> Trie token
vocabularyTrie Vocabulary token
vocab) Int
0 (IntMap (Chart token)
forall a. IntMap a
IntMap.empty, Memo token
memo0))
  where
    memo0 :: Memo token
memo0 = IntMap (Chart token)
-> IntMap (Map token (Maybe (Int, Chart token)))
-> Map (Int, Scan) Int
-> Memo token
forall token.
IntMap (Chart token)
-> IntMap (Map token (Maybe (Int, Chart token)))
-> Map (Int, Scan) Int
-> Memo token
Memo (Int -> Chart token -> IntMap (Chart token)
forall a. Int -> a -> IntMap a
IntMap.singleton Int
0 Chart token
chart0) IntMap (Map token (Maybe (Int, Chart token)))
forall a. IntMap a
IntMap.empty Map (Int, Scan) Int
forall k a. Map k a
Map.empty

    walk :: Trie p
-> Int -> (IntMap (Chart p), Memo p) -> (IntMap (Chart p), Memo p)
walk (Trie IntSet
_ Map p (Trie p)
next) Int
chartId (IntMap (Chart p), Memo p)
accMemo = ((IntMap (Chart p), Memo p)
 -> p -> Trie p -> (IntMap (Chart p), Memo p))
-> (IntMap (Chart p), Memo p)
-> Map p (Trie p)
-> (IntMap (Chart p), Memo p)
forall a k b. (a -> k -> b -> a) -> a -> Map k b -> a
Map.foldlWithKey' (IntMap (Chart p), Memo p)
-> p -> Trie p -> (IntMap (Chart p), Memo p)
step (IntMap (Chart p), Memo p)
accMemo Map p (Trie p)
next
      where
        step :: (IntMap (Chart p), Memo p)
-> p -> Trie p -> (IntMap (Chart p), Memo p)
step (IntMap (Chart p)
acc, Memo p
memo) p
x sub :: Trie p
sub@(Trie IntSet
ends Map p (Trie p)
next') = case Int -> p -> Memo p -> (Maybe (Int, Chart p), Memo p)
forall {token}.
Categorized token =>
Int
-> token -> Memo token -> (Maybe (Int, Chart token), Memo token)
scanned Int
chartId p
x Memo p
memo of
          (Maybe (Int, Chart p)
Nothing, Memo p
memo') -> IntMap (Chart p)
acc IntMap (Chart p)
-> (IntMap (Chart p), Memo p) -> (IntMap (Chart p), Memo p)
forall a b. a -> b -> b
`seq` (IntMap (Chart p)
acc, Memo p
memo')
          (Just (Int
chartId', Chart p
chart'), Memo p
memo') ->
            let acc' :: IntMap (Chart p)
acc' = (IntMap (Chart p) -> Int -> IntMap (Chart p))
-> IntMap (Chart p) -> IntSet -> IntMap (Chart p)
forall a. (a -> Int -> a) -> a -> IntSet -> a
IntSet.foldl' (\IntMap (Chart p)
m Int
i -> Int -> Chart p -> IntMap (Chart p) -> IntMap (Chart p)
forall a. Int -> a -> IntMap a -> IntMap a
IntMap.insert Int
i Chart p
chart' IntMap (Chart p)
m) IntMap (Chart p)
acc IntSet
ends
            in if Map p (Trie p) -> Bool
forall k a. Map k a -> Bool
Map.null Map p (Trie p)
next'
              then IntMap (Chart p)
acc' IntMap (Chart p)
-> (IntMap (Chart p), Memo p) -> (IntMap (Chart p), Memo p)
forall a b. a -> b -> b
`seq` (IntMap (Chart p)
acc', Memo p
memo')
              else Trie p
-> Int -> (IntMap (Chart p), Memo p) -> (IntMap (Chart p), Memo p)
walk Trie p
sub Int
chartId' (IntMap (Chart p)
acc', Memo p
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 :: Int
-> token -> Memo token -> (Maybe (Int, Chart token), Memo token)
scanned Int
chartId token
x Memo token
memo = case token
-> Map token (Maybe (Int, Chart token))
-> Maybe (Maybe (Int, Chart token))
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup token
x Map token (Maybe (Int, Chart token))
table of
      Just Maybe (Int, Chart token)
next -> (Maybe (Int, Chart token)
next, Memo token
memo)
      Maybe (Maybe (Int, Chart token))
Nothing -> (Maybe (Int, Chart token)
next, Memo token
memo'
        { memoNext = IntMap.insert chartId (Map.insert x next table) (memoNext memo') })
        where
          chart :: Chart token
chart = Memo token -> IntMap (Chart token)
forall token. Memo token -> IntMap (Chart token)
memoCharts Memo token
memo IntMap (Chart token) -> Int -> Chart token
forall a. IntMap a -> Int -> a
IntMap.! Int
chartId
          scan :: Scan
scan = token -> Chart token -> Scan
forall token. Categorized token => token -> Chart token -> Scan
chartScan token
x Chart token
chart
          (Maybe (Int, Chart token)
next, Memo token
memo')
            | Scan -> Bool
nullScan Scan
scan = (Maybe (Int, Chart token)
forall a. Maybe a
Nothing, Memo token
memo)
            | Bool
otherwise = case (Int, Scan) -> Map (Int, Scan) Int -> Maybe Int
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup (Int
chartId, Scan
scan) (Memo token -> Map (Int, Scan) Int
forall token. Memo token -> Map (Int, Scan) Int
memoScanned Memo token
memo) of
                Just Int
chartId' -> ((Int, Chart token) -> Maybe (Int, Chart token)
forall a. a -> Maybe a
Just (Int
chartId', Memo token -> IntMap (Chart token)
forall token. Memo token -> IntMap (Chart token)
memoCharts Memo token
memo IntMap (Chart token) -> Int -> Chart token
forall a. IntMap a -> Int -> a
IntMap.! Int
chartId'), Memo token
memo)
                Maybe Int
Nothing ->
                  let
                    chartId' :: Int
chartId' = IntMap (Chart token) -> Int
forall a. IntMap a -> Int
IntMap.size (Memo token -> IntMap (Chart token)
forall token. Memo token -> IntMap (Chart token)
memoCharts Memo token
memo)
                    chart' :: Chart token
chart' = Chart token -> Maybe (Chart token) -> Chart token
forall a. a -> Maybe a -> a
fromMaybe (String -> Chart token
forall a. HasCallStack => String -> a
error String
"allowedPieces: an empty scan")
                      (Scan -> Chart token -> Maybe (Chart token)
forall token. Scan -> Chart token -> Maybe (Chart token)
scanChartBy Scan
scan Chart token
chart)
                  in
                    ( (Int, Chart token) -> Maybe (Int, Chart token)
forall a. a -> Maybe a
Just (Int
chartId', Chart token
chart')
                    , Memo token
memo
                      { memoCharts = LazyIntMap.insert chartId' chart' (memoCharts memo)
                      , memoScanned = Map.insert (chartId, scan) chartId' (memoScanned memo)
                      }
                    )
      where
        table :: Map token (Maybe (Int, Chart token))
table = Map token (Maybe (Int, Chart token))
-> Int
-> IntMap (Map token (Maybe (Int, Chart token)))
-> Map token (Maybe (Int, Chart token))
forall a. a -> Int -> IntMap a -> a
IntMap.findWithDefault Map token (Maybe (Int, Chart token))
forall k a. Map k a
Map.empty Int
chartId (Memo token -> IntMap (Map token (Maybe (Int, Chart token)))
forall token.
Memo token -> IntMap (Map token (Maybe (Int, Chart token)))
memoNext Memo token
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
  { forall token. Memo token -> IntMap (Chart token)
memoCharts :: IntMap (Chart token)
  -- ^ lazily, so a chart's only closed once a piece is scanned from it
  , forall token.
Memo token -> IntMap (Map token (Maybe (Int, Chart token)))
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
  , forall token. Memo token -> Map (Int, Scan) Int
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 :: forall token (m :: * -> *).
(Categorized token, Monad m) =>
Chooser m
-> Predictor m
-> Vocabulary token
-> Int
-> Transducer token
-> m (Decoded token)
decode Chooser m
choose Predictor m
predict Vocabulary token
vocab Int
bound Transducer token
et = Int -> [Int] -> [[token]] -> Chart token -> m (Decoded token)
go Int
0 [] [] (Transducer token -> Chart token
forall token. Transducer token -> Chart token
startChart Transducer token
et)
  where
    go :: Int -> [Int] -> [[token]] -> Chart token -> m (Decoded token)
go Int
n [Int]
pieces [[token]]
chunks Chart token
chart
      | Int
n Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
bound = Decoded token -> m (Decoded token)
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([token] -> Decoded token
forall token. [token] -> Decoded token
Truncated [token]
text)
      | Bool
otherwise = do
          weights <- Predictor m
predict ([Int] -> [Int]
forall a. [a] -> [a]
reverse [Int]
pieces)
          choice <- choose weights
          case choice of
            Maybe Int
Nothing | Chart token -> Bool
forall token. Chart token -> Bool
chartAccepts Chart token
chart, Weights -> Double
endWeight Weights
weights Double -> Double -> Bool
forall a. Ord a => a -> a -> Bool
> Double
0 -> Decoded token -> m (Decoded token)
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([token] -> Decoded token
forall token. [token] -> Decoded token
Finished [token]
text)
            Just Int
i
              | Just [token]
piece <- Vocabulary token -> Int -> Maybe [token]
forall token. Vocabulary token -> Int -> Maybe [token]
vocabularyPiece Vocabulary token
vocab Int
i
              , Just Chart token
chart' <- [token] -> Chart token -> Maybe (Chart token)
forall token.
Categorized token =>
[token] -> Chart token -> Maybe (Chart token)
scanChartMany [token]
piece Chart token
chart ->
                  Int -> [Int] -> [[token]] -> Chart token -> m (Decoded token)
go (Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) (Int
i Int -> [Int] -> [Int]
forall a. a -> [a] -> [a]
: [Int]
pieces) ([token]
piece [token] -> [[token]] -> [[token]]
forall a. a -> [a] -> [a]
: [[token]]
chunks) Chart token
chart'
            -- the unmasked choice isn't allowed, so mask & choose again
            Maybe Int
_ -> do
              let
                allowed :: IntMap (Chart token)
allowed = Vocabulary token -> Chart token -> IntMap (Chart token)
forall token.
Categorized token =>
Vocabulary token -> Chart token -> IntMap (Chart token)
allowedPieces Vocabulary token
vocab Chart token
chart
                masked :: Weights
masked = Weights
                  { pieceWeights :: IntMap Double
pieceWeights = (Double -> Bool) -> IntMap Double -> IntMap Double
forall a. (a -> Bool) -> IntMap a -> IntMap a
IntMap.filter (Double -> Double -> Bool
forall a. Ord a => a -> a -> Bool
> Double
0)
                      ((Double -> Chart token -> Double)
-> IntMap Double -> IntMap (Chart token) -> IntMap Double
forall a b c. (a -> b -> c) -> IntMap a -> IntMap b -> IntMap c
IntMap.intersectionWith Double -> Chart token -> Double
forall a b. a -> b -> a
const (Weights -> IntMap Double
pieceWeights Weights
weights) IntMap (Chart token)
allowed)
                  , endWeight :: Double
endWeight = if Chart token -> Bool
forall token. Chart token -> Bool
chartAccepts Chart token
chart then Double -> Double -> Double
forall a. Ord a => a -> a -> a
max Double
0 (Weights -> Double
endWeight Weights
weights) else Double
0
                  }
              if IntMap Double -> Bool
forall a. IntMap a -> Bool
IntMap.null (Weights -> IntMap Double
pieceWeights Weights
masked) Bool -> Bool -> Bool
&& Weights -> Double
endWeight Weights
masked Double -> Double -> Bool
forall a. Ord a => a -> a -> Bool
<= Double
0
                then Decoded token -> m (Decoded token)
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([token] -> Decoded token
forall token. [token] -> Decoded token
Stuck [token]
text)
                else do
                  choice' <- Chooser m
choose Weights
masked
                  case choice' of
                    Maybe Int
Nothing | Weights -> Double
endWeight Weights
masked Double -> Double -> Bool
forall a. Ord a => a -> a -> Bool
> Double
0 -> Decoded token -> m (Decoded token)
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([token] -> Decoded token
forall token. [token] -> Decoded token
Finished [token]
text)
                    Just Int
i
                      | Just Chart token
chart' <- Int -> IntMap (Chart token) -> Maybe (Chart token)
forall a. Int -> IntMap a -> Maybe a
IntMap.lookup Int
i IntMap (Chart token)
allowed
                      , Just [token]
piece <- Vocabulary token -> Int -> Maybe [token]
forall token. Vocabulary token -> Int -> Maybe [token]
vocabularyPiece Vocabulary token
vocab Int
i ->
                          Int -> [Int] -> [[token]] -> Chart token -> m (Decoded token)
go (Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) (Int
i Int -> [Int] -> [Int]
forall a. a -> [a] -> [a]
: [Int]
pieces) ([token]
piece [token] -> [[token]] -> [[token]]
forall a. a -> [a] -> [a]
: [[token]]
chunks) Chart token
chart'
                    Maybe Int
_ -> Decoded token -> m (Decoded token)
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([token] -> Decoded token
forall token. [token] -> Decoded token
Stuck [token]
text)
      where
        text :: [token]
text = [[token]] -> [token]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat ([[token]] -> [[token]]
forall a. [a] -> [a]
reverse [[token]]
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 :: forall token (m :: * -> *) a.
(Categorized token, Monad m) =>
Chooser m
-> Predictor m
-> Vocabulary token
-> Int
-> Grammar token a
-> m (Either (Decoded token) a)
decodeG Chooser m
choose Predictor m
predict Vocabulary token
vocab Int
bound Grammar token a
grammar = do
  decoded <- Chooser m
-> Predictor m
-> Vocabulary token
-> Int
-> Transducer token
-> m (Decoded token)
forall token (m :: * -> *).
(Categorized token, Monad m) =>
Chooser m
-> Predictor m
-> Vocabulary token
-> Int
-> Transducer token
-> m (Decoded token)
decode Chooser m
choose Predictor m
predict Vocabulary token
vocab Int
bound (Grammar token a -> Transducer token
forall token a.
Categorized token =>
Grammar token a -> Transducer token
transducerG p a a
Grammar token a
grammar)
  pure $ case decoded of
    Finished [token]
word | (a
a, []) : [(a, [token])]
_ <- CtxGrammar token a -> [token] -> [(a, [token])]
forall string token (m :: * -> *) a.
(Cons string string token token, Snoc string string token token,
 IsList string, Item string ~ token, Categorized token,
 Alternative m, Monad m, Filterable m) =>
CtxGrammar token a -> string -> m (a, string)
parseG p a a
CtxGrammar token a
Grammar token a
grammar [token]
word -> a -> Either (Decoded token) a
forall a b. b -> Either a b
Right a
a
    Decoded token
_ -> Decoded token -> Either (Decoded token) a
forall a b. a -> Either a b
Left Decoded token
decoded