How Regex-Constrained Token Generation Works with Outlines and Guidance
Constrained generation libraries enforce regular expressions directly during autoregressive decoding rather than validating and retrying after the model finishes generating. Because you have direct access to raw model logits on open-weight LLMs (via Hugging Face transformers, llama.cpp, vLLM, or mlx-lm), both Outlines and Guidance mask invalid vocabulary tokens at every decoding step:
- Finite-state automaton compilation: The regex is compiled into a finite-state machine (FSM) aligned with the model’s exact tokenizer vocabulary so each FSM state maps to the subset of token IDs that can validly continue the match.
- Step-by-step logit masking (
-inf): Before sampling each token, logits for disallowed token IDs are set to $-\infty$, guaranteeing zero probability mass on outputs that violate the regex while preserving normal temperature/top-p sampling across valid tokens. - Outlines vs. Guidance workflow: Outlines compiles the regex into a reusable generator (
outlines.generate.regexoroutlines.types.regex) with fast $O(1)$ per-step token lookups, whereas Guidance lets you compose regex constraints (gen(regex=...)orguidance.regex(...)) inline with Python control flow, chat role blocks (system(),user(),assistant()), and captured variables.
Steps to Apply Regex Constraints to Open-Weight LLMs
- Load your open-weight model and matching tokenizer: Initialize the model through an open-weight backend (
transformers,llama.cpp,vLLM, orsglang) so the constraint engine can inspect the exact token vocabulary and apply logit processors. - Write an anchored, bounded regular expression: Define the exact pattern (for example,
r"ORD-\d{6}"orr"\d{4}-\d{2}-\d{2}") and avoid unbounded.*patterns that prevent the automaton from reaching a clean accepting/EOS state. - Compile or attach the regex constraint: In Outlines, pass the regex pattern to
outlines.generate.regex(model, pattern)(or passoutlines.types.regex(pattern)tomodel(prompt, ...)); in Guidance, appendgen(name="...", regex=pattern)inside anassistant()context block. - Run generation and reuse compiled constraints: Cache compiled generators or grammars across requests so FSM compilation happens once at startup rather than on every inference call.
Python Example: Regex-Constrained Generation in Outlines and Guidance
# --- Option 1: Outlines with Hugging Face Transformers ---
import outlines
from transformers import AutoModelForCausalLM, AutoTokenizer
MODEL_ID = "Qwen/Qwen2.5-3B-Instruct"
hf_model = AutoModelForCausalLM.from_pretrained(MODEL_ID, device_map="auto")
hf_tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
model = outlines.from_transformers(hf_model, hf_tokenizer)
# Constrain output strictly to a canonical tracking ID format
tracking_id_pattern = r"TRK-[A-Z]{3}-\d{6}"
tracking_regex = outlines.types.regex(tracking_id_pattern)
prompt = (
"Extract the tracking code from this message and output only the code:\n"
"Customer note: My package label shows TRK-KHI-482910 arrived damaged."
)
tracking_id = model(prompt, tracking_regex, max_new_tokens=20)
print("Outlines output:", tracking_id) # Guaranteed match: TRK-KHI-482910
# --- Option 2: Guidance with Transformers / llama.cpp ---
from guidance import assistant, gen, models, system, user
lm = models.Transformers(MODEL_ID, device_map="auto")
with system():
lm += "Extract the requested field accurately."
with user():
lm += "Invoice date is March 14, 2026. Return ISO date (YYYY-MM-DD)."
with assistant():
lm += "Date: " + gen(
name="iso_date",
regex=r"\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])",
max_tokens=15,
)
print("Guidance output:", lm["iso_date"]) # Guaranteed match: 2026-03-14
Helpful Tips for Production Regex Decoding
- Ensure the regex allows a valid termination path: Every valid path through your regex should eventually reach an accepting state so the engine can unmask the model’s
EOStoken cleanly instead of hittingmax_tokensmid-pattern. - Watch whitespace and leading-space tokenization: Many BPE tokenizers encode
" 123"and"123"as distinct token IDs; if your prompt ends without a trailing space or newline, account for optional leading whitespace or place the delimiter in the prompt prefix ("Date: "). - Use dedicated serving engines for high-throughput production: In multi-user deployments, run the same Outlines or
llguidance/ XGrammar backends natively inside vLLM (guided_regex) or SGLang (regex) so logit masking executes in compiled kernels alongside continuous batching.
You must log in or register to comment.
