Crates.io | kbnf |
lib.rs | kbnf |
version | 0.5.5 |
source | src |
created_at | 2024-06-14 00:51:56.587722 |
updated_at | 2024-10-25 23:55:54.783509 |
description | A fast constrained decoding engine based on context free grammar. |
homepage | |
repository | https://github.com/Dan-Wanna-M/kbnf |
max_upload_size | |
id | 1271574 |
size | 5,710,654 |
This crate provides a constrained decoding engine which ensures that a language model's output adheres strictly to the format defined by KBNF (Koishi's BNF), an enhanced variant of EBNF. KBNF includes features that enhance usability, notably embeddable regular expressions.
If you are interested in the design and implementation behind this crate, you may want to check out my blog.
n
is the generated text length and m
is the vocabulary size.n
has a fixed upper bound, or the grammar is regular.Simply add it to your Cargo.toml
or run cargo add kbnf
in your command line.
One of the goals of this crate is for the constrained decoding engine to be "fast." This can be interpreted both theoretically and practically.
Theoretically, this crate is designed to provide the asymptotically fastest algorithms for each subclass of context free grammar. By implementing an Earley recognizer with Leo optimization, this crate has successfully achieve linear time complexity for every LR(k) grammar and quadratic time complexity for every unambiguous grammar. For general context free grammar, things are more ambiguous(pun intended): while subcubic algorithms exist(although with a large constant), all other general-purpose parsing algorithms(like Earley, GLR, GLL...) are indeed cubic, like ours.
Practically, this crate tries to make the engine be as efficient as possible for grammars used in practice. While many improvements, such as Earley sets compaction and lazy caching, have been made, this is inherently an ongoing process. If you find the engine is a bottleneck in your application, feel free to open an issue.