Skip to content

[Grammars] Optimization: Single lookup, remove extra copies - 1.2x-1.3x speedup - #26885

Merged
aldehir merged 1 commit into
ggml-org:masterfrom
HanClinto:issue-4218-seen-move
Sep 13, 2026
Merged

aldehir merged 1 commit into
ggml-org:masterfrom
HanClinto:issue-4218-seen-move

Conversation

@HanClinto

@HanClinto HanClinto commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Overview

Tinkering with #4218 again. Even though we have llguidance available (which is generally much faster), I would still like to see improvements made to our in-house grammar engine.

This is a small change, but it includes two speed optimizations for grammar-parsing here:

1) 2 lookups => 1 lookup

Combines two consecutive lookups (initial if (seen.find()), then the internal lookup performed by seen.insert()) into a single insert-attempt/lookup so that we don't perform two lookup operations in a row -- we only need to do it once and then see if the insert succeeded.

Before:

  // find() is one presence lookup
  if (seen.find( curr_stack) != seen.end()) {
      continue;
  }
  // insert() performs a duplicate presence lookup internally (because it will not insert a duplicate value)
  seen.insert(curr_stack); // This function has a return value that is currently not being used

After:

  // It's safe to blindly call `insert()` because it will not insert if it already exists -- the bool check tells us if it was successful or not, which saves time.
  // seen.insert() returns a pair of values we can be using:
  //  If successful, a pointer to the object that was inserted
  //  A boolean indicating whether or not it was inserted
  auto [curr_stack_it, inserted] = seen.insert(std::move(curr_stack_candidate));
  if (!inserted) {
      continue;
  }
  const llama_grammar_stack & curr_stack = *curr_stack_it;

Because insert() already does the check (and returns a boolean indicating whether it already existed or not), we don't need to do this find() operation twice -- we just need to utilize the return value from insert() instead of duplicating its effort.

2) always copy, optional move => always move, optional copy

Instead of copying every intermediate stack (expensive) and then moving it (cheap) to new_stacks when it's a final output state, we switch the order so that we move every intermediate stack (cheap), and then only copy it (expensive) to new_stacks when it's a final output state.

There are a LOT of intermediate states that get generated with these stacks, and unless they become final output states, then all of those expensive intermediate copies are wasted.

So now we transfer ownership of each unique intermediate stack into seen, then copy it only if it must also be returned through new_stacks.

Before:

  // Get a pointer to the current stack
  llama_grammar_stack curr_stack = std::move(todo.back());
  if (...) { continue; }
  // Copy it when we mark it as seen
  seen.insert(curr_stack);
  ...
  // If it's a final output state
  if (...) {
    // Just move the pointer over, because we already copied the object earlier
    new_stacks.emplace_back(std::move(curr_stack));
  }

After:

  // Get a pointer to the current stack
  llama_grammar_stack curr_stack_candidate = std::move(todo.back());
  // Mark the original object as seen (without copying yet)
  seen.insert(std::move(curr_stack_candidate));
  ...
  // If it's a final output state
  if (...) {
    // Copy it now, because we know we'll use it in `new_stacks`
    new_stacks.emplace_back(std::move(curr_stack));
  }

In total:

Before: lookup -> lookup/insert + copy -> optional move to output

New: lookup/insert + move -> optional copy to output

Lookups Copy Move
Before 2 Always Sometimes
After 1 Sometimes Always

Additional information

See overall discussion of the problem here: #4218

This doesn't tackle any of the big-hitter items that we see in that thread, but it's a small improvement that provides a measurable performance benefit and is self-contained enough to be well-understood.

Results:

Ran three different grammar cases I have locally. Results showed anywhere from 1.2x-1.3x speedup:

Fixture Baseline Optimized Speedup
Overlapping synthetic 268.3 +/- 12.0 ms 226.5 +/- 12.0 ms 1.18 +/- 0.08x
PostgreSQL SELECT suite 99.6 +/- 9.1 ms 77.9 +/- 7.4 ms 1.28 +/- 0.17x
SQLite SELECT suite 49.1 +/- 3.9 ms 40.8 +/- 6.0 ms 1.20 +/- 0.20x

Each command used 10 warmups and 300 measured runs. Median speedups were 1.19x, 1.27x, and 1.21x respectively. An independent 30-run pass produced 1.18x, 1.30x, and 1.22x.

