This library implements constrained decoding (also called constrained sampling or structured outputs) for Large Langauge Models (LLMs). It can enforce arbitrary context-free grammar on the output of LLM and is fast - on the order of 100us of CPU time per token (for 128k tokenizer) with negligible startup costs.
Following grammar formats are supported:
llguidance
- internal (JSON-based) format- regular expressions (following Rust regex crate syntax)
- a large subset of JSON schemas (but see issue)
- context-free grammars in (a subset of) Lark format
The internal format is most powerful (though lark-like format is catching up) and can be generated by the following libraries:
- Guidance (Python)
- guidance.ts (TypeScript)
- hopefully more to come!
The library can be used from:
The library is currently integrated in:
- Guidance - library for interacting with LLMs; uses either llama.cpp or HF Tranformers
- LLGTRT - OpenAI-compatible REST server using NVIDIA's TensorRT-LLM
- mistral.rs
The integration is ongoing in:
- onnxruntime-genai - draft PR
- llama.cpp - preliminary PR; note that llama.cpp is fully integrated in Guidance above via Python bindings
Given a context-free grammar, a tokenizer, and a prefix of tokens, llguidance computes a token mask - a set of tokens from the tokenizer - that, when added to the current token prefix, can lead to a valid string in the language defined by the grammar. Mask computation takes approximately 100us of single-core CPU time for a tokenizer with 128k tokens. While this timing depends on the exact grammar, it holds, for example, for grammars derived from JSON schemas. There is no significant startup cost.
The library implements a context-free grammar parser using Earley’s algorithm on top of a lexer based on derivatives of regular expressions. Mask computation is achieved by traversing the prefix tree (trie) of all possible tokens, leveraging highly optimized code.
LM-format-enforcer and llama.cpp grammars are similar to llguidance in that they dynamically build token masks for every step of the decoding process. Both are significantly slower - the former due to clean Python code and the latter due to the lack of a lexer and use of a backtracking parser, which, while elegant, is inefficient.
Outlines builds an automaton from constraints and then pre-computes token masks for all automaton states, making sampling fast but inherently limiting constraint complexity and introducing significant startup cost and memory overhead. Llguidance computes token masks on the fly and has essentially no startup cost. The lexer’s automata in llguidance are built lazily and are typically much smaller, as the context-free grammar imposes the top-level structure.
Recently released XGrammar follows an approach similar to llama.cpp (explicit stack-based, character-level parser) with additional pre-computation of certain token masks, similar to Outlines. The pre-computation often runs into seconds, and sometimes minutes. If the pre-computation works well for a given input, the masks are computed quickly (under 50us in half of masks we tested), however if it doesn't fit the particular input, the mask computation times can run into seconds. Avarage mask computation time, for masks under 10ms was 277us, however over 3% of masks took longer than 10ms (with avarage time of over 1s).
In llguidance, the full mask computation for a typical JSON schema takes about 1.5ms (for 128k tokenizer). However, very often the "slicer" optimization applies, and thus the avarage mask computation in a large JSON benchmark suite (2M tokens, 10k schemas) is well under 100us, with 1% of masks taking longer than 1ms, and 0.001% taking longer than 10ms (but still shorter than 30ms). The optimization doesn't involve any significant pre-computation.
Thus, with 16 cores and a 10ms forward pass, llguidance can handle batch sizes up to 1600 without slowing down the model. (Note that a 10ms forward pass for small batch sizes typically increases to 20ms+ for batch sizes of 100-200.)
- install rust; 1.75 or later
If you just need the C or Rust library (llguidance
),
check the parser directory.
For Python bindings:
- install python 3.9 or later; very likely you'll need a virtual env/conda
- run
./scripts/install-deps.sh
- to build and after any changes, run
./scripts/test-guidance.sh
This builds the Python bindings for the library and runs the tests (which mostly live in the Guidance repo - it will clone it).
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.
When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.
This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.
This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft's Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies.