Skip to content

chat : implement token aware parsing - #29307

Merged
aldehir merged 62 commits into
ggml-org:masterfrom
aldehir:token-aware-parsing
Nov 22, 2026
Merged

aldehir merged 62 commits into
ggml-org:masterfrom
aldehir:token-aware-parsing

Conversation

@aldehir

@aldehir aldehir commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Overview

Currently, chat parsing operates purely on text. This makes it impossible to distinguish regular text from special tokens.

For example, Qwen3+ has dedicated tokens for <think> and </think>. It can, however, also generate these as separate pieces that are not intended to signal reasoning boundaries, e.g. </ think >. Operating purely on text loses this information and leads to incorrect parsing of model output.

This PR implements token-aware parsing, leveraging the changes from #29876.

Chat parsers can use the p.token() parser to match a token:

auto parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
    // Matches the <think> / </think> special tokens, not the literal text
    auto think_start = p.token("<think>");
    auto think_end   = p.token("</think>");

    // A model that *writes* "</think>" as plain text (e.g. explaining the
    // format) no longer ends the reasoning block early, only the real token does
    auto reasoning = p.optional(think_start + p.reasoning(p.until(think_end)) + think_end);

    return reasoning + p.content(p.rest()) + p.end();
});

Or multiple tokens:

p.token({"<|end|>", "<|call|>"}) // any one of these tokens
p.token({"<|end|>", "<|call|>"}, /* negate = */ true)  // any single token *except* these

If a piece isn't registered as a special token, p.token() falls back to p.literal(), so parsers still work with templates/vocabs that don't define it.

The p.until()/p.through() parsers can accept a parser as a delimiter that defines both tokens and literals:

// Content runs until the model starts a tool call.
// Some models emit the <tool_call> special token, others may skip it and go straight to "<function=", which is plain text.
auto tool_start = p.token("<tool_call>") | p.literal("<function=");
auto content    = p.content(p.until(tool_start));

// Delimiters can also mix the two in a sequence, e.g. an optional newline (text) followed by the </think> token
auto think_end  = (p.literal("\n") + p.token("</think>")) | p.token("</think>");
auto reasoning  = p.token("<think>") + p.reasoning(p.until(think_end)) + think_end;

Additional Information

Extended grammar to support token sets

To parse heterogeneous grammars with both literals and tokens, the grammar sampler needs support for token grammar sets implemented as:

# match a single token by id
root ::= <[1000]>

# a set: token 1000, or any token with id 1005 through 1010 inclusive
root ::= <[1000,1005-1010]>

# negated set: any token EXCEPT those ids
root ::= !<[1000,1005-1010]>

Additionally, any tokens referenced in the grammar are marked as opaque and cannot be matched against with character rules.

Removed p.ac()

The p.ac() parser seemed a little unintuitive, so I instead merged it with the until() parser and a included boolean. The p.through(p.until(END), END) can be used in place, where the parser will consume END to match the GBNF grammar rules.

Additionally, delimiters can be defined as parser rules with limitations. This is to support a mixture of literal and token delimiters.

Replacing trigger patterns with a scanning grammar

Trigger words/patterns use std::regex to determine when to start constraining. This has some downsides:

  • The entire generation is checked on every token, which gets worse as the generation grows.
  • std::regex is known to stack overflow or hit an internal recursion limit on large strings.
  • It cannot differentiate between tokens.

Instead of using std::regex, we can leverage the grammar sampler itself.

p.trigger_rule(name, start, rest) will produce a "scanning" grammar that scans for every trigger start. Since the grammar sampler operates a token at a time, it is better than std::regex and can differentiate between strings and tokens.

Effectively, rules come out to be:

root ::= trigger
trigger ::= | <tool_call> tool-call | !<tool_call> trigger
tool-call ::= <function= ...

Multiple trigger rules will produce a grammar that finds the first trigger and then constrains the branch associated with that trigger (e.g. the rest parameter).

Model Master per-token cost at 64k (std::regex) PR (grammar)
gpt-oss-20b 4,250 µs ~10 µs
Muse Glimmer 2,840 µs ~10 µs
Gemma 4 949 µs 1.2 µs
Qwen3.8 1,014 µs 1.1 µs

Decode speed for gpt-oss-20b on an RTX 3090 over a 16k-token generation with tools offered, master vs. PR.

Window Master tok/s PR tok/s
0–4k 141.1 147.2 +4.3%
4–8k 144.3 144.7 +0.3%
8–12k 137.7 146.1 +6.1%
12–16k 128.3 142.4 +11.0%

Other changes

  • Added token aware parsing to the following parsers:

    • GPT-OSS
    • Qwen 3.5+
    • Gemma 4
    • Muse Glimmer
  • Added infra in test-chat to support testing by crafting fake special tokens.

There is another side to this problem, which is input sanitization to prevent the model from regurgitating special tokens if included in the system/user prompt. That is out of scope for this PR.

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: Yes, a mixture of Fable 5.1 and Opus 5.5. Design was made by me and reviewed at every step. Examples in PR description are AI-generated.

@aldehir
aldehir force-pushed the token-aware-parsing branch from fdf7580 to 27c2bb4 Compare September 23, 2026 10:17
@aldehir
aldehir force-pushed the token-aware-parsing branch from 27c2bb4 to 8f404f3 Compare September 28, 2026 05:40
@github-actions github-actions Bot added documentation Improvements or additions to documentation testing Everything test related labels Sep 28, 2026
@aldehir
aldehir force-pushed the token-aware-parsing branch 2 times, most recently from f9df835 to 2f91099 Compare September 28, 2026 07:33
@aldehir
aldehir force-pushed the token-aware-parsing branch from 2f91099 to f3d2453 Compare November 2, 2026 05:41
@aldehir
aldehir force-pushed the token-aware-parsing branch from f3d2453 to f762d79 Compare November 9, 2026 01:55
@aldehir

aldehir commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

/bot review

@ggml-gh-bot

ggml-gh-bot Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

❌ Code review failed.

Error: failed to fetch diff (504) from https://github.com/ggml-org/llama.cpp/pull/29307.diff

@aldehir

aldehir commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

/bot review

@ggml-gh-bot

ggml-gh-bot Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

❌ Code review failed.

Error: pi agent produced an empty review

@aldehir

aldehir commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor Author

I swear it never works for me.

I think the bot failing illustrates why this is necessary :)

