Overview

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.

Benchmarks

Time between masks

Hover or tap to inspect. When focused, use left and right arrows to inspect the tail; Escape dismisses values.

Time between masks

· µs
Statistic GLRMask GLRMaskdynamic llguidance XGrammar
mean 3.2 30.9 25.3 35.9
2.9 9.0 11.4 9.1
5.1 87.5 40.6 38.2
10.1 212.0 267.8 534.0
17.0 657.4 1,070.7 2,736.8
25.2 1,825.9 3,627.2 7,901.3
43.8 4,731.5 8,276.3 12,660.3

Time to first mask

· ms
Statistic GLRMask GLRMaskdynamic llguidance XGrammar
mean 37.3 5.8 1.3 84.5
p50 16.8 4.1 0.9 44.3
p90 75.0 9.5 2.1 203.2
p99 306.4 43.4 13.3 834.3
max 1,350.1 138.0 48.6 4,066.2
Measurement details

The displayed engines use one AWS c7i.16xlarge run (Intel Xeon Platinum 8488C, Linux), the Llama 3.1 8B Instruct vocabulary and the system allocator. TTFM compares 7,948 commonly built schemas from the 9,558-schema JSONSchemaBench corpus (Geng et al.). TBM compares 10,668 complete, correct valid trajectories accepted across the complete campaign: 1,570,228 token positions per engine. Failed, incorrect and incomplete trajectories are excluded. The original campaign cohort is fixed for every displayed arm. One wall-clock pass; sequential cases, CPU affinity 0–31 and a 32-thread compiler budget.

GLRMask 3d65c7a; llguidance 1.9.1; XGrammar 0.2.8 (97787376). These are frozen-source measurements, preceding the later strict schema-policy revision a306051. No verified later-policy eligibility map accompanies this run; no inferred filtering is applied. One XGrammar schema hit the memory limit; six llguidance runtime-error examples remain unknown. Fixture agreement does not establish full-language equivalence. Exact provenance and exclusions.

Full-run outcomes

ModeBuild OKBuild errorsRuntime-error examples
GLRMask854610120
llguidance833212266
XGrammar94191380

GLRMask’s dynamic mode trades some mask-generation speed for lower cold-start latency. It is heavily based on llguidance.

How it works

Getting started

Installation

python -m pip install glrmask==1.0.0rc1

Usage

GLRMask has four core types:

  • Grammar: a grammar, written as source text or built from an expression.
  • Constraint: a compiled grammar, ready to use.
  • ConstraintState: the state of one generated sequence.
  • Module: a partially compiled grammar (see below).

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.

Python quickstart

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)

Rust quickstart

let grammar = Grammar::from_json_schema(r#"
    {
        "type": "object",
        "properties": {
            "color": {
                "enum": ["red", "green", "blue"]
            }
        },
        "required": ["color"],
        "additionalProperties": false
    }
"#)?;

// Token ID -> exact bytes from tokenizer
let vocab = Vocab::new(token_bytes)?;
let constraint = grammar.compile(&vocab)?;
let mut state = constraint.start();

let mut output = Vec::new();
loop {
    let logits = model(&output);
    let mask = state.mask();
    let token = sample(&logits, &mask, state.is_accepting());
    if token == EOS { break; }
    assert!(state.commit_token(token));
    output.push(token);
}

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.