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 Schema, Lark and GLRM.

Installation

python -m pip install glrmask

Usage

GLRMask has four core types:

In the quickstart, supply the tokenizer's exact token bytes and the model's EOS ID. The model produces logits; the sampling routine must apply the packed mask and permit EOS only when the state is accepting.

Quickstart

from glrmask import Grammar, Vocab
import numpy as np

# Replace with your tokenizer's token bytes
token_bytes = {i: bytes([i]) for i in range(256)}
EOS = 256
rng = np.random.default_rng(0)
def model(output):
    return rng.standard_normal(EOS + 1)  # 256 byte tokens + EOS
def sample(logits, mask, accepting):
    allowed = np.zeros(len(logits), dtype=bool)
    bits = np.unpackbits(mask.astype('<u4').view(np.uint8), bitorder='little')
    allowed[:EOS] = bits[:EOS]
    allowed[EOS] = accepting
    if not allowed.any():
        raise RuntimeError('no allowed token and cannot stop')
    return int(np.argmax(np.where(allowed, logits, -np.inf)))
grammar = Grammar.from_json_schema(
    {
        "type": "object",
        "properties": {
            "color": {
                "enum": ["red", "green", "blue"]
            }
        },
        "required": ["color"],
        "additionalProperties": False,
    }
)

# Token ID -> exact bytes from tokenizer
vocab = Vocab(token_bytes)
state = grammar.compile(vocab).start()

output = []
while True:
    logits = model(output)
    mask = state.mask()
    token = sample(logits, mask, state.is_accepting())
    if token == EOS:
        break
    if not state.commit_token(token):
        raise RuntimeError("Rejected token")
    output.append(token)
assert state.is_accepting()
print(bytes(output).decode())

Composing grammars

In a typical serving setup, a grammar constraint is one main grammar with smaller grammars nested inside it, some of which, like tool schemas, change from request to request. GLRMask is built to make this kind of composition cheap. Like modules in a program, grammars can be written and compiled as separate parts and combined later.

A server compiles its main grammar once as a Module with named externs. Each tool's schema is compiled on its own, in parallel or on another machine. For each request, GLRMask composes the main grammar with the compiled schemas by filling in the externs.

Resolving the interactions between them requires some extra boundary work. However, this work is usually small compared with compiling the grammars themselves, so composition remains cheap even when the grammars are large.

from glrmask import Grammar, Module, Vocab
# Replace with your tokenizer's token bytes
token_bytes = {i: bytes([i]) for i in range(256)}
# Token ID -> exact bytes from tokenizer
vocab = Vocab(token_bytes)

weather = Grammar.from_json_schema(
    {
        "type": "object",
        "properties": {
            "city": {"type": "string"}
        },
        "required": ["city"],
        "additionalProperties": False,
    }
).compile(vocab)

parent = Grammar.from_glrm('''
    extern grammar ARGS
    start call
    nt call = "<weather>" ARGS "</weather>"
''')
call = Module(parent)
call.bind("ARGS", weather)
constraint = call.compile(vocab)

Learn more

Full guide ยท API reference

class Vocab:

Each token ID and its bytes. Hugging Face tokenizers don't expose token bytes (#2719); converting them is outside GLRMask's scope.

Vocab(id_to_bytes: Mapping[int, bytes], /)
class Grammar:
@staticmethod
def from_glrm(source: str, /) -> Grammar:

Parses GLRM source.

@staticmethod
def from_lark(source: str, /) -> Grammar:

Parses Lark source.

@staticmethod
def from_json_schema(schema: str | bool | dict[str, typing.Any], /) -> Grammar:

Parses a JSON Schema, given as JSON text or a dict.

@staticmethod
def from_expr(expr: Expr, /) -> Grammar:

Builds a grammar from an Expr.

externs: Externs

All extern declarations.

def compile( self, vocab: Vocab, *, mask_strategy: MaskStrategy = MaskStrategy.AUTO) -> Constraint:

