glrmask
GLRMask is a grammar-constrained decoding library for high-throughput LLM serving. It is optimized for fast mask computation with extremely low tail latency, even for complex grammars.
GLRMask supports general context-free grammars, including ambiguous ones. It accepts JSON schemas, GLRM, Lark, and EBNF.
GLRMask has three core types:
Grammar: the language you want to generate.Constraint: a grammar compiled against a specific vocabulary.ConstraintState: the mutable state for a single generated sequence.
Compile a Grammar into a Constraint, then call constraint.start(). In the
decoding loop, compute the next-token mask, sample a token the mask allows, and
commit that token to the state.
Quick start
import glrmask
vocab = glrmask.Vocab.from_id_to_bytes({
0: b"hello",
1: b" ",
2: b"world",
})
grammar = glrmask.Grammar.from_ebnf(
'start ::= "hello" " " "world"'
)
constraint = grammar.compile(vocab)
state = constraint.start()
assert state.mask()[0] & 1
state.commit_token(0)
state.commit_token(1)
state.commit_token(2)
assert state.is_accepting()
Vocab records the model token IDs and their bytes. Python masks are packed
32-bit words; bit token_id % 32 in word token_id // 32 indicates whether
that token is allowed.
Use Grammar.compile_unlinked and UnlinkedConstraint when a compiled parent
will be reused with different compiled children or exact-token bindings.
The class and method reference below documents these operations.
Optional boundary-query metadata, built before compile or link returns.
Compiled grammar constraint. Immutable, thread-safe.
Mutable per-sequence parse state.
One exact model token, retaining its complete vocabulary identity.
A nonempty set of exact model tokens, retaining its vocabulary identity.
Immutable grammar description with source-grammar or exact-token bindings.
bind returns another description. compile produces a complete runnable Constraint; compile_unlinked intentionally preserves unresolved slots.
Return a new description with one declared slot bound. No compilation occurs.
Compile a closed, immediately runnable constraint for this vocabulary.
end_tokens are reserved generation controls, allowed only at acceptance. Their policy is not inherited when the result is later embedded as a child.
Preferred compilation/runtime trade-off; accepted-language semantics are unchanged.
Immutable vocabulary-specific compiled constraint in pre-link form.
Bind a compiled Constraint child or exact-token value, returning a new value.
Build the byte vocabulary used by a llama-cpp-python Llama model.
EOG, control, unused, and empty-piece tokens are omitted from the byte
vocabulary. EOG IDs remain available through llama_cpp_end_token_ids
for the decoder's stopping policy.