Skip to content

onnx: bench_npu_serve.py can measure a container whose chat route is disabled - #1140

Merged
bong-water-water-bong merged 3 commits into
mainfrom
bench-serve-endpoint
Nov 5, 2026
Merged

bong-water-water-bong merged 3 commits into
mainfrom
bench-serve-endpoint

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

onnx/bench_npu_serve.py is the only thing in the tree that reproduces AMD's model_benchmark layout (prompt
processing / token generation / E2E) from a server's own stream, and it drove /v1/chat/completions only. A container
whose chat route is deliberately disabled therefore had no number in AMD's units at all — not a slow row, an
unmeasurable one.

Root cause

The chat route refuses, on purpose and correctly, when the tokenizer has no ChatML tokens (#963):

bad request: 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

The gap is on the harness side, not in the refusal: /v1/completions serves such a container (app/forward_serve.cpp
renders nothing on that path, and the reply carries the same timings.prompt_ms / timings.predicted_ms and usage),
but the harness had no way to send it there. So the Llama-3.2-1B pack container — the family this engine's docs point at
/v1/completions for — could be measured for correctness (gate (a)/(b)) and not for speed in AMD's units.

The change

--endpoint {chat,completions}, default chat:

  • chat — unchanged body and URL, so every row taken before this switch stays reproducible;
  • completions — {"prompt": <text>, "max_tokens": ...} against /v1/completions, no template rendered. Sent as text
    rather than token ids because the harness has no tokenizer and needs none: the route tokenizes the prompt with the
    container's own tokenizer, and the count used for the rate comes back in usage (the same rule the chat path follows),
    so the two endpoints measure the same quantity.

Two lines beyond the switch, both in the same failure path the issue is about:

  • the stream counter now also accepts a chunk's text, which is the completions chunk shape (forward_serve.cpp streams
    choices[0].text there). Without it, --mode stream --endpoint completions would count zero tokens and fail with "no
    tokens streamed" instead of reporting a row;
  • a refusing server is now reported instead of crashing: urllib raises HTTPError on a 400, and the reason — which is
    precisely "send /v1/completions" — lives in the body the traceback discarded. Measured before that line:
BEFORE  $ python3 onnx/bench_npu_serve.py --host … --lens 64 --gen 8
        Traceback (most recent call last): … urllib.error.HTTPError: HTTP Error 400: Bad Request
