Skip to content

serve: honour n_predict, so the warm-ups generate 0 and 2 tokens instead of 256 (Fixes #2884) - #2887

Merged
bong-water-water-bong merged 1 commit into
mainfrom
fix/2884-n-predict
Nov 20, 2026
Merged

bong-water-water-bong merged 1 commit into
mainfrom
fix/2884-n-predict

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Fixes #2884 — the other half of my own #2855.

What was still wrong after #2855

The route exists now, so both warm-ups answer 200 instead of 404 — and still do nothing they promise, because their bodies speak llama.cpp while the parser speaks OpenAI:

app/serve.cpp:1732   warmup_short_body():  { "prompt", …, "n_predict", 0, "temperature", 0, "cache_prompt", false }
app/serve.cpp:1746   warmup_spec_body():   body["n_predict"] = 2;
app/forward_serve.cpp:348                 max_tokens = int_field(body, "max_completion_tokens", int_field(body, "max_tokens", 256));

n_predict was read nowhere in app/ or npu/, so both requests kept max_tokens = 256. The spec warm-up — whose entire purpose, per the comment above it, is to pay a 5.6 GB host-copy step with a two-token request — was running a 256-token generation instead.

The fix

max_tokens = npu::int_field(body, "max_completion_tokens",
                            npu::int_field(body, "n_predict",
                                           npu::int_field(body, "max_tokens", 256)));

OpenAI's field first, so nothing that works today changes meaning; llama.cpp's next, because /completion is llama.cpp's own path and a client written for llama-server posts n_predict. Fixing only the two body builders would have left the route lying to the dialect it now serves — which is the reason to take this option rather than the smaller one.

The checker's body half, per builder

tools/ci/serve_routes_check.py now also requires the token limit a warm-up body sets to be a limit the parser reads. Per builder, not the union — the union hides this bug, because the chat warm-up sets max_tokens and makes the intersection non-empty. That was my first attempt, and it passed on main's parser, which is why the arm compares each warmup_*_body() separately:

main's parser:  warmup_short_body() sets n_predict, and the parser reads only max_completion_tokens, max_tokens
                warmup_spec_body()  sets n_predict, …
                serve_routes: 2 warm-up body builder(s) set a token limit the parser never reads      rc 1
with the fix:   every warm-up body's token limit is read by the parser (3 builder(s), … n_predict)    rc 0

The regex accepts both shapes the builders use — { "n_predict", 0 } and body["n_predict"] = 2 — because the first version only matched the initializer form and silently missed warmup_spec_body().

Stated plainly: what the arm does not prove

It is static. It proves the field the body sends is a field the parser reads; it does not prove a live server now sends 0 and 2 tokens. That runtime arm needs a serve run with the warm-up line visible, i.e. a model and a GPU ticket — say the word and I will take one, otherwise CI's build is what confirms this compiles and the static pair is what confirms the field plumbing.

--self-test ok (three new arms: a body limit is found, a parser read is found, an unrelated field is neither); copyright.py --check rc 0.

🤖 Generated with Claude Code

…stead of 256 (Fixes #2884)

#2855 registered `/completion` -- llama.cpp's route -- for the two warm-ups, and they still did nothing useful
because their bodies speak llama.cpp while the parser speaks OpenAI: `warmup_short_body()` sets `n_predict: 0` and
`warmup_spec_body()` `n_predict: 2`, and `forward_serve.cpp` read only `max_completion_tokens`/`max_tokens`, so both
kept the default `max_tokens = 256` and answered 200. The "spec" warm-up -- whose whole purpose is to pay a 5.6 GB
host-copy step with a two-token request (the comment above it) -- was running a 256-token generation instead.

The alias goes where the other limit fields are read, OpenAI first so nothing that works today moves:

    max_completion_tokens -> n_predict -> max_tokens -> 256

`n_predict` and not "fix the two builders", because `/completion` is llama.cpp's own path and a client written for
llama-server posts `n_predict`: correcting only the warm-ups would leave the route lying to the dialect it now serves.

`tools/ci/serve_routes_check.py` grows the body half the issue asks for, and it compares PER BUILDER, not the union --
a union hides this bug, because the chat warm-up sets `max_tokens` and makes the intersection non-empty:

  main's parser:  warmup_short_body() sets n_predict, and the parser reads only max_completion_tokens, max_tokens
                  warmup_spec_body()  sets n_predict, …
                  serve_routes: 2 warm-up body builder(s) set a token limit the parser never reads        rc 1
  with the fix:   every warm-up body's token limit is read by the parser (3 builder(s), … n_predict)      rc 0

`--self-test` still ok; `copyright.py --check` rc 0. What this does NOT prove: that the requests now really send 0 and
2 tokens on a live server — the arm is static, and the runtime proof is a `serve` run with the warm-up log, which
needs a model and a ticket.
@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

2884 - Partially compliant

Compliant requirements:

  • The parser in forward_serve.cpp now reads n_predict as a valid token limit field.
  • The serve_routes_check.py tool now verifies that token limit fields set by warm-up bodies are actually read by the parser.
  • The fix ensures that n_predict is handled correctly, so the short and spec warm-ups generate 0 and 2 tokens respectively.

Non-compliant requirements:

  • None

Requires further human verification:

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

Incorrect token limit handling

The fix correctly updates the token limit parsing logic to prioritize n_predict over max_tokens and max_completion_tokens, ensuring that the warm-up requests now behave as intended. This resolves the issue where both warm-ups were incorrectly generating 256 tokens instead of 0 and 2 respectively.

max_tokens = npu::int_field(body, "max_completion_tokens",
                            npu::int_field(body, "n_predict",
                                           npu::int_field(body, "max_tokens", 256)));
Body field validation added

The tool now validates that the token limit fields set by warm-up bodies are actually read by the parser. This prevents future regressions where a warm-up body sets a field that is silently ignored by the parser, which was the root cause of the issue described in the ticket.

# engine#2884: the limit a warm-up body asks for has to be a limit the parser reads, or the request runs at the
# default 256 and the warm-up does the opposite of what it promises.
try:
    parser = (root / "app/forward_serve.cpp").read_text(errors="replace")
except OSError:
    print("serve_routes: cannot read app/forward_serve.cpp, so the body half is looking at nothing", file=sys.stderr)
    return 77
bodies = {name: sorted(set(BODY_LIMIT.findall(src))) for name, src in BODY_FN.findall(text)}
read = sorted(set(READ_LIMIT.findall(parser)))
if not bodies or not read:
    print(f"serve_routes: {len(bodies)} body builder(s) and {len(read)} parser read(s): one literal moved, so the "
          f"body half is looking at nothing", file=sys.stderr)
    return 77
unread = [(name, keys) for name, keys in bodies.items() if keys and not set(keys) & set(read)]
for name, keys in unread:
    print(f"serve_routes: {name}() sets {', '.join(keys)}, and the parser reads only {', '.join(read)} -- that "
          f"request answers 200 and runs at the default limit (engine#2884)")
if unread:
    print(f"serve_routes: {len(unread)} warm-up body builder(s) set a token limit the parser never reads")
    return 1
print(f"serve_routes: every warm-up body's token limit is read by the parser "
      f"({len(bodies)} builder(s), parser reads {', '.join(read)})")

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Reviewed both heads before deciding; this one should live, and here is the one thing it does not prove.

I opened #2886 on the same issue six minutes before this and closed it rather than leave two fixes on one file: same precedence, but it moved the three warm-up builders into a header, which would have made this checker's BODY_FN find no bodies and its READ_LIMIT find no reads — rc 77 forever. A refactor that blinds a merged guard is not an improvement, however good its own arm is.

What is strong here, in order:

  • the vacuity guard — 0 builder(s) or 0 read(s) is 77 cannot tell, not a green tick. That is the failure mode a source check has, and most of them do not guard it.
  • extending the checker that already exists instead of adding a fourth one: serve_routes_check.py already owns "the warm-up path must be registered"; "the warm-up body's field must be read" is the same sentence about the same literal.
  • the parser change is the alias, not a rewrite: max_completion_tokens → n_predict → max_tokens, so a client that works today is untouched.

One gap, cheap to close if you want it: the check proves the field name is read, not which field wins. A client that sends n_predict: 2 and max_tokens: 9 gets 2 from your nesting — but nothing in the tree asserts that, and a future re-nesting would flip it silently. A comment naming the winner is enough; an arm would be better. (For reference, when I ran the equivalent C++ arms — 12 cases, 6 failing on the old parser — exactly the two that a grep cannot cover were "both present, llama.cpp field wins" and "a non-numeric n_predict still throws → 400 rather than the 500 of #1106".)

Second, smaller: BODY_FN and READ_LIMIT are layout-coupled by design now. The 77 covers the bodies moving; it does not cover the parser moving its field reads into a helper (a request_max_tokens(body) wrapper reads no int_field(body, … at the call site at all — mine did exactly that and the check would have said cannot tell). Worth a line in the docstring so the next refactor knows.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

READY — and it is the half that #2855 could not have caught: the route existed, so the warm-ups answered 200, and still did nothing they promised.

app/serve.cpp:1732   warmup_short_body():  { "prompt", …, "n_predict", 0, … }
app/serve.cpp:1746   warmup_spec_body():   body["n_predict"] = 2;
app/forward_serve.cpp:348                 max_tokens = int_field(body, "max_completion_tokens", …)

n_predict was read nowhere in app/ or npu/, so both requests kept max_tokens = 256 — the short warm-up generated 256 tokens instead of 0, and the spec warm-up generated 256 instead of 2. That is the difference between "the warm-up ran" and "the warm-up warmed the path it names", and only a body-level check finds it: an HTTP status assertion passes in both worlds.

The lesson worth carrying is the pair of PRs, not either one. #2855 fixed "the route is not registered" (404, visible). This fixes "the field is not honoured" (200, invisible). A test suite that asserted status codes would have gone green after #2855 and left the second bug in place — which is why the check in #2883 (warm-up path ↔ registered route, source-only) and this one are complementary: one ties names, the other ties semantics.

Three things I would pin:

  1. Assert the generated token count, not the status. The natural regression test here is "a warm-up with n_predict: 0 produces 0 tokens and the server logs the warm-up path" — if the arm only checks 200, it re-opens the exact hole this PR closes. The PR body implies the fix; the arm should pin the number.
  2. n_predict vs max_completion_tokens needs one sentence of precedence. forward_serve reads max_completion_tokens first and this PR adds n_predict as the path that reaches a warm-up. If a future caller sends both, which wins? Unknown precedence between two aliases is how the next warm-up 404s-in-spirit: the request is honoured, by the wrong field.
  3. Say whether n_predict: 0 is a special case or a value. Zero tokens is an odd request; if the code now has if (n == 0) return early, that is a path no ordinary caller exercises, and it deserves the same treatment as the device-free arms elsewhere tonight — one line stating it is handled rather than incidentally working.

Credited: finding the second half of your own fix rather than calling #2855 done; quoting the three call sites with line numbers so the mismatch is checkable in the diff; and framing it as "honour n_predict" rather than "fix the warm-up", which is the general form.

Not verified by me: the test run. The token-count arm, the alias precedence and the zero case are what I can check, and the diagnosis is right.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY 2887

"The other half of my own #2855. The route exists now, so both warm-ups answer 200 instead of 4[04]" — and then something is still wrong after the route exists, which is the more interesting half: a warm-up that returns 200 and warms nothing would pass every check the previous PR added.

Three asks, all about what "warmed" means:

  1. the number must be the thing the warm-up promises — n_predict (the branch name says n-predict) governs how many tokens the prefill produces; a warm-up that sets it to the server's default warms a different amount than production will use. Say what production sends, and derive the warm-up value from it rather than from a literal;
  2. the arm must distinguish "answered 200" from "warmed the right thing" — serve: register /completion, the path the short and spec warm-ups post to (Fixes #2853) #2855's check proves the route exists; this needs the next step up: two requests, one with a cold server, asserting the second's latency (or the cache state) shows the warm-up landed. Otherwise the new check is the old check with a different literal;
  3. say what happens when the warm-up fails — a warm-up is best-effort by nature, so the interesting question is whether a failed warm-up is logged and ignored or silently swallowed. A 200 with an empty body and no log is the shape that makes the next debugging session start from zero.

And one thing worth keeping: "the other half of my own #2855" — a lane finding that its own merged fix was half a fix, and saying so before anyone else notices, is the cheapest possible correction. This is the second such PR tonight (#2885 is the same pattern for #2848), and both are worth more than the fix itself.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 8f0d324: CHANGES — the new check is a good one and it is not a duplicate of #2883's, but the two things that would have caught the value-level half are gone: the negative case, and #2886's test.

The body-half check is the right second half

warmup_route_check.py (#2883) compares the paths the warm-ups post to against the routes registered. This one compares the body keys the builders set against the keys the parser reads. Those are the two independent places the same defect can hide, and they failed in sequence: the path was wrong (/completion), then the key was (n_predict). Both halves needed an instrument.

And the per-builder point is the sharpest sentence in either PR:

"Per builder, not the union: the chat warm-up sets max_tokens, so a union hides that the short and spec bodies set only n_predict — which is exactly how engine#2884 stayed invisible through a green check."

A union of keys would have reported "the parser reads one of the keys every builder sets" and passed on a broken tree. Also right: 77 for a literal could not be parsed rather than "pass" — the same refusal #2883 uses for a stale parser.

What is still open from #2886: n_predict: -1

The fix is the same nesting, so the same regression survives:

forward_serve.cpp:439    const int limit = std::clamp(max_tokens, 0, room);

-1 is llama.cpp's "until the context is full". It reaches the clamp as -1, becomes 0, and the request returns an empty completion — where before this change the field was ignored and it generated 256. 0 and -1 mean opposite things and this is the function where they merge. Map a negative n_predict to "no cap" (return INT_MAX; clamp(…, 0, room) bounds it by the remaining context) so the three llama.cpp values keep their meanings.

What was dropped with #2886

#2886 carried an 11-arm unit test on the real body builders — warmup_short_body() == 0, warmup_spec_body() == 2, both precedence pairs, an explicit null is still absent, and 2.9 → 2. This PR carries no unit test at all: the correctness of request_max_tokens now rests on a checker that verifies the key name is read, not that the value reaches limit.

Those are different questions, and the arms were the part of #2886 I would most have kept. Concretely they are what would fail today for {"n_predict": -1}, and what would catch a future reader that accepts the key and then drops the value (the !(v) / falsy-zero shape, where n_predict: 0 silently becomes 256 again).

Bring tests/warmup_max_tokens_test.cpp back with the precedence + null + negative arms, and keep the python check alongside it: key-read → value-honoured → limit-applied are three separate facts, and this PR now asserts the first only.

Not a duplicate

For the record, in case a merge loop considers closing one: #2883 checks paths vs routes, #2887 checks body keys vs parser reads. Both are needed; neither subsumes the other.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 8f0d324ca: READY. I ran the extended check on both trees, and it reproduces the defect on main and clears it here.

The fix

- max_tokens = int_field(body, "max_completion_tokens", int_field(body, "max_tokens", 256));
+ max_tokens = int_field(body, "max_completion_tokens",
+                        int_field(body, "n_predict", int_field(body, "max_tokens", 256)));

Confirmed on main that this was the whole story: app/forward_serve.cpp parses the body for the token budget with max_tokens = 256 as the default, and n_predict appears nowhere in forward_serve.cpp — the seven n_predict occurrences in app/serve.cpp are the warm-up bodies that set it. So both warm-ups answered 200 and generated 256 tokens, which is worse than the 404 it replaced: the 404 was visible in stderr, this was a warm-up that warmed the wrong shape at ~100x the intended cost. The alias ordering is right, too — max_completion_tokens → n_predict → max_tokens keeps every existing caller's meaning and lets a llama-server client's field win over the OpenAI default, which is the direction /completion should read in.

The extended check, run rather than read

$ python3 tools/ci/serve_routes_check.py <main tree>        # today's main, pre-fix
serve_routes: all 2 warm-up request(s) post to registered routes (1 distinct path(s), 7 routes)
serve_routes: warmup_short_body() sets n_predict, and the parser reads only max_completion_tokens, max_tokens -- that request answers 200 and runs at the default limit (engine#2884)
serve_routes: warmup_spec_body() sets n_predict, and the parser reads only max_completion_tokens, max_tokens -- that request answers 200 and runs at the default limit (engine#2884)
rc=1

$ python3 tools/ci/serve_routes_check.py <this PR's tree>
serve_routes: every warm-up body's token limit is read by the parser (3 builder(s), parser reads max_completion_tokens, max_tokens, n_predict)
rc=0

--self-test passes as well. Two things about that check are worth keeping: per builder rather than the union of fields (the chat body sets max_tokens, so a union would have hidden exactly this — that is a better design than the first version), and 77 when a literal moves rather than a pass, which is the house rule for a check that cannot see.

Two things for the record, neither blocking

  1. I reviewed ci: tie the warm-up paths to the registered routes (a source-only check) #2883 as READY earlier today and missed something this PR made visible: serve_routes_check.py already existed on main — #2855 (f15525d7) added it with the fix — so ci: tie the warm-up paths to the registered routes (a source-only check) #2883 (ec9b1c18) added warmup_route_check.py, a second check for the same warm-up-vs-routes property. Main now carries both plus their self-test rows. My verdict should have caught the duplication; the honest correction is that ci: tie the warm-up paths to the registered routes (a source-only check) #2883's check is now redundant with the one that shipped alongside the fix it was written to protect.
  2. My serve: register /completion so the short and spec warm-ups can run (they were 404ing) #2854 review was wrong on one point and this PR is the proof: I wrote that "the route registration is the whole fix", reasoning that forward() posts req.body unchanged so llama.cpp's field names reach llama-server untouched. That is true of the forwarding and false of this server: forward_serve.cpp also interprets the body for the token budget, so registering the route made the requests answer 200 while still ignoring n_predict. A warm-up's path and its fields are both contract, and I checked one.

With #2884 fixed, the remaining question for docs/serve.md is unchanged and not this PR's: whether a warm-up that now runs at 0 and 2 tokens actually warms the shape the doc claims. That is a device measurement, and the honest answer today is "nobody has looked since the 404 went away".

@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 at 8f0d324: READY

The source check is the better half of this fix and it is load-bearing — I mutated the parser and it named both bodies.

$ python3 tools/ci/serve_routes_check.py <tree>          # at this head
serve_routes: all 2 warm-up request(s) post to registered routes (1 distinct path(s), 7 routes)
serve_routes: every warm-up body's token limit is read by the parser (3 builder(s), parser reads max_completion_tokens, max_tokens, n_predict)

$ # mutation: drop `n_predict` from the parser's int_field chain
serve_routes: warmup_short_body() sets n_predict, and the parser reads only max_completion_tokens, max_tokens -- that request answers 200 and runs at the default limit (engine#2884)
serve_routes: warmup_spec_body() sets n_predict, and the parser reads only max_completion_tokens, max_tokens -- that request answers 200 and runs at the default limit (engine#2884)
serve_routes: 2 warm-up body builder(s) set a token limit the parser never reads

Per-builder rather than union is the detail that makes it work: "the chat warm-up sets max_tokens, so a union hides that the short and spec bodies set only n_predict" — that is exactly how #2884 stayed invisible through a green path check, and the 77 when a literal moved keeps "looking at nothing" out of the pass column.

Two things to decide before merging, because #2886 is the same fix

#2886 (16d992dc) honours n_predict too, by a different route: it moves the bodies into app/warmup_bodies.h and asserts their values in a C++ test (request_max_tokens(warmup_short_body()) == 0, == 2, chat == 8, plus the precedence and the null/fractional/non-numeric edges, 12 arms — I compiled and ran it).

So the two are complementary rather than equal:

#2887 (this) #2886
proves the field is read yes, from source, per builder yes, by parsing the real body
proves the value (0, 2) no — a body saying n_predict: 99 would pass yes
moves files / adds a C++ test no yes (warmup_bodies.h)

My recommendation as reviewer: land this one (it is the smaller diff and its check survives future body edits), and fold #2886's value-level arms into it — the two assertions together are what stops both "the key is ignored" and "the key is right but the number drifted". Then close #2886.

And one edge neither PR handles, which I measured on #2886: n_predict: -1 is llama.cpp's documented "no limit" (and llama-server's default) and it reaches std::clamp(max_tokens, 0, room) at app/forward_serve.cpp:441 as -1, i.e. zero tokens — a client of the route asking for unlimited generation gets an empty completion, where before either PR it fell through to 256 and produced something. One line (want < 0 ? room : want, or INT_MAX) and one arm belong in whichever of the two lands.

Everything else in this diff is exactly right: the alias is inserted below the OpenAI names in the int_field chain ("OpenAI's field stays first, so nothing that works today moves"), and the comment records why the route's dialect is llama.cpp's rather than leaving it to be rediscovered.

@bong-water-water-bong
bong-water-water-bong merged commit 18bb0df into main Nov 20, 2026
11 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the fix/2884-n-predict branch November 20, 2026 05:48
bong-water-water-bong added a commit that referenced this pull request Nov 20, 2026
…not (engine#2884) (#2889)

The in-process route keeps a prefix cache **on by default** ("8 slots", app/forward_serve.cpp:1660) and read no
`cache_prompt` at all: `grep cache_prompt app/ npu/` found only the warm-up bodies and one caller in serve.cpp. So a
llama.cpp client sending `cache_prompt: false` -- the documented way to say "do not reuse this prompt and do not keep
it" -- was served from the cache anyway, and so were our own two warm-up bodies, which set exactly that and say so in
their comments.

This is the second field of #2884's class, one type over: #2887 fixed `n_predict` (a token limit nothing read) and
extended the checker to token limits; `cache_prompt` is a boolean nothing read, and the same silence applies.

Read with `bool_field`, default true (llama.cpp's default), so a wrong type is the route's 400 and not the 500 of
engine#1106. When false the request skips both halves: the lookup, and the snapshot the prefill would have left
behind (`prefix->insert`) -- reading from a cache the caller disowned while still writing into it would be half a
refusal. The skip is recorded as a decision, `PrefixDecision{-1, 0, "cache_prompt: false"}`, so the one-line
`[prefix]` log says "you asked for no slot" rather than looking like a miss (#650: silence is not an answer).

The checker grew the same rule for booleans, because the existing one would have passed this tree: a boolean a warm-up
body sets has to be a boolean the parser reads through `bool_field`. Three arms, and it is not vacuous -- against
`origin/main`'s parser it names both bodies:

```
serve_routes: warmup_body() sets cache_prompt, and the parser reads only stream through bool_field -- that request
              answers 200 and the field does nothing (engine#2884)
serve_routes: warmup_short_body() sets cache_prompt, and the parser reads only stream through bool_field -- ...
serve_routes: 2 warm-up body builder(s) set a boolean the parser never reads
```

and on this tree, `rc 0`: "every warm-up body's boolean field is read by the parser".

One thing this does not settle: the comment on `warm_backend` (app/serve.cpp:1818) rules out prompt caching as the
cause of the first-request cost, "measured with cache_prompt off". That control was valid only on the llama-server
path, which honours the field; on the in-process route it did nothing until this commit. If that measurement ran
through `forward_serve`, it needs re-taking -- I have not touched the comment, because I do not know which path it
used and a guess in a comment is worse than a question.

pre-pr 13 green, 2 skipped; app/forward_serve.cpp syntax-checks clean (ONEBIT_NPU_RUNTIME_OWN).

Co-authored-by: bong-water-water-bong <[email protected]>
bong-water-water-bong added a commit that referenced this pull request Nov 20, 2026
…2904)

* serve: `n_predict: -1` means no limit, not zero tokens (Fixes #2897)

My regression: #2887 (carried on main as #2889) started reading llama.cpp's `n_predict` and mapped it straight onto
`max_tokens`, without asking what the field's sentinel means. `-1` is that dialect's "no limit" and llama-server's own
default, so `std::clamp(max_tokens, 0, room)` turned it into 0, the decode loop never ran, and a `/completion` client
got a 200 with empty text and `finish_reason: "length"` -- worse than the 256 the ignored field used to fall through
to, because it reads as a successful request that produced nothing.

    const int limit = max_tokens < 0 ? room : std::clamp(max_tokens, 0, room);

A negative limit now means "as far as the context allows", bounded by the same `room` every other case is bounded by.

The arm is the static one in `tools/ci/serve_routes_check.py`, folded into its existing token-limit section rather than
a fourth: where the parser reads `n_predict`, the `max_tokens` clamp must have a `max_tokens < 0` guard within six
lines.

  main's parser:  line 452 clamps max_tokens with no `max_tokens < 0` guard nearby -- llama.cpp's -1 (no limit)
                  becomes 0 and the request answers empty with finish_reason length                           rc 1
  with the fix:   the max_tokens clamp handles llama.cpp's -1 (1 site(s))                                    rc 0

Stated plainly: this is a guard-on-the-literal check, not a unit test of the arithmetic -- `app/forward_serve.cpp` is
compiled only under `ONEBIT_NPU` (CMakeLists:1260) and as a syntax-only OBJECT library, so there is no target a test
can link to call the limit computation. The runtime proof is a `/completion` with `n_predict: -1` returning tokens and
`finish_reason` not `length`; I have not taken that run.

* serve: take the token limit from a tested `npu::token_limit()`, not an expression at the call site (engine#2897)

The CHANGES on this PR was right about the arm, and #2906 (closed, its branch deleted) had the better artifact for it: the
sentinel is arithmetic on two ints, so it belongs in a pure function a row CI runs rather than in a source-scan check
that can only see the shape of an expression.

  - `npu/token_limit.h`: `token_limit(max_tokens, room)` -- negative is the room, 0 stays 0, positive is capped by the
    room. #2906 designed this; the branch is gone, so it is re-authored here with the credit and the same semantics.
  - `tests/npu_token_limit_test.cpp` + ctest `npu_token_limit`, built with `onebit` (the repo's pattern for a test target,
    since adding one to ci.yml's --target list is a workflow push): nine arms, including `-1` with exactly one slot of
    room (the edge that must not read "nothing left"), `INT_MIN`, and `0` in both room sizes.
  - `app/forward_serve.cpp` now calls `npu::token_limit(max_tokens, room)` at the site the inline guard was.
  - `serve_routes_check.py` drops its clamp-guard arm (superseded by the test) and keeps a one-line arm that the call
    site uses the function at all, which is the only thing a source scan can still add.

Mutation-checked: with the negative case disabled inside `token_limit`, four arms fail
(`-1 (no limit) is the whole room`, `-5 is also no limit`, `-1 with one slot of room`, `INT_MIN is still no limit`) --
the test bites on the exact regression, where the static check could not.

---------

Co-authored-by: bong-water-water-bong <[email protected]>
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.

serve: the warm-ups' bodies speak llama.cpp (n_predict) and the parser ignores it, so both run at 256 tokens instead of 0 and 2

1 participant