Skip to content

npu: the chat route refuses a container whose tokenizer cannot represent ChatML (measured: 200 with the wrong prompt -> 400 naming the model's specials) - #987

Merged
bong-water-water-bong merged 7 commits into
mainfrom
1bit/npu-963-chatml-guard
Nov 4, 2026
Merged

bong-water-water-bong merged 7 commits into
mainfrom
1bit/npu-963-chatml-guard

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

The chat route refuses a container whose tokenizer has no ChatML anchors, instead of prompting it with text it never produces

app/forward_serve.cpp:167 renders npu::chatml() for every container — deliberate when #832 introduced it (the
route parses and masks every answer as AnswerFamily::qwen3), and wrong for any family whose template is not ChatML:
the <|im_start|> marker is not in that vocabulary, so it becomes ordinary pieces and the model is prompted with text
its own template never produces, while the route answers 200 with plausible output.

This is the smallest fix (#963 option 1). A container whose tokenizer cannot represent the prompt gets a 400 naming
the model's own specials
on /v1/chat/completions, and is pointed at /v1/completions with token ids (#938), which
is the correct way to serve such a container: the caller renders the model's own template and sends the ids. Option 2
from the issue — pack the model's chat_template and render a Jinja subset — is the real fix and a container-format
decision, so it is not in this PR. Option 3 (docs only) would leave the trap armed.

Closes #963.

What changed

file change
app/npu_chatml.h chatml_supported(const Tokenizer&): both `<
app/forward_serve.cpp the condition is evaluated once at load (chatml_ok + the 400's message, built from the container's own bos/eos ids decoded through its tokenizer), so a request pays nothing; the chat branch throws that message, which the existing handler turns into a 400. Also one stderr line at load and one line of the file's header comment
tests/npu_chatml_test.cpp, CMakeLists.txt 5 rows on two real tokenizer fixtures (tests/data/tokenizer_chatml.json new, tests/data/tokenizer_linear.json as the negative); the test now links onebit_npu and takes both fixture paths — it previously linked only nlohmann and had nothing to read a tokenizer with
docs/npu.md the prompt summary line, plus a paragraph under the request-field table: what is refused, why ids are the way out, and that the check is a necessary condition

Refusing per request rather than at load is deliberate: /v1/completions and /health must stay up on such a
container. /v1/systemone renders the d3 pack's own template (app/npu_systemone.h) and is untouched.

Measured

Reproduced before changing the route, device-free (no ticket, the container's own tokenizer.json through
npu::chatml() — one user message, hi):

| container | rendered prompt | <|im_start|> alone | chatml_supported() |
|---|---:|---|---|
| Zyphra/ZR1-1.5B (DeepSeek specials) | 23 tokens | 6 pieces | no |
| Qwen3-0.6B (ChatML) | 9 tokens | 1 token, id 151644 | yes |

ctest -R 'npu_chatml|npu_sampling|tokenizer_linear' → 3/3 pass, npu_chatml: ok (the direct binary run, not only
the ctest line); tools/copyright.py --check rc 0.

Served rows (strixhalo, host GEMM so the array is never opened, npu-hold -l npufeat ticket, two containers and one
binary — A = Qwen3-0.6B as shipped, B = the same 0.6B weights/plan with Zyphra/ZR1-1.5B's tokenizer.json,
tokenizer_config.json and its bos/eos ids):

row before after
A1 chat, Qwen3-0.6B (ChatML — must not move) 200, prompt_tokens 9 200, prompt_tokens 9 — identical
A2 /v1/completions, ids [151644,77091,198] 200 200
B1 chat, same 0.6B weights/plan + ZR1 tokenizer 200, `content: "< ", prompt_tokens` 23 — the wrong prompt, answered plausibly
B2 the same with stream: true 200 SSE, `delta.content: "< "`
B3 /v1/completions, ids [100,200,300], same container 200 200 — the escape hatch is untouched
B4 stderr at load (nothing) 1bit forward-serve: chat route disabled: … once

Two binaries (before = this worktree with only app/forward_serve.cpp + app/npu_chatml.h reverted to eda7542e,
strings … | grep -c 'chat route disabled' = 0; after = 1), two npu-hold -l npufeat tickets (queued 522 s and
252 s, held 16 s and 22 s, both released cleanly, both commands exited 0 well inside -t 12), amdxdna ERROR
lines 0 in both windows.

The cross-check worth noting: B1's prompt_tokens: 23 from the old binary is exactly the 23 the device-free tokenizer
measurement gives for the same request — the served number and the tokenizer number are the same fact, from two
directions.
Not claimed: no device row (host GEMM), no tok/s number, and a container that carries both anchors but uses another
template is still not caught — only packing chat_template closes that.

Note for another lane, not changed here

app/unified.cpp:112 has its own chatml() and uses it for the llama.cpp lane's chat route
(unified.cpp:164), so the same trap exists there for a non-ChatML GGUF. Not this lane's file and not part of #963's
measurement, so it is reported rather than touched.

…ent ChatML (#963)

app/forward_serve.cpp renders npu::chatml() for every container (#832), so a family whose
tokenizer has no <|im_start|>/<|im_end|> is prompted with text its own template never produces
and answers 200 anyway: on Zyphra/ZR1-1.5B's tokenizer the same request is 23 prompt tokens
against Qwen3's 9, and the marker alone is 6 pieces.

chatml_supported() (app/npu_chatml.h) reads the container's own tokenizer once at load; a
container without both anchors now gets a 400 on /v1/chat/completions naming its real bos/eos
specials and pointing at /v1/completions with token ids (#938), which is how such a container is
served correctly. /v1/completions and /v1/systemone are untouched, so the refusal is per request
rather than a load failure.

Measured, same requests, before and after (host GEMM, npu-hold, amdxdna errors 0): B chat
200 content "<|" -> 400; B streamed 200 SSE -> 400; B completions ids 200 -> 200; Qwen3 chat
200 prompt_tokens 9 -> unchanged. 5 new ctest rows on two real tokenizer fixtures.

Necessary condition, not a proof the template is ChatML -- packing chat_template is the real fix
and a container-format decision (option 2 of #963), left to the owner.
@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit e5fa410)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

963 - Partially compliant

Compliant requirements:

  • The chat route now refuses containers whose tokenizer cannot represent ChatML with a 400 error
  • The refusal includes the model's own specials and points to /v1/completions with token ids
  • The check is performed once at load time
  • Documentation has been updated to reflect the new behavior

Non-compliant requirements:

  • None

Requires further human verification:

  • None
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

ChatML Support Check

The chat route now checks if the container's tokenizer supports ChatML anchors (\u200c and \u200d) at load time and refuses requests with a 400 error if not. This prevents silent incorrect behavior where a non-ChatML tokenizer would render the prompt incorrectly, causing the model to be prompted with text it never produces. The check is performed once at load time, which is efficient.

if (!npu::chatml_supported(*e.tok)) {
    e.chatml_ok = false;
    std::string specials;
    const std::pair<const char*, int> named[] = {{"bos", e.bos_id}, {"eos", e.eos}};
    for (const auto& [label, id] : named) {
        const std::string text = id >= 0 ? e.tok->decode(id) : std::string();
        if (text.empty()) continue;
        specials += std::string(specials.empty() ? "" : ", ") + label + " " + text + " (" +
                    std::to_string(id) + ")";
    }
    e.chatml_refusal =
        "this container's tokenizer has no <|im_start|> / <|im_end|>, so the ChatML prompt the chat route "
        "renders would be tokenized into pieces the model never sees (#963); send /v1/completions with "
        "prompt as token ids (#938) and render the model's own template" +
        (specials.empty() ? std::string() : " (model specials: " + specials + ")");
    std::fprintf(stderr, "1bit forward-serve: chat route disabled: %s\n", e.chatml_refusal.c_str());
}
ChatML Support Function

A new function chatml_supported() is added to check if the tokenizer has the required ChatML anchors (\u200c and \u200d) as special tokens. This function is used to determine if a container can safely use the ChatML prompt format. The check is necessary but not a proof that the template is ChatML, as noted in the comments.

inline bool chatml_supported(const Tokenizer& tok) {
    return tok.token_id("<|im_start|>") >= 0 && tok.token_id("<|im_end|>") >= 0;
}

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

READY, with one stale number to fix in a comment.

Independent repro of the disposition (device-free; tokenizers 0.23.3 on the real tokenizer.json files, my own rendering of the same one-message ChatML prompt):

Zyphra/ZR1-1.5B (~/models/zyphra-orig/ZR1-1.5B@6108a26d/tokenizer.json): <|im_start|> -> 7 pieces,
    vocab has <|im_start|>: False, <|im_end|>: False        => chatml_supported() = no
Qwen3-0.6B     (~/models/npu/Qwen3-0.6B/tokenizer.json):                <|im_start|> -> 1 token, id 151644,
    vocab has both: True                                    => chatml_supported() = yes

So the predicate lands on the right side for both containers, and the marker really is spelled out as ordinary pieces on the Zyphra vocabulary. Reading the route: the decision is taken once at load, the chat branch throws the message and the existing handler turns it into a 400, /v1/completions (ids) and /health are untouched, and the header/docs say it is a necessary condition rather than a proof the template is ChatML — that is the right scope for option 1.

The number. app/forward_serve.cpp's new comment says "zyphra/ZR1-1.5B: 33 tokens rendered against 15 under the model's template", but the measured row in the PR body says 23 tokens (and my own render of that prompt gives 24, 7 of them for the marker). One measurement, two numbers: keep the measured pair and drop the 33/15, or re-measure and correct whichever is stale.

I did not run ctest here (no engine build of mine), so the 3/3 line stands as yours.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

VERDICT: READY

Built and ran the PR's own test at this head, then ran it against the real container tokenizers on this box — which
is the part that matters, because the predicate is the whole fix.

Build + test at 3cca1fa03:

cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=gcc-16 -DCMAKE_CXX_COMPILER=g++-16
cmake --build build --target npu_chatml_test          -> links
./build/npu_chatml_test tests/data/tokenizer_chatml.json tests/data/tokenizer_linear.json
                                                      -> npu_chatml: ok   (rc 0)
ctest -R npu_chatml                                   -> 1/1 Passed

The same binary against the containers themselves, not the fixtures:

npu_chatml_test ~/models/npu/Qwen3-0.6B/tokenizer.json  ~/models/npu/ZR1-1.5B-npu-q4km/tokenizer.json
  -> npu_chatml: ok        (Qwen3 served, ZR1 refused)

and with the two arguments swapped, as a control that the test can fail:

  -> FAIL a tokenizer with <|im_start|>/<|im_end|> is served the chat route
     FAIL a tokenizer without them is refused, not prompted anyway (#963)
     FAIL with the anchor the marker is one token, which is what ChatML requires
     FAIL the rendered prompt opens with that anchor token
     FAIL without it there is no such id: the refusal's condition is the anchor, not the prompt's length

So chatml_supported() says "served" for the Qwen3 container and "refused" for the ZR1-1.5B container — the exact pair
the issue was filed about — and the test is direction-sensitive rather than passing on any input.

The route wiring (read, not device-run): the refusal is thrown inside the same try that already produces the 400
for a malformed body (app/forward_serve.cpp:173), so the client gets the message naming the model's own specials
rather than a 500; /v1/completions is untouched, which is the documented way out for such a container; and
chatml_ok/chatml_refusal are decided once at load from the tokenizer, so a request pays nothing for it.

Notes, neither a gate:

  1. tests/data/tokenizer_chatml.json is new but tests/data/tokenizer_linear.json was already on main (same blob), so
    the CMake argv[2] does not depend on a file this PR forgot to add — I checked git ls-tree at both heads rather
    than assuming.
  2. chatml_supported() is a necessary condition, and the code comment says so ("a container may carry both anchors and
    still use a different template") — the real fix is packing the model's chat_template, which the docs also say. Worth
    keeping that sentence intact if the doc section is ever tightened.

Not run by me: the live 200 -> 400 transition on /v1/chat/completions, which needs the NPU and the owner's device; the
lane's measured row stands for that, and the predicate plus the throw site are what I could verify without it.

@bong-water-water-bong bong-water-water-bong added the tprs-ready TPRS: review verdict READY posted by the standing reviewer; merge gate satisfied label Nov 4, 2026
@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit ca5ae20

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

VERDICT: READY at ca5ae200a — merge-only update, own content byte-identical.

Checked with a hash of the PR's own diff at both heads rather than by eyeballing the file list: git diff <merge-base> <head> | sha256sum is the same at 3cca1fa03 and at ca5ae200a, so nothing of this PR's moved. The branch is MERGEABLE/BEHIND; the whole delta is main advancing (#1007, #1002, and the console-TUI/prefix-cache work that landed with them).

Evidence from the review at 3cca1fa03 stands: the chat route's ChatML refusal — npu_chatml_test run against the real containers: Qwen3 served, ZR1-1.5B refused, swapped-argument control fails five checks.

CI at this head: red/pending: build — pr_agent failures on engine PRs are superseded-run cancellations ("Canceling since a higher priority waiting request exists"), not findings.

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 10946e5

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit e5fa410

@bong-water-water-bong
bong-water-water-bong merged commit 0662681 into main Nov 4, 2026
9 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the 1bit/npu-963-chatml-guard branch November 4, 2026 19:05
bong-water-water-bong added a commit that referenced this pull request Nov 5, 2026
…ine #963 option 2) (#1115)

`app/forward_serve.cpp:176` renders ChatML for every container, and #987 refuses the chat route for a
container whose tokenizer has no ChatML anchors — so a non-ChatML container cannot be chatted with at
all today. #963's option 2 (render the container's own template) was left as an owner decision because
it looked like a container-format change plus a new Jinja dependency. Measured on this box, it is
neither:

- the containers already carry their template (`chat_template.jinja` in an imported OGA pack,
  `tokenizer_config.json`'s `chat_template` in a FastFlowLM pack), and #1095 already reads it to log and
  pin its sha256;
- the pinned llama.cpp fork already vendors a C++ Jinja engine (`common/jinja/`, ~6.2 kLOC, the one
  `llama-server` renders with), so the route can reuse it instead of growing a second implementation;
- the templates we ship use a small part of Jinja: `for`/`if`/`set`+`namespace`/filters/attribute
  access/string methods/macros in 24/24, 23/24, 18/24 and 10/24 templates; `{% generation %}` and
  content-gated branches in **none**. Sizes 209 B - 16.7 KB.

The note records that, the four shipped NPU catalogue rows with what changes for each (all four are
ChatML-anchored today, so nothing is blocked — this is about serving each container the template it
declares, including FastFlowLM's `user_system_prompt` branch, and about the next non-ChatML container),
the security rules the renderer must carry, and the three decisions it asks for: reuse `common/jinja`,
container-template -> ChatML-only-with-anchors -> 400 fallback order, and a template that fails to render
being a 400 naming its sha rather than a silent fall back.

Co-authored-by: bong-water-water-bong <[email protected]>
bong-water-water-bong added a commit that referenced this pull request Nov 6, 2026
…te, not ChatML for every container (#1298)

`app/forward_serve.cpp` rendered `npu::chatml()` for every NPU container; #987 made that honest
(a container whose tokenizer has no `<|im_start|>`/`<|im_end|>` anchors gets a 400 instead of a
prompt its vocabulary cannot read), but a container that *declares* its template was still served an
approximation of it.  This is #963 option 2, the shape #1115 asked a decision for: no container-format
change, no new dependency, one call site.

The template is already in the container (`tokenizer_config.json`'s `chat_template` string, else
`chat_template.jinja`), and the renderer is the pinned llama.cpp fork's own Jinja engine
(`third_party/llama.cpp/common/jinja`, the one `llama-server --jinja` uses).  `app/npu_template.h`
loads the template with the same read `app/template_pin.h` already did for the load line and the pin
(so the rendered prompt, the printed sha256 and the pin cannot disagree) and renders it; a template
that cannot be rendered is a 400 naming its sha256, never a fall back to ChatML.

Measured in each container's own tokenizer, one system+user request, before -> after:

  Qwen3-0.6B-NPU2 (a136047ba140) 31 -> 31     ZR1-1.5B (b6835114b730) 52 -> 21
  Qwen3-0.6B     (a55ee1b16601) 31 -> 31     bonsai2-27b (c3cf9e34abf4) 31 -> 71
  qwen3-coder    (87710339d25b) 31 -> 31     d3-lite-bf16 (273d8e0e683b) 31 -> 35

and served, on the NPU (npu-hold, one ticket, released clean):

  before (build with ONEBIT_JINJA=OFF, i.e. main's behaviour): ZR1 chat -> 400 "no <|im_start|>"
  after:                                                      ZR1 chat -> 200, prompt_tokens 21

Two defects found on the way, both in this PR: the request must be read as *ordered* JSON for the chat
path (a `nlohmann::json` is a std::map, so a `tools` block serialized through `tojson` would have been
alphabetized -- a prompt llama-server never produces), and `add_bos` must not prepend a second BOS when
the template already emitted it.

Tests: `tests/npu_template_test.cpp` compares the rendered bytes against **Jinja2 3.1.6 itself** for 11
cases across two shipped templates (Qwen3/FLM's and ZR1's DeepSeek-special one), plus the two refusal
rows; `--self-test`-style, device-free, no model.  `tests/data/templates/*.json` carry the fixtures and
where each byte came from.

Build: `ONEBIT_JINJA`, default on when `third_party/llama.cpp` is checked out (a tree without submodules
still builds, keeps #987's behaviour and says so at load); ci.yml checks out that submodule (shallow,
8 s) and builds the test, so the renderer cannot reach a green build unbuilt.  Docs: `docs/npu.md`
("Serving") and `docs/npu-chat-template.md`, which also records what this does *not* do: the answer
side still parses as the Qwen3 family, and request text that spells a model's control tokens is still
tokenized as those tokens (llama.cpp's own behaviour; the part-wise fix I built literalizes a real
template's BOS, measured 32 vs 21).

Fixes #963

Co-authored-by: x <x@x>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Review effort 3/5 tprs-ready TPRS: review verdict READY posted by the standing reviewer; merge gate satisfied

Projects

None yet

1 participant