AFTER   $ python3 onnx/bench_npu_serve.py --host … --lens 64 --gen 8
        HTTP 400 from http://…/v1/chat/completions: {"error": {"message": "bad request: this container's tokenizer
        has no <|im_start|> / <|im_end|>, … send /v1/completions with prompt as token ids (#938) …"}}

Proof

Two legs, neither taking an NPU dispatch.

1. The wiring, against a stand-in server that answers the chat route with the container's own 400 and the completions
route with a timings + usage reply (throwaway script, no repo file added). Default chat hits /v1/chat/completions
and reports the refusal; --endpoint completions hits /v1/completions, sends prompt (asserted: no messages key),
and prints the full AMD-layout table with prompt_tokens read from usage:

--- chat (default)   HTTP 400 from http://127.0.0.1:18178/v1/chat/completions: {"error": {"message": "bad request: this
                     container's tokenizer has no <|im_start|> / <|im_end|>"}}
--- completions      Number of Tokens: 60
                     Prompt processing (time to first token): avg (us): 240000  avg (tokens/s): 250.000
                     Token generation:                        avg (us): 285714.3  avg (tokens/s): 3.5000
                     E2E generation (entire generation loop):  avg (ms): 2240.00

2. The container this issue was filed on (~/ogaload/oga13/ctr-llama-b8, the Llama-3.2-1B pack container in
engine#671's gate table), forward-serve in host-GEMM mode on port 18090 — plumbing only, so the rate in this row is not
a speed claim (host GEMM on a loaded box; the device row is engine#671's business):

$ ~/wt/fwd-timings/build-npu/1bit forward-serve -m ctr-llama-b8/model.q4nx -p 18090   # NPU_INFER_HOST_GEMM=1
1bit forward-serve: chat route disabled: 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 …
1bit forward-serve: ctr-llama-b8 ready on http://127.0.0.1:18090 (full ELF)

=== BEFORE  python3 onnx/bench_npu_serve.py --host 127.0.0.1:18090 --lens 64 --gen 8 -w 0 -r 1
HTTP 400 from http://127.0.0.1:18090/v1/chat/completions: {"error":{"message":"bad request: this container's tokenizer
has no <|im_start|> / <|im_end|> … send /v1/completions with prompt as token ids (#938) …"}}

=== AFTER   python3 onnx/bench_npu_serve.py --host 127.0.0.1:18090 --lens 64 --gen 8 -w 0 -r 1 --endpoint completions
Prompt
  Number of Tokens: 69
Batch size: 1, prompt tokens: 69, tokens to generate: 8
  Prompt processing (time to first token):
      avg (us): 15073306  avg (tokens/s): 4.578  p50 (us): 15073306  stddev (us): 0  n: 1 * 69 token(s)
  Token generation:
      avg (us): 2410787.2  avg (tokens/s): 0.4148  p50 (us): 2410787.2  stddev (us): 0.0  n: 7 * 1 token(s)
  E2E generation (entire generation loop):
      avg (ms): 31948.82  p50 (ms): 31948.82  stddev (ms): 0.00  n: 1

The 69 prompt tokens are the container's own count from usage (the filler sentence is 13 tokens per repetition), which is
the number the rates are computed from — the same rule the chat path already followed.

python3 -m py_compile onnx/bench_npu_serve.py clean; tools/copyright.py --check clean (no new file, the Apache notice
is already on this one); no NPU dispatch, no :18097, no device lock taken for either leg.

closes #1125

…disabled

The harness that reproduces AMD's model_benchmark layout drove /v1/chat/completions only, so a
container with no ChatML tokens -- which the chat route refuses by design (#963) -- had no AMD-unit
number at all. --endpoint completions sends the prompt to /v1/completions, which renders no
template (#938) and reports the same usage/timings. Default stays chat, so earlier rows stand.

Also: count a chunk's `text` in stream mode (the completions chunk shape), and report a refusing
server's body instead of raising HTTPError, since that body is what names the route to use.

closes #1125

@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 (one nit, one note about a deliberate deviation from the issue's suggested shape)

I drove the harness against a stand-in server I wrote (not yours), so the wiring is checked by what it actually put on the wire, in all three combinations:

=== chat default (json)   rc=0   path=/v1/chat/completions
    keys=[max_tokens, messages, model, stream, temperature]  messages=True  prompt=False
=== completions (json)    rc=0   path=/v1/completions
    keys=[max_tokens, model, prompt, stream, temperature]    messages=False prompt=True
    Number of Tokens: 69          <- from usage.prompt_tokens, not from the prompt text
=== completions (stream)  rc=0   path=/v1/completions  stream_options={include_usage:true}
    Token generation: … n: 7 * 1 token(s)   <- so `choices[0].text` is counted; without the new line this fails
=== chat (stream)         rc=0   path=/v1/chat/completions, one delta per token, unchanged

The default really is unchanged: for chat the body is the same mapping in the same order ({"model": …, "messages": …, "max_tokens": …, …}) and the URL is untouched — I diffed the request the stub received, not the source.

The 400 path is better than the issue asked for, and I measured the truncation rather than eyeballing it: the real refusal body is 292 bytes, the cut is at 300, and send /v1/completions starts at byte 201 of it — so the actionable half survives, and rc=1 with no traceback:

HTTP 400 from http://127.0.0.1:18183/v1/chat/completions: {"error": {"message": "bad request: this container's
tokenizer has no <|im_start|> / <|im_end|>, … send /v1/completions with prompt as token ids (#938) …"}}

The engine side matches the three shapes the harness now relies on, read at this head: /v1/completions takes a string prompt (app/forward_serve.cpp:186), the non-stream reply carries choices[0].text (:529) with usage (:531) and timings (:532), and the stream chunk for the non-chat route is {"choices":[{"index":0,"text":…}]} (:572) with usage in the tail (:611) — which is exactly the choice.get("text") the counter now accepts. py_compile clean, tools/copyright.py --check rc 0, no new file.

Nit — the new switch is not reachable from the wrapper that operators actually run. onnx/bench_npu.sh forwards a whitelist of bench flags and rejects everything else before it touches the device:

$ onnx/bench_npu.sh --endpoint completions
bench_npu.sh: unknown option --endpoint            (exit 2, from the `*)` arm at :62)

so a chat-disabled container measured through the wrapper still gets the 400 — the fix is reachable only by calling the python directly. One word in the --lens|--gen|-w|--warmup|-r|--repeat|--mode arm (plus the row in the script's own usage block sed -n '2,30p') keeps the two entry points aligned. It fails loudly rather than silently, so it is a nit and not a blocker.

Note, for the record rather than as a complaint: #1125's suggested shape sends the prompt as token ids, and this sends text. The reason is argued in the body and I think it is the right call for this harness — it carries no tokenizer, the route tokenizes with the container's own, the count comes back in usage (the same rule the chat path already followed), and the ids form would need a tokenizer the tool does not have. What it does not give you is #938's parity property (ids skip tokenization, so two engines compare the forward); anyone wanting a parities row still has to run the ids form from the gate-(c) scripts. Worth one line in the --endpoint help so nobody reads text-mode rows as #938-parity rows.

Not run by me: your leg 2 (the Llama-3.2 container under forward-serve in host-GEMM mode). It needs your build, and I would not start a serve on this box for a plumbing check — the two legs above are enough to prove the change, and the row's rate is explicitly not a speed claim.

CI at this head: Analyze (actions/python/javascript-typescript) success, Analyze (c-cpp), Analyze (rust) and build still in progress, hw_gate skipped, pr_agent queued — so BLOCKED here is checks-not-finished, not a red.

…s not a #938 parity row

Review nit fixed where it bites: bench_npu.sh whitelists bench flags and rejected --endpoint before
it touched the device (exit 2, '"*)' arm), so the new switch was reachable only by calling the python
directly. The usage block gains the example. Also records in --endpoint's help the reviewer's note:
text is tokenized server-side, so a completions row is not #938 parity -- that needs ids, which the
gate (c) scripts send and this harness cannot without a tokenizer.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Nit fixed at 5959fa1a: onnx/bench_npu.sh now forwards --endpoint in the same whitelist arm as --mode/--lens, and the wrapper's usage block carries the example:

$ ONEBIT_BIN=/nonexistent onnx/bench_npu.sh --endpoint completions
bench_npu.sh: no engine binary at /nonexistent (set ONEBIT_BIN)     <- past arg parsing, to the next check
$ ONEBIT_BIN=/nonexistent onnx/bench_npu.sh --endpointnd completions
bench_npu.sh: unknown option --endpointnd                            <- a typo is still refused

Your note is now in the --endpoint help text rather than only in the PR body: text is tokenized server-side, so a completions row is not a #938 parity row — that needs ids, which the gate (c) scripts send and this harness cannot without a tokenizer. py_compile clean, tools/copyright.py --check rc 0, no device touched for this commit.

@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 5959fa1a — both nits closed, and the forwarding is proven by running the wrapper, not by reading the case arm

Nit 1 (wrapper): --endpoint is now in the forward arm, and I drove the whole wrapper to see it arrive at the harness. A stub engine binary that answers /v1/health and /v1/models, a python3 earlier on PATH that records its argv:

$ ONEBIT_BIN=<stub> ONEBIT_DX_KERNELS=<kern> ONEBIT_MODEL=<model> onnx/bench_npu.sh --endpoint completions --lens 64 --gen 8
INVOKED: -u onnx/bench_npu_serve.py --host 127.0.0.1:52625 --model  --endpoint completions --lens 64 --gen 8

So the container this PR exists for is now measurable through the wrapper, not only by calling the python directly. Two things I checked around it, because they are what a whitelist edit can break: --endpointx is still refused (bench_npu.sh: unknown option --endpointx, exit 2 — the arm is precise, not a wildcard), and bash -n + shellcheck -S warning are clean. The empty --model above is my stub's /v1/models parser being captured by the same fake python3, not the wrapper.

(Side observation, not a finding: the wrapper's "something already answers on port N; refusing to measure it" guard fired at me twice while I built that stub. It is correct and it is the kind of guard that stops a benchmark measuring another lane's server.)

Nit 2 (the parity note): the --endpoint help now carries it, printed by --help, at the point where someone deciding which endpoint to use will read it — "text is tokenized by the server, so a completions row is not a #938 parity row". That was the whole ask, and it is where the wrong conclusion would otherwise be drawn.

Nothing else moved. The python diff is that help string only, so my earlier evidence still describes this head, and I re-ran it to be sure: chat default unchanged (messages, no prompt, /v1/chat/completions), completions sends prompt and no messages to /v1/completions, and stream mode still counts the chunks.

CI at this head: CodeQL + all five Analyze success, build in progress, hw_gate skipped, MERGEABLE/BEHIND.

@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

963 - Partially compliant

Compliant requirements:

  • The chat route now properly checks for ChatML tokens in the tokenizer and returns a 400 error if they are missing
  • The bench_npu_serve.py script now supports the --endpoint flag to switch between chat and completions endpoints
  • The change maintains backward compatibility with existing working Qwen3/Qwen2-Chat rows

Non-compliant requirements:

  • The PR does not implement option 2 (real fix) of packing the model's chat_template from tokenizer_config.json into the container and rendering it

Requires further human verification:

  • Need to verify that the 400 error message is clear and actionable for users
  • Need to confirm that the completions endpoint properly measures containers with disabled chat routes
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 No relevant tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Error Handling for Disabled Chat Routes

The change introduces a try/except block to handle HTTP errors from the server, which is good for debugging. However, the error message handling could be improved to provide more context about why the endpoint failed, especially when the server returns a 400 error for containers with no ChatML tokens. The current implementation raises a SystemExit with a truncated error message that might not be sufficient for users to understand the root cause.

try:
    resp = urllib.request.urlopen(req, timeout=600)
except urllib.error.HTTPError as err:
    # A refusing server answers 400 with the reason in the body (the chat route on a container with no
    # ChatML tokens does exactly that); a traceback that drops the body leaves the user with no way to
    # know that --endpoint completions is the route for this container.
    raise SystemExit(f"HTTP {err.code} from {req.full_url}: {err.read().decode('utf-8', 'replace')[:300]}")
with resp:
Endpoint Switching Logic

The new --endpoint argument allows switching between chat and completions endpoints, which is necessary for measuring containers with disabled chat routes. However, the logic for determining which endpoint to use is based on the container's tokenizer configuration, which is not explicitly checked or validated in the bench script itself. This could lead to unexpected behavior if the container configuration is not properly set up.

def one_run(
    host: str, model: str, prompt: str, gen: int, mode: str = "json", endpoint: str = "chat"
) -> dict:
    # `chat` renders a ChatML prompt, which a tokenizer with no ChatML tokens cannot be given (#963);
    # `completions` sends the text as the prompt and renders nothing (#938), which is the only route a
    # Llama-family container can be measured on. Both report `usage` and `timings`, so the stages below
    # are the same quantity either way.
    prompt_field = (
        {"messages": [{"role": "user", "content": prompt}]}
        if endpoint == "chat"
        else {"prompt": prompt}
    )
    body = json.dumps(
        {
            "model": model,
            **prompt_field,
            "max_tokens": gen,
            "temperature": 0.0,
            "stream": mode == "stream",
            **({"stream_options": {"include_usage": True}} if mode == "stream" else {}),
        }
    ).encode()
    req = urllib.request.Request(
        f"http://{host}/v1/{'chat/completions' if endpoint == 'chat' else 'completions'}",

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

onnx: bench_npu_serve.py is chat-only, so a container with its chat route disabled cannot be measured in AMD's units

1 participant