But what about llama_grammar_accept_str? It accepts text codepoint by codepoint. If the grammar's char rules receive text that was previously part of... hmm, accept_str is used for the lazy grammar trigger buffer. Text there is fine — but opaque tokens: if the trigger buffer contains a special token's text (e.g. "

@aldehir
aldehir marked this pull request as ready for review November 9, 2026 07:54
@aldehir
aldehir requested review from a team, ggerganov and pwilkin as code owners November 9, 2026 07:54
@ngxson

ngxson commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

@aldehir lol it seems like to try it the worst time possible: GH was down (504 error) and for the later I'm not sure, but sometimes (rare) the inference provider stuck and cannot doesn't return any tokens at all

let's wait until GH is green again and retry https://www.githubstatus.com/

@aldehir

aldehir commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

It's looking green now, let's give it another shot.

/bot review

@ggml-gh-bot

ggml-gh-bot Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

❌ Code review failed.

Error: pi agent timed out after 1800000ms

@aldehir

aldehir commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

/bot review

@ggml-gh-bot

ggml-gh-bot Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Automated code review

Follow-up review of the delta since 18b48fa: upstream merge 2e2656c (declared conflict in common/parsers/gemma4.cpp, auto-merge in common/parsers/muse-spark.cpp) plus three commits: ce69a23 (LOG_WRN + dead-code removal), a2c8846 (harmony-xml missing-close restore), f7e28e5 (muse-glimmer eot removal + test updates).

Fixes verified as correct

(point 1) The LOG_WRN in common_chat_input_tokenize (common/chat.cpp:1805) resolves the previous silent-fallback finding. log.h is included, and the message says enough to diagnose a token-id-less parse.

(point 2) Removing the dead ac.is_terminal(0) block in gbnf_ac_grammar (common/peg-parser.cpp:1837 area) is safe: both callers (gbnf_excluding_grammar, gbnf_including_grammar) get tries whose delimiters cannot match the empty string (insert_delimiter/trigger_rule throw first), and prefix is still used by state_name, so nothing dangles. This closes the previous dead-code finding, including its stale comment.

(point 3) The harmony-xml restore (common/parsers/harmony-xml.cpp:104-106) is mechanically sound and matches the old master semantics: the gbnf node parses through its child (arg_string | missing_close, lenient), while the grammar emits the strict rfl-arg-string rule text; collect_reachable traverses the gbnf child, so the rule is emitted and referenced. missing_close is byte-for-byte master's lenient alternative ("\n" + peek of optional "\n" + next_open). The new comment is concise and states the non-obvious parser/grammar split. This resolves the previously blocking finding.

(point 4) The gemma4 merge resolution is correct as far as I can verify: the token parsers were re-applied on top of upstream's #31915 refactor, and the old gemma4 workaround namespace the PR branch carried was already removed upstream, so nothing was silently dropped. The post-merge grammar_lazy = false + build_grammar(builder, !(has_response_format || REQUIRED)) combination is coherent: the second argument only selects the grammar shape (scanning root vs strict root) while the grammar is active from the first token, and the prefill path in common_sampler_init feeds the generation prompt into non-lazy grammars.

Still open / newly raised

(point 5) The restored harmony-xml tolerance is untested, and so is the whole parser. No template under models/templates/ contains rfl:parameter, and nothing in tests/ constructs a harmony-xml case, so neither the well-formed close nor the missing-close branch is exercised anywhere. The previous review explicitly asked for a test here; the fix landed without one. A peg_tester case with (a) a string parameter running into "\n<|end|>" with no closing tag and (b) a well-formed call would pin the behavior that was just broken and restored.

(point 6) muse-glimmer <|eot|> removal: defensible, but underdocumented and divergent from its sibling.

  • The header comment (common/parsers/muse-glimmer.cpp:5-7) still documents "<|eot|> (end of turn)" and "final answer: to=user, terminated by <|eot|>" while the parser now has zero knowledge of that token. If the rationale is that <|eot|> is the vocab EOS and never reaches the parser (callers strip EOS), say that in one line where the comment is; right now it reads as an oversight.
  • Residual behavior change: if eot text does reach the parser (ignore_eos, a caller feeding a full turn, the realtime path), it is now absorbed into content as literal "<|eot|>" instead of terminating the message. The sibling muse-spark.cpp:77 still tolerates a trailing "<|eot|>", so the two parsers now give different results for identical input. Either align them or note why glimmer differs.
  • Grammar side: the constrained grammar no longer names eot at all. That only works if eot is the EOS token (accepted once the grammar stack empties); if it is not, a constrained generation could never emit <|eot|> and would run to n_predict. Worth one sentence of confirmation in the PR description.

Will slow the review (carried forward, unchanged)

(point 7) Unused surface still has no production caller: negated token(pieces, true), through()'s optional flag and multi-branch form, and common_peg_tokens::tokens. It is documented in docs/development/parsing.md now, but reviewers will still ask whether it stays.

(point 8) The specials table is still copied per request: common/chat.cpp:1522 (params.specials = tmpls->specials), then again into the builder and arena on every parser build. A const ref or shared ownership held by the templates would avoid it.

(point 9) Duplicate trigger starts still throw std::runtime_error (common/peg-parser.cpp, "must not share a start"), which a client can trigger via two same-named tools in qwen3-coder auto mode; std::invalid_argument with the offending names would map to a 400.

Nits (carried forward, unchanged)

(point 10) common/parsers/gpt-oss.cpp:75: [ ]+ still requires a leading space, so ...<|constrain|>json with no space does not parse; no test covers it.

(point 11) ❌/✅ remain in tests/test-grammar-integration.cpp (AGENTS.md wants ASCII only).

(point 12) Hard-wrapped mid-sentence comments remain, e.g. common/parsers/qwen3-coder.cpp:157-160, common/peg-parser.h on token()/through().

(point 13) The test-only hooks in the public common/chat.h (common_chat_templates_set_specials, session_params::tokenize) are still there; if they stay, the PR description should say why they live in the public header.

No whitespace errors or stray non-ASCII in the delta; the three fix commits are each small, single-purpose, and match their stated intent.

This review was generated automatically by pi coding agent using zai-org/GLM-5.3. It may contain mistakes. Maintainers make the final call.

@aldehir

aldehir commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Alright, I've addressed all that I believe need addressing. Here are justifications for the others (excluding nits):

(point 5) The restored harmony-xml tolerance is untested...

The original author did not include tests for this parser.

(point 6) muse-glimmer <|eot|> removal: defensible, but underdocumented and divergent from its sibling.

It's fine. We don't typically include the EOG token in our parsers/grammars, they're implicit. The documentation properly documents the model behavior.

(point 7) Unused surface still has no production caller: negated token(pieces, true), through()'s optional flag and multi-branch form, and common_peg_tokens::tokens. It is documented in docs/development/parsing.md now, but reviewers will still ask whether it stays.

We will leverage these unused functions in future parser changes.

(point 8) The specials table is still copied per request: common/chat.cpp:1522 (params.specials = tmpls->specials), then again into the builder and arena on every parser build. A const ref or shared ownership held by the templates would avoid it.

Models typically have < 20 special tokens, with Nemotron being the exception (1000 special placeholder tokens). If it becomes an issue, I can follow up.

(point 9) Duplicate trigger starts still throw std::runtime_error (common/peg-parser.cpp, "must not share a start"), which a client can trigger via two same-named tools in qwen3-coder auto mode; std::invalid_argument with the offending names would map to a 400.

Will follow up with a PR to handle duplicate tools.

That said, this is a substantial change and should probably land after v1.

thefallentree added a commit to thefallentree/llama.cpp-gp100 that referenced this pull request Nov 14, 2026
…nd in the parsed output

Input: the server tokenized the rendered chat prompt as one string with
parse_special, so a file the agent read and sent back as a tool result
turned "</think>", "<tool_call>", "<|im_end|>" into the special tokens.
llama_tokenize_with_literals() takes byte ranges in which no special token
is matched, not even a user-defined one (Qwen's <think> and <tool_call> are
USER_DEFINED and match even with parse_special = false). The text runs
between real special tokens are still tokenized as a whole, so the tokens
across the part borders are those of the whole text. The jinja input marking
(ggml-org#30389) gives the ranges; tokenize_chat_prompt() follows the shape of the
open upstream PR ggml-org#32033 (--chat-input-special / --no-chat-input-special),
also for the count-tokens endpoints and mtmd (mtmd_tokenize_from_parts joins
adjacent text parts and passes the literal ranges). Fork default: disabled,
client text is text; a request may set "chat_input_special".

Output: with the vocab's special token table, a PEG literal or until
delimiter that names a special token matches only that token id in the
generated tokens (ggml-org#29876), so "</think>" or "<tool_call>" written as
ordinary tokens in reasoning or content no longer cuts it. A small stand-in
for the token-aware parsing of the open upstream PR ggml-org#29307. Text without
tokens parses as before.

Refs: mkyt docs/decisions.md P6-50, P6-51; ggml-org#28249, ggml-org#32033, ggml-org#29307, ggml-org#29876, ggml-org#30389, ggml-org#28250.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ng-v4

# Conflicts:
#	common/parsers/gemma4.cpp
@aldehir

aldehir commented Nov 16, 2026

Copy link
Copy Markdown
Contributor Author

@ggerganov when you have a chance, can you take a look at the grammar changes. Thanks!

thefallentree added a commit to thefallentree/llama.cpp-gp100 that referenced this pull request Nov 17, 2026
…nd in the parsed output

Input: the server tokenized the rendered chat prompt as one string with
parse_special, so a file the agent read and sent back as a tool result
turned "</think>", "<tool_call>", "<|im_end|>" into the special tokens.
llama_tokenize_with_literals() takes byte ranges in which no special token
is matched, not even a user-defined one (Qwen's <think> and <tool_call> are
USER_DEFINED and match even with parse_special = false). The text runs
between real special tokens are still tokenized as a whole, so the tokens
across the part borders are those of the whole text. The jinja input marking
(ggml-org#30389) gives the ranges; tokenize_chat_prompt() follows the shape of the
open upstream PR ggml-org#32033 (--chat-input-special / --no-chat-input-special),
also for the count-tokens endpoints and mtmd (mtmd_tokenize_from_parts joins
adjacent text parts and passes the literal ranges). Fork default: disabled,
client text is text; a request may set "chat_input_special".

Output: with the vocab's special token table, a PEG literal or until
delimiter that names a special token matches only that token id in the
generated tokens (ggml-org#29876), so "</think>" or "<tool_call>" written as
ordinary tokens in reasoning or content no longer cuts it. A small stand-in
for the token-aware parsing of the open upstream PR ggml-org#29307. Text without
tokens parses as before.

Refs: mkyt docs/decisions.md P6-50, P6-51; ggml-org#28249, ggml-org#32033, ggml-org#29307, ggml-org#29876, ggml-org#30389, ggml-org#28250.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
thefallentree added a commit to thefallentree/llama.cpp-gp100 that referenced this pull request Nov 19, 2026
…nd in the parsed output

Input: the server tokenized the rendered chat prompt as one string with
parse_special, so a file the agent read and sent back as a tool result
turned "</think>", "<tool_call>", "<|im_end|>" into the special tokens.
llama_tokenize_with_literals() takes byte ranges in which no special token
is matched, not even a user-defined one (Qwen's <think> and <tool_call> are
USER_DEFINED and match even with parse_special = false). The text runs
between real special tokens are still tokenized as a whole, so the tokens
across the part borders are those of the whole text. The jinja input marking
(ggml-org#30389) gives the ranges; tokenize_chat_prompt() follows the shape of the
open upstream PR ggml-org#32033 (--chat-input-special / --no-chat-input-special),
also for the count-tokens endpoints and mtmd (mtmd_tokenize_from_parts joins
adjacent text parts and passes the literal ranges). Fork default: disabled,
client text is text; a request may set "chat_input_special".

Output: with the vocab's special token table, a PEG literal or until
delimiter that names a special token matches only that token id in the
generated tokens (ggml-org#29876), so "</think>" or "<tool_call>" written as
ordinary tokens in reasoning or content no longer cuts it. A small stand-in
for the token-aware parsing of the open upstream PR ggml-org#29307. Text without
tokens parses as before.

Refs: mkyt docs/decisions.md P6-50, P6-51; ggml-org#28249, ggml-org#32033, ggml-org#29307, ggml-org#29876, ggml-org#30389, ggml-org#28250.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
thefallentree added a commit to thefallentree/llama.cpp-gp100 that referenced this pull request Nov 19, 2026
…nd in the parsed output

Input: the server tokenized the rendered chat prompt as one string with
parse_special, so a file the agent read and sent back as a tool result
turned "</think>", "<tool_call>", "<|im_end|>" into the special tokens.
llama_tokenize_with_literals() takes byte ranges in which no special token
is matched, not even a user-defined one (Qwen's <think> and <tool_call> are
USER_DEFINED and match even with parse_special = false). The text runs
between real special tokens are still tokenized as a whole, so the tokens
across the part borders are those of the whole text. The jinja input marking
(ggml-org#30389) gives the ranges; tokenize_chat_prompt() follows the shape of the
open upstream PR ggml-org#32033 (--chat-input-special / --no-chat-input-special),
also for the count-tokens endpoints and mtmd (mtmd_tokenize_from_parts joins
adjacent text parts and passes the literal ranges). Fork default: disabled,
client text is text; a request may set "chat_input_special".

Output: with the vocab's special token table, a PEG literal or until
delimiter that names a special token matches only that token id in the
generated tokens (ggml-org#29876), so "</think>" or "<tool_call>" written as
ordinary tokens in reasoning or content no longer cuts it. A small stand-in
for the token-aware parsing of the open upstream PR ggml-org#29307. Text without
tokens parses as before.

Refs: mkyt docs/decisions.md P6-50, P6-51; ggml-org#28249, ggml-org#32033, ggml-org#29307, ggml-org#29876, ggml-org#30389, ggml-org#28250.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
thefallentree added a commit to thefallentree/llama.cpp-gp100 that referenced this pull request Nov 20, 2026
…nd in the parsed output

Input: the server tokenized the rendered chat prompt as one string with
parse_special, so a file the agent read and sent back as a tool result
turned "</think>", "<tool_call>", "<|im_end|>" into the special tokens.
llama_tokenize_with_literals() takes byte ranges in which no special token
is matched, not even a user-defined one (Qwen's <think> and <tool_call> are
USER_DEFINED and match even with parse_special = false). The text runs
between real special tokens are still tokenized as a whole, so the tokens
across the part borders are those of the whole text. The jinja input marking
(ggml-org#30389) gives the ranges; tokenize_chat_prompt() follows the shape of the
open upstream PR ggml-org#32033 (--chat-input-special / --no-chat-input-special),
also for the count-tokens endpoints and mtmd (mtmd_tokenize_from_parts joins
adjacent text parts and passes the literal ranges). Fork default: disabled,
client text is text; a request may set "chat_input_special".

Output: with the vocab's special token table, a PEG literal or until
delimiter that names a special token matches only that token id in the
generated tokens (ggml-org#29876), so "</think>" or "<tool_call>" written as
ordinary tokens in reasoning or content no longer cuts it. A small stand-in
for the token-aware parsing of the open upstream PR ggml-org#29307. Text without
tokens parses as before.

Refs: mkyt docs/decisions.md P6-50, P6-51; ggml-org#28249, ggml-org#32033, ggml-org#29307, ggml-org#29876, ggml-org#30389, ggml-org#28250.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@aldehir

aldehir commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

If there are no objections, I think I'm going to merge this in soon so I can leverage it to work on #32180 (not strictly necessary, just easier to manage w.r.t merges).

@ggml-org ggml-org deleted a comment from samyelzoghby01-lang Nov 21, 2026
@samyelzoghby01-lang

This comment was marked as spam.

@samyelzoghby01-lang

This comment was marked as spam.

@samyelzoghby01-lang

This comment was marked as spam.

@pwilkin pwilkin 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.

By all means let's merge it.

pwilkin

This comment was marked as duplicate.

@aldehir
aldehir merged commit 1014775 into ggml-org:master Nov 22, 2026
16 checks passed
Annieren pushed a commit to Annieren/llama.cpp-upstream that referenced this pull request Nov 23, 2026
Kidplayer666 pushed a commit to Kidplayer666/llama.cpp that referenced this pull request Nov 23, 2026
Mr-J-369 pushed a commit to Mr-J-369/llama.cpp-Android that referenced this pull request Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation server testing Everything test related

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants