Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions distributors-grammar/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion distributors-grammar/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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".
45 changes: 44 additions & 1 deletion distributors-grammar/bench/Main.hs
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -22,6 +24,7 @@ import Examples.Json
import Examples.Lambda
import Examples.SemVer
import Examples.SExpr
import Examples.Vocabulary

main :: IO ()
main = do
Expand All @@ -32,6 +35,7 @@ main = do
, backends "example" examples
, pure statics
, pure optics
, pure decodings
]
defaultMain groups

Expand Down Expand Up @@ -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
4 changes: 4 additions & 0 deletions distributors-grammar/distributors-grammar.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -176,6 +177,8 @@ test-suite test
Examples.RegString
Examples.SemVer
Examples.SExpr
Examples.Vocabulary
Properties.Decoding
Properties.Kleene
Properties.Varifocal
Paths_distributors_grammar
Expand Down Expand Up @@ -251,6 +254,7 @@ benchmark core
Examples.Lambda
Examples.SemVer
Examples.SExpr
Examples.Vocabulary
hs-source-dirs:
bench
test
Expand Down
1 change: 1 addition & 0 deletions distributors-grammar/package.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ benchmarks:
- Examples.Lambda
- Examples.SemVer
- Examples.SExpr
- Examples.Vocabulary
ghc-options:
- -O2
- -rtsopts
Expand Down
Loading
Loading