Add basic parser-driven masking utilities #131
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR introduces utilities for parser-driven masking: i.e. a parser is run alongside a language model's (LM) token sampling step and used to filter for grammar-valid next tokens.
lark
was chosen as the underlying parser library because I have previous experience using it, its design is fairly straightforward, it's pure Python, and it supports arbitrary EBNF-like grammars.The current approach is very experimental and is essentially driven by some patches to
lark
's LALR parser. Those patches allow for incremental additions to a lexed/parsed string, and, more importantly, they allow for partial token matches during scanning. Partial tokens arise when the string being scanned cuts off without completely constructing/finalizing a token.For example, the source string
"def fo"
would normally be scanned into two tokensdef
andfo
; however, if the next LM-sampled token is"o("
, the complete sampled source string would be"def foo("
, and the parsed result would be the tokensdef
,foo
,(
. These two scan (or parse) results conflict, because the first one ends by assuming thatfo
is a completed name token, but the next result—when starting from the beginning—contains no such token. In other words, we would need to backtrack in order to find the "correct" name token (i.e.foo
).The approach currently used in this PR doesn't immediately accept (i.e. advance the parse state) scan results from tokens with ambiguities like that.