Expand description
Safe, idiomatic Rust bindings for the xgrammar C++ library for constrained decoding of large language models.
This crate wraps xgrammar’s grammar compilation and token-level matching so you can drive constrained generation (JSON schema, regex, BNF, structural tags) from Rust while retaining the performance of the upstream C++ implementation.
§Highlights
Grammar,GrammarCompiler,CompiledGrammar,TokenizerInfo— compile grammars (BNF, JSON schema, regex, structural tags) against a tokenizer.GrammarMatcher— token-by-token constrained decoding, includingGrammarMatcher::is_completed(root-rule match without stop token),GrammarMatcher::forkfor speculative / branching decoding, andGrammarMatcher::traverse_draft_treefor filling per-node token bitmasks over a speculative-decoding draft tree.BatchGrammarMatcher— batched helpers over a slice of matchers:BatchGrammarMatcher::batch_fill_next_token_bitmaskis parallel and thread-pool-backed;batch_accept_token/batch_accept_string/batch_rollbackare sequential static helpers.- Serialization —
serialize_json/deserialize_jsononGrammar,CompiledGrammar, andTokenizerInfofor persisting compilation results (version-locked to the vendored xgrammar’s serialization format). - Typed errors —
XGrammarErrvariants mirror the upstream xgrammar exception types viaXGrammarError::GetType()(XGrammarErr::InvalidJson,XGrammarErr::InvalidStructuralTag,XGrammarErr::DeserializeVersion,XGrammarErr::DeserializeFormat, …), with the coarse-grained variants kept as fallbacks for untyped C++ errors.
See each item’s documentation for usage details, including when a
BatchGrammarMatcher instance is required vs when associated functions can
be called directly.
Re-exports§
pub use tokenizers;
Modules§
Structs§
Enums§
Statics§
- EOS_
TOKEN_ ID_ KEY - GENERATION_
CONFIG_ FILE - HF_
CONFIG_ FILE - TOKENIZER_
ALLOW_ PATTERN - TOKENIZER_
CONFIG_ FILE - TOKENIZER_
FILE - TOKENIZER_
MODEL_ KEY - TOKENIZER_
VOCAB_ KEY
Functions§
- get_
bitmask_ size - Return the number of
i32elements required per token-bitmask row for a vocabulary ofvocab_sizetokens, i.e.ceil(vocab_size / 32).