Skip to content

Speed up strict grammar sampling before top-k - #256

Merged
leehack merged 2 commits into
mainfrom
grammar-top-k-shortlist
Nov 29, 2026
Merged

leehack merged 2 commits into
mainfrom
grammar-top-k-shortlist

Conversation

@leehack

@leehack leehack commented Nov 29, 2026 •

Copy link
Copy Markdown
Owner

Summary

Gemma 4's 262,144-token vocabulary makes grammar masking the dominant sampling cost in the macOS JSON smoke. Add llama_dart_sampler_init_grammar_top_k for strict CPU grammar immediately followed by ordinary top-k with K from 1 to 64. The wrapper checks the K leading candidates on scratch storage. If one is rejected, the order is ambiguous, or the logits cannot be ranked safely, it applies grammar to the original array. Checked sampling still selects and accepts once.

Refs leehack/llamadart#2444.

Changelog

  • Add an optional native sampler that reduces strict grammar work when the top-k shortlist is already legal.

Scope and risk

High risk because this changes native sampling behavior and adds an exported C API. The constructor transfers ownership on success and exposes failures through the native barrier. An independent deep native audit at 025cfac found no P1/P2 (240,000-step synthetic and 2,160-step real-grammar differential tests with 0 mismatches; 10 of 10 mutations caught; ABI +1/-0). Dart routing, device throughput qualification, and release publication are separate follow-ups.

Validation

Local validation covers 025cfacfe142b523f9b1fb0219a0a88c7e24593f.

Check Result
Failing-first Ordinary grammar-first applied to all 8 candidates where the unique legal winner requires a singleton check.
macOS arm64 Release / AddressSanitizer 116/116 full Release CTests and 68/68 focused ASan CTests. The shipped Metal configuration also built. The default GGUF stayed byte-identical. The grammar variant covers JSON escapes, split UTF-8, and EOG.
Linux arm64 GCC 13.3 72/72 grammar, barrier, teardown, and threadpool CTests. Distinct internal helper names fix the first CI head's C-linkage compile error.
Mutation tests Six independent mutations failed: always scan, early accept, truncated retry, check one stochastic candidate, extra RNG draw, and skip tie fallback. The extra draw failed the seeded token comparison.
Python native tooling 518 tests, one skip.
Android arm64 build The Vulkan configuration and full bundle validation passed with NDK 28.2.13676358 and Ubuntu 24.04 glslc 2023.8-1build1. Cooperative matrices were enabled and integer-dot shaders were excluded.
Dynamic exports 120 required exports on macOS Mach-O and Android AArch64 ELF. The Android wrapper exports add only llama_dart_sampler_init_grammar_top_k versus b78a2def, with no removals.

@leehack

leehack commented Nov 29, 2026

Copy link
Copy Markdown
Owner Author

Independent deep native audit at 025cfacfe142b523f9b1fb0219a0a88c7e24593f

Verdict: mergeable, 0 P1/P2 regressions vs base b78a2def5b7afe468910c8008cdb1fbaed171f3b.

Item Result
Differential test (independent harness) Exact match of token, error, size, selected, sorted and each kept id/logit/probability vs the old grammar-first chain. Synthetic: 240,000 steps, K 1-64, ties, -inf/NaN/+inf, sorted and stale flags, greedy and stochastic chains, 4,710 clones, 0 mismatches. Real JSON grammar on the 262,144-token Gemma 4 vocabulary: 2,160 steps, 15 EOG completions, 51 clones, 0 mismatches. Injected extra RNG draw detected
Failing-first Forcing the full-grammar path fails grammar_top_k_test (size 1 vs 8)
Mutations 10 of 10 caught by the PR test
Ownership Caller keeps the grammar on every constructor failure; clone/free order correct; per-call stack scratch; constructor behind the barrier and exit guard; checked sample remains the only accept point
ABI +1 export (llama_dart_sampler_init_grammar_top_k), 0 removed; Android/Windows/Linux export and link jobs green in CI
Shared fixtures exit-teardown fixtures byte-identical
Performance (Gemma 4 vocab, macOS CPU) full grammar ~26 ms/token vs 0.13-0.17 ms on a fast-path hit; a miss adds ~0.1-0.3 ms
CI 27 passed, 1 skipped