Compiles the grammar into a constraint.

def copy(self) -> Grammar:

Shares the immutable grammar data.

class Constraint:
def start(self) -> ConstraintState:

Starts a new sequence.

mask_bit_len: int

The mask's length in bits (max token ID plus one).

def save(self) -> bytes:

Serializes the compiled constraint for later loading.

@staticmethod
def load(data: bytes, vocab: Vocab, /) -> Constraint:

May fail if saved by a different GLRMask version. Fails if vocab differs from the one it was compiled with.

class ConstraintState:
def mask(self) -> NDArray[numpy.uint32]:

Packed uint32 words: token i is bit i % 32 of word i // 32.

def fill_mask(self, bitmask: NDArray[numpy.uint32], /) -> None:

Like mask(), but writes the words into bitmask. May release the GIL.

mask_bit_len: int

The mask's length in bits (max token ID plus one).

def commit_token(self, token_id: int, /) -> bool:

Advances the state by the token. If it isn't allowed, returns False and terminates the state.

def commit_bytes(self, data: bytes, /) -> bool:

Advances the state by the bytes. If they aren't allowed, returns False and terminates the state.

def forced_bytes(self) -> bytes:

The bytes that must come next.

def is_accepting(self) -> bool:

Whether the output so far could end here.

def is_terminated(self) -> bool:

Whether nothing more can be committed.

def copy(self) -> ConstraintState:

Creates an independent state at the same position.

class Expr:

A grammar expression.

@staticmethod
def literal(value: str | bytes, /) -> Expr:

Matches value exactly.

@staticmethod
def sequence( *parts: Grammar | Module | Constraint | Expr | TokenSet) -> Expr:

Matches parts in order.

@staticmethod
def choice( *parts: Grammar | Module | Constraint | Expr | TokenSet) -> Expr:

Matches any one of parts.

class TokenSet:

A set of token IDs.

TokenSet(ids: Iterable[int | range], /)

Accepts individual IDs and ranges.

class Extern:

A named placeholder in a grammar.

name: str
kind: Literal['token', 'grammar']
class Externs(collections.abc.Mapping[str, 'Extern']):

A read-only mapping of extern names to Extern.

unbound: Externs

Only externs that still need bindings.

class MaskStrategy:

Controls how the constraint is compiled.

AUTO: ClassVar[MaskStrategy] = MaskStrategy.AUTO

The default; currently FAST_MASKS.

FAST_COMPILE: ClassVar[MaskStrategy] = MaskStrategy.FAST_COMPILE

Faster compilation, slower masks.

FAST_MASKS: ClassVar[MaskStrategy] = MaskStrategy.FAST_MASKS

Faster masks, slower compilation.

class GLRMaskError(builtins.Exception):

An error raised by GLRMask.

kind: Literal['syntax', 'invalid_input', 'compilation', 'resource_limit', 'strategy_unsupported', 'serialization', 'vocab_mismatch', 'buffer_too_small', 'internal']

The category of this error.

class Module:

A partially compiled grammar.

Module(source: Grammar, /)

Starts with the grammar and its unbound externs.

externs: Externs

All extern declarations, including bound externs.

def bind( self, name: str, value: Grammar | Module | Constraint | Expr | TokenSet, /) -> None:

Binds an extern by name.

def precompile( self, vocab: Vocab, *, mask_strategy: MaskStrategy = MaskStrategy.AUTO) -> None:

Compiles what it can now, even with externs unbound. Further compilation must use the same vocab.

def compile( self, vocab: Vocab, *, mask_strategy: MaskStrategy = MaskStrategy.AUTO) -> Constraint:

Finishes compiling the module into a constraint.

def save(self) -> bytes:

Serializes the module, including any precompiled work.

@staticmethod
def load(data: bytes, /) -> Module:

May fail if saved by a different GLRMask version.

def copy(self) -> Module:

Creates a snapshot with independent bindings.