Skip to main content

Crate glrmask

Crate glrmask 

Source
Expand description

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

cargo add glrmask

GLRMask needs Rust 1.89 or later. A minor release may raise the minimum Rust version; a patch release won’t.

§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.

§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.

// Token ID -> exact bytes from tokenizer
let vocab = Vocab::new(token_bytes)?;

let weather = Grammar::from_json_schema(r#"
    {
        "type": "object",
        "properties": {
            "city": {"type": "string"}
        },
        "required": ["city"],
        "additionalProperties": false
    }
"#)?.compile(&vocab)?;

let parent = Grammar::from_glrm(r#"
    extern grammar ARGS
    start call
    nt call = "<weather>" ARGS "</weather>"
"#)?;
let mut call = Module::new(&parent);
call.bind("ARGS", &weather)?;
let constraint = call.compile(&vocab)?;

§Learn more

Full guide · API reference

Structs§

CompileOptions
Options for compiling a grammar or module.
Constraint
ConstraintState
Error
Expr
A grammar expression.
Extern
A named placeholder in a grammar.
ExternIntoIter
An owning iterator over externs.
ExternIter
A borrowed iterator over externs.
Externs
A read-only collection of extern names and their Extern values.
Grammar
MaskStrategy
Controls how the constraint is compiled.
Module
A partially compiled grammar.
TokenSet
A set of token IDs.
Vocab
Each token ID and its bytes.

Enums§

ErrorKind
ExternKind
What an extern can be bound to.

Type Aliases§

Result
A result with a GLRMask Error.