Follow-up contract for the Dart routing PR: use this sampler only when DRY, top-n-sigma, mirostat and the thinking-budget composite are off and 1 <= topK <= 64; otherwise an unchecked illegal EOG could reach GGML_ABORT. Add tests that excluded configurations do not take this path. Measure hit rate during device qualification.

Auditor: independent Claude Opus 5.5 (high effort) review agent, 2026-11-29.

@leehack
leehack marked this pull request as ready for review November 29, 2026 23:52
@leehack
leehack merged commit cb83ec7 into main Nov 29, 2026
29 checks passed
leehack added a commit to leehack/llamadart that referenced this pull request Nov 30, 2026
## Summary

- Route eligible strict native llama.cpp grammars through the
already-pinned shortlist wrapper immediately before the same ordinary
top-k sampler. Eligibility starts at 131,072 vocabulary tokens and K
1–64. The wrapper keeps the normal full-vocabulary grammar pass for
ambiguous or rejected shortlists.
- Keep the original grammar chain when the loaded runtime lacks the
export. The published macOS arm64 v1.1.0-2 and v1.1.0-3 bundles report
identical ABI versions, so after normal runtime admission the export is
the sole capability signal.
- Transfer grammar ownership on success. Surface native construction
errors as `LlamaInferenceException` and free the grammar and partial
chain on failure.

