Inferensys

Glossary

GBNF Grammar

GBNF (GGML BNF) is a formal grammar notation used by frameworks like llama.cpp to define syntactical rules for constrained decoding, guaranteeing that a language model's output strictly adheres to a specified format.
Governance lead reviewing model governance framework on laptop, policy documents visible, executive office setup.
FORMAL GRAMMAR NOTATION

What is GBNF Grammar?

GBNF (GGML BNF) is a formal grammar notation used to define syntactical rules for constrained decoding, ensuring language model output strictly matches a specified format.

GBNF Grammar is a notation for defining Context-Free Grammars (CFGs) that constrain the token generation process of a language model. It acts as a strict set of production rules, forcing the model's output to conform to a predefined syntactical structure, such as valid JSON or a custom data format, by dynamically masking invalid tokens during decoding.

Primarily used in high-performance inference engines like llama.cpp, GBNF defines rules using a syntax of terminal strings and non-terminal symbols. During grammar-constrained generation, the engine compiles these rules into a Finite State Machine (FSM) that tracks the valid next tokens, guaranteeing the final output is syntactically correct and parseable without post-processing.

GRAMMAR-CONSTRAINED DECODING

Key Features of GBNF Grammar

GBNF (GGML BNF) is a formal grammar notation used by llama.cpp and related frameworks to define syntactical rules for constrained decoding. It ensures language model output strictly matches a specified format, such as JSON or a custom DSL.

01

Formal Syntax Definition

GBNF uses a Context-Free Grammar (CFG) notation to define all valid output strings. Rules are expressed as recursive production rules, providing a strict syntactic contract for the model.

  • Root Rule: Every grammar starts with a root rule defining the top-level structure.
  • Terminals: Literal strings and character ranges (e.g., [a-z]) define valid tokens.
  • Non-Terminals: Named rules (e.g., json-object) allow recursive composition.
  • Alternation: The pipe | operator defines logical OR branches for valid sequences.
02

Token-Level Enforcement

During decoding, the GBNF grammar is compiled into a Finite State Machine (FSM). At each step, the FSM calculates the set of permissible next tokens and applies a token mask.

  • Logit Bias: The probabilities of all invalid tokens are set to negative infinity.
  • Guaranteed Validity: The model is physically prevented from sampling an out-of-schema token.
  • Zero Overhead: Masking happens natively in the C++ inference engine for minimal latency impact.
03

JSON Schema Compliance

GBNF is the primary mechanism for forcing JSON output in local inference engines. A grammar can precisely define the structure, required keys, and data types of a JSON object.

  • Type Safety: Enforce string, number, boolean, and null types.
  • Required Fields: Define mandatory keys within an object.
  • Array Constraints: Specify the element type and cardinality of arrays.
  • Example: A grammar can enforce the exact { "name": string, "age": integer } schema.
04

Domain-Specific Languages

Beyond JSON, GBNF enables the creation of custom Domain-Specific Languages (DSLs) for specialized agent outputs. This allows for more token-efficient and parseable formats.

  • ReAct Format: Enforce the Thought: ... Action: ... structure for agentic loops.
  • Code Generation: Constrain output to a specific programming language syntax.
  • Tool Calling: Define a precise grammar for function names and arguments.
  • Efficiency: Custom DSLs often require fewer tokens than equivalent JSON.
05

Integration with llama.cpp

GBNF is a core feature of the llama.cpp inference engine, making structured output accessible on consumer hardware. The grammar is passed as a string parameter to the API.

  • Server API: Use the grammar field in the /completion endpoint.
  • Offline Usage: Pass the grammar string directly to the llama_eval() function.
  • Grammar Caching: Compiled FSMs are cached to avoid re-parsing on subsequent calls.
  • Compatibility: Works with all GGUF-quantized models supported by the runtime.
06

Comparison to JSON Schema

While JSON Schema defines the what (the data contract), GBNF defines the how (the token-level path to get there). GBNF is a lower-level, more deterministic mechanism.

  • JSON Schema: Validates output after generation. Relies on model instruction-following.
  • GBNF: Physically constrains generation during decoding. Guarantees syntactic validity.
  • Combined Approach: Use a library to compile a JSON Schema into a GBNF grammar for the strongest guarantee.
  • Trade-off: GBNF is rigid; it cannot gracefully recover from a semantic error mid-stream.
STRUCTURED OUTPUT TECHNIQUE COMPARISON

GBNF Grammar vs. Other Structuring Methods

A feature-level comparison of GBNF Grammar against JSON Schema, Function Calling, and Token Masking for constraining language model output to valid, parseable formats.

FeatureGBNF GrammarJSON SchemaFunction CallingToken Masking

Constraint Mechanism

Context-Free Grammar rules

JSON structure definition

API tool definition

Per-token logit modification

Guarantees Syntactic Validity

Supports Non-JSON Formats

Requires Post-Processing

Schema Complexity Support

Arbitrary CFG rules

Nested objects, arrays, enums

Flat parameter lists

Simple token sequences

Runtime Overhead

Low (FSM-based)

Medium (validation step)

Medium (API round-trip)

Low (logit bias)

Framework Dependency

llama.cpp, llama-cpp-python

OpenAI, LangChain, Instructor

OpenAI, Anthropic, Cohere

Custom inference code

Whitespace and Formatting Control

Exact character-level

Schema-agnostic

Model-dependent

Token-level only

GBNF GRAMMAR FAQ

Frequently Asked Questions

Clear, technical answers to the most common questions about GBNF grammar, its role in constrained decoding, and how it compares to other structured output techniques.

GBNF (GGML BNF) is a formal grammar notation used by the llama.cpp inference framework to define syntactical rules for constrained decoding. It works by compiling a set of production rules into a finite state machine (FSM) that tracks the valid state of an output sequence. At each generation step, the FSM determines the set of permissible next tokens, and a token mask is applied to the model's logits, setting the probability of all invalid tokens to zero. This physically prevents the language model from generating text that violates the defined grammar, guaranteeing that the final output is syntactically valid according to the specified rules. GBNF is an extension of the standard Backus-Naur Form (BNF), adapted to handle the token-level constraints of large language models.

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.