Skip to content

Speed up strict grammar sampling on large vocabularies - #2459

Merged
leehack merged 1 commit into
mainfrom
perf/grammar-top-k-sampling
Nov 30, 2026
Merged

leehack merged 1 commit into
mainfrom
perf/grammar-top-k-sampling

Conversation

@leehack

@leehack leehack commented Nov 30, 2026 •

Copy link
Copy Markdown
Owner

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

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 Grammar-constrained sampling is slow on large-vocabulary models (Gemma 4, 262k tokens) #2444 and Track the 0.23.x Apple llama.cpp companion compatibility exception #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

  • Routing, constructor failure, ownership and fallback are implemented.
  • Performance guide, maintainer teardown documentation and chat-streaming skill updated. Public API, examples and platform support have the same contract.
  • Regression tests cover both export states, the chain shape and native lifecycle. The real-model test checks exact generated token IDs including EOG.
  • Capability registry change is N/A because no public capability is added.
  • No new user data or runtime logging.
  • 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

  • Workspace preparation with Flutter 3.47.1 / Dart 3.13.1
  • Root format, analyze, platform boundaries and diff whitespace
  • Targeted sampler and barrier suites
  • Gemma 4 greedy and seeded differential, split UTF-8, EOG, cancellation and reload
  • Root Chrome, docs build/link check, website tests and native exit teardown
  • 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

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 Warm Gemma Chat prompt prefixes after explicit Studio loads #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.

@leehack

leehack commented Nov 30, 2026

Copy link
Copy Markdown
Owner Author

Independent deep audit (uninvolved session) at head 2695841: clean, no P1/P2/P3. 196-case grids (8 grammars x 6 sampler chains x 4 prompts) on Gemma 4 E2B and Qwen3 1.7B: 0 token mismatches (shortlist accepted 786/962 times, full-vocab fallback 1,819/2,697). Published v1.1.0-2 and -1 libraries lack the export and produce identical text through the existing path. Timing ratios reproduce (greedy K=1 ~19 -> ~0.97 ms/token; seeded K=64 ~20 -> ~11 ms/token). 14 of 15 mutations fail tests; the survivor (always passing K=64) is output-neutral. Non-blocking nit: website/docs/guides/performance-tuning.md omits speculative decoding from the excluded-request list.

@leehack
leehack marked this pull request as ready for review November 30, 2026 13:57
@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Chat app preview removed for leehack/llamadart-chat-pr-2459.

@leehack
leehack merged commit 5a7b10c into main Nov 30, 2026
62 checks passed
@leehack
leehack deleted the perf/grammar-top-k-sampling branch November 30, 2026 13:59
leehack added a commit that referenced this pull request Nov 30, 2026
## Summary

- Document the speculative decoding exclusion from the strict grammar
fast path added in #2459.
- Pin the exact exception types for failed speculative initialization,
invalid combinations, and missing native exports covered by #2462.
- Fail the Gemma 4 smoke when a draft call ran and proposed zero tokens.
The report includes `NoDraftTokensProposed` and preserves the
performance counters.

## Changelog

- [core] Make the local Gemma 4 MTP smoke fail with a typed JSON report
when the drafter runs but proposes zero tokens.

## Production-readiness scope

- **User-facing scope:** Performance tuning guidance and the maintainer
smoke CLI.
- **Supported platforms/paths:** Native llama.cpp Gemma 4 GGUF with an
external or embedded drafter.
- **Unsupported or intentionally unavailable paths:** An unsupported MTP
turn still exits 1 and reports its original exception type and message.
- **Out of scope / follow-ups:** None.

## Completeness checklist

- [x] Scope implemented.
- [x] Existing unsupported-path diagnostics preserved.
- [x] Performance guide and smoke matrix documentation updated.
- [x] Added regression tests and verified that the original smoke
behavior and four exception type mutations fail.
- [x] Validation inventory N/A. Public capabilities are unchanged.
- [x] The smoke diagnostic contains a fixed message and adds no model
data or paths.
- [x] No follow-up issues required.

## PR type guidance

- **Bugfix:** A completed speculative turn could return 0 after the
drafter proposed zero tokens. Check the draft-attempt and proposed-token
counters and report the failure through the existing JSON output.

## Test Plan

- [x] `dart run tool/prepare_workspace.dart` with Flutter 3.47.1.
- [x] Repository format, analyze, platform boundaries, docs build and
link check, and full Chrome suite.
- [ ] Full local VM suite stopped after 1,338 passes with `No space left
on device` (errno 28). Focused VM suites passed independently.
- [x] Coverage-lib N/A. Library behavior is unchanged.
- [x] Verified that four subtype mutations fail the targeted exception
assertions, and that the new zero-proposal test fails before the smoke
change.

## Matrix Evidence

| Matrix row | Scope covered | Platform / model / backend | Result |
Evidence / notes |
| --- | --- | --- | --- | --- |
| static-format-analyze | Format, analyzer, import boundaries | macOS
arm64 | PASS | Flutter 3.47.1 |
| root-vm | Exception types, smoke runner, and tooling | macOS arm64 |
PASS focused | 833 passed, 3 skipped. Full local suite blocked by disk
exhaustion. Four subtype mutations and the before-fix smoke failed as
expected. |
| root-chrome | Browser-compatible suites | macOS Chrome | PASS | 5,422
passed, 1 skipped |
| docs-site | Website build and links | macOS arm64 | PASS |
`./tool/docs/build_site.sh` completed its build and link check |
| gemma4-mtp-smoke | External drafter and missing-drafter refusal |
Gemma 4 E2B Q4_K_S / Metal | PASS | External drafter proposed 8 tokens
and accepted 7, exit 0. Missing drafter returned the typed
initialization error, exit 1. A one-token turn made zero draft attempts
and exited 0. |
| high-risk-exact-head-independent-qa | Independent review | PR head and
current base | Passed | Independent Opus audit at
`b985029daf0e26a6fd47e0e7b44a2d2d59834e5c` vs `main` `aabe6fba9b`: no
blocking findings; report in pr-2465/audit.md |

## Review Notes

- Independent review status: Passed, no P1/P2/P3.
- CI status / head SHA: 7 successful, 19 skipped, 12 pending, 0 failed
at `b985029daf0e26a6fd47e0e7b44a2d2d59834e5c`.

## High-risk regression review

- **Classification:** high-risk (`regressionPolicy`).
- **Implementation task:** Follow-ups from #2459 and #2462.
- **Independent blocking QA task:** Passed at
`b985029daf0e26a6fd47e0e7b44a2d2d59834e5c`; non-blocking notes only.
- **Exact head / base at submission:**
`b985029daf0e26a6fd47e0e7b44a2d2d59834e5c` /
`aabe6fba9bf1969985f34dee4ccb2c7f9d2149e1`.
- **Production-branch deletion, bypass, or miswire proof:** The old
smoke exited 0 in the new zero-proposal fixture. Changing the missing
API, thinking-budget, bundled loadMtp, and topLogprobs paths to the
subtype each failed its exact-type assertion.
- **Affected-family real-model/artifact evidence:** Gemma 4 E2B with the
external MTP drafter on Metal.
- **Explicit unavailable-family or other N/A evidence:** The
zero-proposal result is injected in a VM fixture. The available native
Gemma 4 target uses external MTP.
- **Known PR-caused P1 regressions:** 0 known.
- **Unresolved review threads:** 0 at submission.
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