Refs #2444. [Native sampler
contract](leehack/llamadart-native#256)

## Changelog

- [core] Reduce strict grammar sampling cost on large native GGUF
vocabularies while preserving greedy and seeded output.

## Production-readiness scope

- **User-facing scope** Automatically accelerates eligible strict
grammar requests without a new setting.
- **Supported paths** Native llama.cpp CPU sampling chain on admitted
runtimes exporting the wrapper. Existing model offload and public
generation options keep their existing semantics.
- **Fallback paths** The original route covers absent export, small
vocabularies, out-of-range K, lazy grammar, thinking-budget composites,
DRY, top-n-sigma, Mirostat, speculative decoding and requested logprobs.
Existing input validation still applies.
- **Follow-ups** Android XL throughput and Apple companion qualification
for the patch decision remain under #2444 and #2448. This draft includes
macOS host evidence.

If a future native release introduces a second shortlist contract, add
an optional sampler-specific ABI version export in the owner repository.
Preserve detection of the existing contract by its constructor export,
use full-vocabulary sampling for unknown versions, and test both exports
across the supported loaders.

## Completeness checklist

- [x] Routing, constructor failure, ownership and fallback are
implemented.
- [x] Performance guide, maintainer teardown documentation and
chat-streaming skill updated. Public API, examples and platform support
have the same contract.
- [x] Regression tests cover both export states, the chain shape and
native lifecycle. The real-model test checks exact generated token IDs
including EOG.
- [x] Capability registry change is N/A because no public capability is
added.
- [x] No new user data or runtime logging.
- [x] Device and patch qualification follow-ups are linked above.

## PR type guidance

Backend performance fix. Repeated grammar masking over the full
vocabulary dominated native sampling on Gemma 4. The native sampler
certifies the immediate top-k shortlist before the existing selector or
applies the original full mask.

## Test Plan

- [x] Workspace preparation with Flutter 3.47.1 / Dart 3.13.1
- [x] Root format, analyze, platform boundaries and diff whitespace
- [x] Targeted sampler and barrier suites
- [x] Gemma 4 greedy and seeded differential, split UTF-8, EOG,
cancellation and reload
- [x] Root Chrome, docs build/link check, website tests and native exit
teardown
- [x] Local root VM and `coverage-lib` with 70% threshold

## Matrix Evidence

| Matrix row | Scope covered | Platform / model / backend | Result |
Evidence / notes |
| --- | --- | --- | --- | --- |
| `static-format-analyze` | Format, analyzer, platform imports | Flutter
3.47.1 / Dart 3.13.1 | PASS | Root formatter, analyzer and platform
boundaries |
| `root-vm` / `coverage-lib` | Root VM tests and coverage | macOS arm64
| PASS | 16,720 passed and 136 skipped. Library line coverage 93.88%
(38,184/40,674). All three PR CI Linux VM shards passed. |
| `root-chrome` | Browser-compatible root tests | Chrome | PASS | 5,421
passed and one skipped locally. All three PR CI shards passed. |
| `docs-site` | Static build, links and website tests | Jaspr | PASS |
No broken internal links and 32 website tests passed locally. Docs Build
Check passed in CI. |
| `native-exit-teardown` | Host process exit smoke | macOS arm64 / Llama
3.2 1B Instruct Q4_K_M / Metal | PASS | Seven scenarios passed in three
runs each. Four projector, decision-head and TTS scenarios skipped
without their fixtures. Gemma exercises request cancellation and reload
separately. |
| `structured-output-adversarial` | Strict grammar equivalence and
fallback | Gemma 4 E2B IT Q4_K_S, macOS M4 Max CPU, threads 2+2,
v1.1.0-3 | PASS | Greedy K=1 and seeded K=64 matched every token ID
through EOG. Also checks JSON escaping and actual split UTF-8. |
| `high-risk-exact-head-independent-qa` | Independent blocking review |
Exact head and base | PASS | Deep audit (Opus, fresh session) clean at
exact head: 0/0/0 P1/P2/P3 |

Targeted sampler and barrier suites passed 33 tests. The eligible
routing test failed against baseline. Additional mutations changing the
forwarded K, admitting a lazy request or leaking the grammar on
rejection each failed their relevant test.

### Gemma 4 CPU comparison

Four paired timed runs per mode after one warmup per arm, alternating
full-first and shortlist-first. Both arms use v1.1.0-3, with the export
hidden at lookup for the full scan. The metric is the service's sampling
and token-to-piece time divided by actual sampler calls, including EOG.
The model has a 262,144-token vocabulary and SHA-256
`0a2fac16f388b4839f075dedb681357aec3e73a96bd66b413e462b6853550c99`. Seed
7, 1,024 context, prefix reuse off, three-field JSON schema. The
committed-head rerun also passed exact token parity and lifecycle
checks.

| Sampling | Tokens including EOG | Median full scan | Median shortlist
|
| --- | ---: | ---: | ---: |
| Greedy, K=1 | 63 | 17.376 ms/token | 0.931 ms/token |
| Seeded, K=64, temp 0.8 | 77 | 18.182 ms/token | 10.266 ms/token |

Reproduce with
`LLAMADART_GEMMA4_GRAMMAR_MODEL=/path/to/gemma-4-E2B-it-Q4_K_S.gguf
TMPDIR="$(mktemp -d)" dart test -p vm --run-skipped
test/e2e/backends/llama_cpp_grammar_top_k_e2e_test.dart --reporter
expanded`.

## Review Notes

- **Independent review** Clean at
`2695841c0d3388cb51adcf8cc26b5979c6d58be7`: 196-case equivalence grids
on Gemma 4 E2B and Qwen3 1.7B with zero token mismatches, published
v1.1.0-2/-1 libs fall back correctly, ownership and exit-teardown paths
reviewed, 14/15 mutations fail tests.
- **CI and head** 31 successful, 12 skipped, zero failures at
`2695841c0d3388cb51adcf8cc26b5979c6d58be7`. PR CI intentionally omits
the coverage job.
[Checks](https://github.com/leehack/llamadart/pull/2459/checks)

## High-risk regression review

- **Classification** High-risk (`backendRuntime`).
- **Implementation task** Route eligible sampler chains through the
optional guarded native constructor.
- **Independent blocking QA task** Deep audit by an uninvolved session:
clean (pr-2459/audit.md in the maintainer evidence store).
- **Exact head / current base**
`2695841c0d3388cb51adcf8cc26b5979c6d58be7` /
`ae3789e4a5ede46ca9839a777c5e7e7bb0dd540e`. The head was tested from
merge base `38d07ea31657f1454e3d866e6620c05fc7e2f2c1`. Main advanced by
Studio PR #2458. A merge simulation against current main had no
conflicts.
- **Production-branch deletion, bypass, or miswire proof** The routing
test is red before wiring. Wrong K, lazy eligibility and error cleanup
mutations each fail the targeted test. A loader seam removes the export
in both the synthetic chain test and Gemma differential.
- **Affected-family evidence** Gemma 4 E2B IT Q4_K_S with exact token-ID
parity, including EOG, and measured phase costs above.
- **Other evidence** No Android XL or Apple companion device
qualification in this draft. The local CPU results cover one Gemma 4
model and configuration.
- **Known PR-caused P1 regressions** 0 (implementation and independent
audit).
- **Unresolved review threads** 0 at opening.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant