Skip to content
6 changes: 4 additions & 2 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -575,8 +575,10 @@ add_dependencies(npu_sampling_test systemone_route_test)
# and the bytes it produces, which is the half of issue #832 a test can pin without a model.
add_executable(npu_chatml_test tests/npu_chatml_test.cpp)
target_include_directories(npu_chatml_test PRIVATE ${CMAKE_SOURCE_DIR}/app ${CMAKE_SOURCE_DIR}/npu)
target_link_libraries(npu_chatml_test PRIVATE nlohmann_json::nlohmann_json)
add_test(NAME npu_chatml COMMAND npu_chatml_test)
target_link_libraries(npu_chatml_test PRIVATE onebit_npu nlohmann_json::nlohmann_json)
# The #963 rows read the two fixtures: a tokenizer with ChatML anchors (served) and one without (refused).
add_test(NAME npu_chatml COMMAND npu_chatml_test ${CMAKE_SOURCE_DIR}/tests/data/tokenizer_chatml.json
${CMAKE_SOURCE_DIR}/tests/data/tokenizer_linear.json)
# Same reason as the other device-free tests: ci.yml builds a named list of targets, so a test whose
# target is not built reports "Not Run" (#635). This lane's token cannot edit the workflow.
add_dependencies(npu_sampling_test npu_chatml_test)
Expand Down
37 changes: 34 additions & 3 deletions app/forward_serve.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
//
// GET /health, /v1/health 200 once the model is on the device
// GET /v1/models the one model
// POST /v1/chat/completions ChatML prompt, sampling controls, optional SSE stream
// POST /v1/chat/completions ChatML prompt, sampling controls, optional SSE stream (400 when the
// container's tokenizer cannot represent ChatML, app/npu_chatml.h)
// POST /v1/completions raw prompt
// POST /v1/systemone d3 decision questions (alias /v1/decisions), when the model
// GET /v1/systemone/models directory carries a decision head -- see docs/npu.md "Decisions"
Expand Down Expand Up @@ -81,6 +82,11 @@ struct ForwardEngine {
int eos = -1;
int endoftext = -1;
int max_context = 0; // config.json max_position_embeddings: prompt plus answer
// The chat route renders ChatML for every container (#832), so whether this container's
// tokenizer can represent that prompt is a property of the container: decided once at load
// (#963). A refusal, not a load failure -- the id route stays usable on such a container.
bool chatml_ok = true;
std::string chatml_refusal; // empty unless !chatml_ok; the 400's message
// decode() of every vocabulary id, built on the first constrained request: the GBNF
// mask tests each token's text against the grammar state, per token.
std::vector<std::string> tok_text;
Expand Down Expand Up @@ -164,8 +170,10 @@ void handle_generate(ForwardEngine& e, const httplib::Request& req, httplib::Res
std::vector<int> prompt_ids;
bool prompt_is_ids = false;
try {
if (chat) prompt = npu::chatml(body.at("messages"), npu::thinking_from_body(body));
else {
if (chat) {
if (!e.chatml_ok) throw std::runtime_error(e.chatml_refusal);
prompt = npu::chatml(body.at("messages"), npu::thinking_from_body(body));
} else {
prompt_is_ids = npu::prompt_ids_from_body(body, e.tok->size(), prompt_ids);
if (!prompt_is_ids) prompt = body.at("prompt").get<std::string>();
}
Expand Down Expand Up @@ -743,6 +751,29 @@ int run_forward_serve(int argc, char** argv) {
e.max_context = q4nx_config_int(cfg.c_str(), "max_position_embeddings", 0);
if (e.max_context <= 0) e.max_context = 32768;

// #963: the chat route's prompt is ChatML for every container, and a tokenizer with no
// <|im_start|>/<|im_end|> added token cannot represent it -- the marker becomes ordinary pieces and
// the model reads text its own template never produces (zyphra/ZR1-1.5B: 33 tokens rendered
// against 15 under the model's template). Refused per request rather than refused at load,
// because /v1/completions with token ids (#938) is the way to serve such a container correctly.
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());
}

// The prompt cache (#650): --prefix-slots 0 turns it off, and an invalid value is refused here
// rather than clamped, like every other option on this command.
if (prefix_opts.slots > 0) {
Expand Down
16 changes: 16 additions & 0 deletions app/npu_chatml.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
// `app/unified.cpp`'s lane has always honoured it, and this emits the same bytes.
#pragma once

#include "tokenizer.h"

#include <nlohmann/json.hpp>

#include <string>
Expand Down Expand Up @@ -59,4 +61,18 @@ inline std::string chatml(const nlohmann::json& messages, bool thinking = true)
return p;
}

// Whether the container's tokenizer can represent the prompt above. `chatml()` is rendered for
// every container (#832), and a tokenizer without the anchors spells `<|im_start|>` as ordinary
// pieces, so the model is prompted with text its own template never produces (#963: on
// Zyphra/ZR1-1.5B, whose specials are DeepSeek's, 33 tokens rendered against 15 under the model's
// template). The route answers 400 in that case instead of answering plausibly from the wrong
// prompt.
//
// A necessary condition read off the container itself, not a proof that the template *is* ChatML: a
// container may carry both anchors and still use a different template. Packing the model's own
// `chat_template` is the real fix and a format decision, not this check.
inline bool chatml_supported(const Tokenizer& tok) {
return tok.token_id("<|im_start|>") >= 0 && tok.token_id("<|im_end|>") >= 0;
}

} // namespace onebit::npu
17 changes: 16 additions & 1 deletion docs/npu.md
Original file line number Diff line number Diff line change
Expand Up @@ -780,7 +780,8 @@ that runs the phase is private, like the kernels it runs.
all 14 match, ids and round trip.
- **Endpoints:** `/v1/health` (503 while loading), `/v1/models`, `/v1/chat/completions`
(streaming or not) and `/v1/completions`.
- **Prompt:** ChatML, Qwen2/Qwen3's template for text messages.
- **Prompt:** ChatML, Qwen2/Qwen3's template for text messages — for a container whose tokenizer has the
ChatML anchors. One that does not is refused on the chat route rather than prompted anyway (#963).
- **Decoding:** greedy, with a 1.1 repetition penalty over the last 64 ids by default.
`repetition_penalty` in the request overrides it, and 1 gives plain greedy.
- **One request at a time:** the model has one KV cache.
Expand Down Expand Up @@ -851,6 +852,20 @@ got before.
| `grammar` | a GBNF grammar in llama.cpp's format (`third_party/llama.cpp/grammars/*.gbnf`) the answer cannot leave |
| `response_format` | `{"type": "json_object"}` constrains the answer to JSON; `{"type": "json_schema", "json_schema": {"schema": …}}` constrains it to that JSON Schema |

Every chat prompt is rendered with **ChatML** (`app/npu_chatml.h`), the template Qwen2/Qwen3 use, not with a
template read out of the container. A container whose tokenizer has no `<|im_start|>`/`<|im_end|>` added token
cannot represent that text — the marker becomes ordinary pieces — so `/v1/chat/completions` answers **400**
naming the model's own specials instead of prompting it with text its tokenizer never produces (#963). The
measured cost of getting it wrong on Zyphra/ZR1-1.5B, whose specials are DeepSeek's: the same request is **23
tokens under this render against 9** under Qwen3's tokenizer, and `<|im_start|>` alone is **6 pieces**.

`/v1/completions` is unaffected, and it is how such a container is served: it takes the prompt as token ids
(`prompt: [ids]`, #938), so a caller renders the model's own template and sends those ids. The check reads the
container's tokenizer **once at load** (`chatml_supported()`), so it costs a request nothing, and it is a
necessary condition rather than a proof — a container can carry both anchors and still use another template.
Packing the model's `chat_template` into the container is what closes that gap, and it is a container-format
decision, not something this route does.

`logprobs` keeps OpenAI's shape: non-streamed, every entry is `choices[0].logprobs.content[i] =
{token, logprob, top_logprobs: [{token, logprob}]}`; streamed, each chunk carries the entries whose bytes that
chunk carries, so the deltas add up to the non-streamed reply. Token text that is half a character is reported with the invalid bytes replaced, never as a failed
Expand Down
51 changes: 51 additions & 0 deletions tests/data/tokenizer_chatml.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{
"version": "1.0",
"added_tokens": [
{
"id": 7,
"content": "<|im_start|>",
"special": true
},
{
"id": 8,
"content": "<|im_end|>",
"special": true
}
],
"pre_tokenizer": {
"type": "ByteLevel",
"add_prefix_space": false,
"trim_offsets": true,
"use_regex": true
},
"model": {
"type": "BPE",
"vocab": {
"a": 0,
"b": 1,
"Ġ": 2,
"aa": 3,
"aaaa": 4,
"aaaaaaaa": 5,
"ab": 6
},
"merges": [
[
"a",
"a"
],
[
"aa",
"aa"
],
[
"aaaa",
"aaaa"
],
[
"a",
"b"
]
]
}
}
29 changes: 26 additions & 3 deletions tests/npu_chatml_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@
// limitations under the License.

// npu_chatml_test: the Qwen3-lane chat prompt of `forward-serve` (app/npu_chatml.h, issue #832) -- the
// request's `chat_template_kwargs.enable_thinking` and the bytes it produces. No model, no device, no
// network.
// request's `chat_template_kwargs.enable_thinking` and the bytes it produces -- plus the container check of
// #963: whether the model's tokenizer can represent that prompt at all. No model, no device, no network;
// the two tokenizers are fixtures under tests/data.
//
// What this can and cannot pin: the prompt is the only part of "turn thinking off" the route controls.
// Whether the model then answers outside `<think>` -- and so whether `logprobs.content` comes back
Expand All @@ -32,6 +33,7 @@

using nlohmann::json;
using onebit::npu::chatml;
using onebit::npu::chatml_supported;
using onebit::npu::kEmptyThink;
using onebit::npu::thinking_from_body;

Expand All @@ -48,7 +50,11 @@ static bool ends_with(const std::string& s, const std::string& tail) {
return s.size() >= tail.size() && s.compare(s.size() - tail.size(), tail.size(), tail) == 0;
}

int main() {
int main(int argc, char** argv) {
if (argc < 3) {
std::printf("usage: npu_chatml_test <tokenizer.json with ChatML anchors> <tokenizer.json without>\n");
return 2;
}
const json msgs = json::array({{{"role", "user"}, {"content", "hi"}}});
const std::string assistant = "<|im_start|>assistant\n";

Expand Down Expand Up @@ -103,6 +109,23 @@ int main() {
}
check(threw, "a non-boolean enable_thinking throws (the caller answers 400)");

// #963: is this container's tokenizer able to represent the prompt at all? The anchors have to be
// vocabulary entries -- an added token stays whole, while text the pre-tokenizer merely splits is what
// made the render 23 tokens where Qwen3's own tokenizer spends 9 on the same request, and 33 against 15
// under the model's own template on Zyphra/ZR1-1.5B.
const onebit::npu::Tokenizer with_anchors(argv[1]);
const onebit::npu::Tokenizer without(argv[2]);
check(chatml_supported(with_anchors), "a tokenizer with <|im_start|>/<|im_end|> is served the chat route");
check(!chatml_supported(without), "a tokenizer without them is refused, not prompted anyway (#963)");
check(with_anchors.encode("<|im_start|>").size() == 1 && with_anchors.token_id("<|im_start|>") >= 0,
"with the anchor the marker is one token, which is what ChatML requires");
check(with_anchors.encode(chatml(msgs, true))[0] == with_anchors.token_id("<|im_start|>"),
"the rendered prompt opens with that anchor token");
check(without.token_id("<|im_start|>") < 0 && without.token_id("<|im_end|>") < 0,
"without it there is no such id: the refusal's condition is the anchor, not the prompt's length");
check(!without.encode(chatml(msgs, true)).empty(),
"the refusal is not about whether the prompt tokenizes at all -- it does, into the wrong ids");

if (failures == 0) std::printf("npu_chatml: ok\n");
return failures == 0 ? 0 : 1;
}
Loading