Grammar Sampling
Definition
Grammar Sampling is a technique of controlled generation where the probability distribution of the model at each step is restricted to a set of tokens allowed by the current state of a formal grammar (e.g., GBNF, regular expression, or JSON schema).
How It Works
- A grammar is defined as a finite automaton or pushdown automaton.
- The set of permissible continuations is calculated before a token is chosen.
- The logits of invalid tokens are set to −∞.
- Sampling is applied to the adjusted distribution.
# Pseudocode
state = grammar.initial()
for step in range(max_tokens):
allowed = grammar.allowed_tokens(state)
logits = mask_logits(model_logits, allowed)
token = sample(logits, temperature)
state = grammar.advance(state, token)
Applications
- Guaranteed syntactically correct JSON, SQL, XML.
- Code generation in a specified language.
- Argument formation for Function Calling without parsing errors.