Skip to content

Fix incompleteness of regex and cfg guided generation #544

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jan 24, 2024
Merged
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
48 changes: 39 additions & 9 deletions examples/cfg.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import outlines.generate as generate
import outlines.models as models

# examples from https://lark-parser.readthedocs.io/en/latest/examples/index.html

nlamb_grammar = """
nlamb_grammar = r"""
start: sentence

sentence: noun verb noun -> simple
Expand All @@ -21,7 +19,7 @@
%ignore WS
"""

calc_grammar = """
calc_grammar = r"""
?start: sum
| NAME "=" sum -> assign_var

Expand All @@ -38,22 +36,54 @@
| NAME -> var
| "(" sum ")"

%import common.CNAME -> NAME
%import common.NUMBER
%import common.LETTER -> NAME
%import common.INT -> NUMBER
%import common.WS_INLINE

%ignore WS_INLINE
"""

dyck_grammar = r"""
start: s
s: /a+/
| "(" s ")"
| "{" s "}"
| "[" s "]"
"""

json_grammar = r"""
?start: value

?value: object
| array
| string
| SIGNED_NUMBER -> number
| "true" -> true
| "false" -> false
| "null" -> null

array : "[" [value ("," value)*] "]"
object : "{" [pair ("," pair)*] "}"
pair : string ":" value

inner: /([^"]|\\\")+/ |
string : "\"" inner "\""

%import common.SIGNED_NUMBER
%import common.WS

%ignore WS
"""

model = models.transformers("hf-internal-testing/tiny-random-gpt2")
batch_size = 10
for grammar in [nlamb_grammar, calc_grammar]:
generator = generate.cfg(model, grammar)
for grammar in [nlamb_grammar, calc_grammar, dyck_grammar, json_grammar]:
generator = generate.cfg(model, grammar, max_tokens=model.model.config.n_positions)
sequences = generator([" "] * batch_size)
for seq in sequences:
try:
parse = generator.fsm.parser.parse(seq)
assert parse is not None
print("SUCCESS", seq)
except Exception:
except Exception: # will also fail if goes over max_tokens / context window
print("FAILURE", seq)
Loading