Full Hyperfine commands and test files available here.

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: YES
    • Used GH Copilot w/ GPT 5.6 Sol High to iterate through some old suggestions we've kicked around for grammar speed increases for quite some time. In the midst of testing some larger changes / improvements, happened upon this small and isolated change that gave measurable results, so decided to carve it off as its own PR before continuing with the original effort.

1) Combine two consecutive lookups (find + insert) into a single insert-attempt/lookup routine so that we don't per
form two O(log(n)) lookup operations in a row anymore -- we only need to do it once and then see if the insert succeeded.
2) Instead of copying every potential stack (expensive) and then moving it (cheap) to new_stacks when it's a final output state, we switch the order so that we move every potential stack (cheap), and then only copy it (expensive) to new stacks when it's a final output state. There are a LOT of intermediate states that get generated, and unless they become final output states, then all of these expensive intermediate copies are wasted.

Before: lookup -> lookup/insert + copy -> optional move to output
New: lookup/insert + move -> optional copy to output
@HanClinto
HanClinto requested a review from ggerganov as a code owner August 11, 2026 05:40
@HanClinto HanClinto changed the title Two speed optimizations for grammar-parsing here. [Grammars] Optimization: Single lookup, remove extra copies - 1.2x-1.3x speedup Aug 11, 2026
@HanClinto

Copy link
Copy Markdown
Contributor Author

@pwilkin I believe this touches on some code that you and @aagit worked on as part of #18604 , so if either / both of you are available to review this, that would be wonderful. Thank you!

@aldehir aldehir left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The changes look sensible, and I’m seeing a similar improvement on my end (~1.2x on a JSON grammar).

@aldehir

aldehir commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

@ggerganov what do you think about this small change?

@ggerganov ggerganov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks correct

@aldehir
aldehir merged commit 7a16a6c into ggml-org:master Sep 13, 2026
26 of 27 checks passed
quimmedes pushed a commit to quimmedes/cafe-llama.cpp that referenced this pull request Sep 16, 2026
…/copy mechanics (ggml-org#26885)

1) Combine two consecutive lookups (find + insert) into a single insert-attempt/lookup routine so that we don't per
form two O(log(n)) lookup operations in a row anymore -- we only need to do it once and then see if the insert succeeded.
2) Instead of copying every potential stack (expensive) and then moving it (cheap) to new_stacks when it's a final output state, we switch the order so that we move every potential stack (cheap), and then only copy it (expensive) to new stacks when it's a final output state. There are a LOT of intermediate states that get generated, and unless they become final output states, then all of these expensive intermediate copies are wasted.

Before: lookup -> lookup/insert + copy -> optional move to output
New: lookup/insert + move -> optional copy to output
roverdrubber added a commit to roverdrubber/llama.cpp that referenced this pull request Oct 15, 2026
The branch is far behind upstream master and the parts that a card other than
this one needs had drifted. This ports the non-backend half of that sync,
content-matched against upstream rather than replayed by hash: the parser and
JSON schema chain (ggml-org#27764, ggml-org#28736, ggml-org#28742, which adds common/parsers/,
common/json-schema.* and tests/test-json-schema.cpp and retires the three
example scripts it replaces), the chat, grammar, jinja and server fixes
(ggml-org#28302, ggml-org#28469, ggml-org#26885, ggml-org#28279, ggml-org#28511, ggml-org#28620, ggml-org#28817, ggml-org#28749), the
qwen4exp RMSNorm and multiply fusion (ggml-org#28896, hand-ported because the norm
tensors here load with a different shape), the GDN q/k l2 norm as
flash-linear-attention defines it (ggml-org#28068), the ggml_prec_set_acc API that
replaces ggml_mul_mat_set_prec and ggml_flash_attn_ext_set_prec at every call
site, and the scheduler fixes for zero-sized expert ids (ggml-org#28739) and split
inputs (ggml-org#28387).

The GPU backend half of the same sync lands in the following two commits; this
one alone does not build the CUDA or HIP backend, because their call sites move
to the new precision API there.

test-chat, test-json-schema, test-json-schema-to-grammar,
test-grammar-integration and test-grammar-parser pass.

Assisted-by: Claude Opus 5
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.

3 participants