Performance study · llama.cpp
Grammar Tax
A study I designed and measured: what grammar-constrained (JSON-schema) sampling costs in llama.cpp on a CPU, and how much three small patches remove.
The cost hides inside the sampler, not the model. I built a record/replay benchmark to isolate it, and proved the patched masks bit-identical before trusting any speed-up.
- RoleA study I designed and measured
- Year2026
- StackC++ · Python · llama.cpp · perf · callgrind

01Problem
At every generation step, llama.cpp’s grammar sampler checks the whole vocabulary — 151,936 tokens for Qwen2.5 — against the grammar. On a CPU that mask cost a median of ~27 ms per token, about as much as running the 0.5B model itself.
02Approach
- A record/replay benchmark that isolates mask computation from model inference: 206 grammars (8 built-in + 198 JSONSchemaBench schemas), 23,448 replayed tokens.
- Profiling with callgrind and perf found a large share of mask instructions in per-token heap allocation.
- Three small patches: one decode buffer per call, an ASCII match table, and reuse of per-stack reject lists.
- Correctness first: masks compared bit for bit on every recorded step, plus differential random-walk tests including partial-UTF-8 edge cases.
- Statistics: five interleaved runs, paired per grammar, bootstrap 95% confidence intervals — and every rejected idea documented with numbers.
03Architecture
04Stack
- C++
- Python
- llama.cpp
- perf
- callgrind
05What I owned
- The question, the benchmark design, the acceptance bar (bit-identical masks) and the statistics.
AI assistance: The code was written with an AI assistant (Claude); the repo discloses this, and says it must be disclosed in any upstream submission.
06Verified results
- 1.47× faster grammar maskwith bit-identical output, across 206 of 206 grammarsabout +1.5% end-to-end on llama.cpp’s default path, +24% where the mask runs every step · not merged upstreamSource: grammar-tax/README.md · Results · read 2026-11-21
- −32.7%median per-token mask cost (27.3 ms → 18.5 ms); p99 −17.9%Source: grammar-tax/README.md · Results · read 2026-11-21
- Bit-identicalmasks on every one of 44,650 trace steps (2 vocabularies) plus 17,167 random-walk stepsSource: grammar-tax/README.md · Results · read 2026-11-21
What these numbers don’t show
- The 1.47× is for mask computation. llama.cpp’s default sampler builds the full mask on only ~5% of steps, so end-to-end throughput there moves by about 2%.
- Nothing has been submitted or merged upstream.
- Measured on a 4-vCPU Xeon VM; numbers depend on the machine.
07More
