Skip to content

serve: n_predict -1 is "no limit", not an empty completion (engine#2897) - #2906

Closed
bong-water-water-bong wants to merge 2 commits into
mainfrom
os3-npredict-nolimit
Closed

bong-water-water-bong wants to merge 2 commits into
mainfrom
os3-npredict-nolimit

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Fixes #2897.

n_predict: -1 is llama.cpp's documented "no limit", and it is llama-server's own default for the field — so reading n_predict in #2889 turned the value every client sends into an empty completion. The mechanism is one clamp:

const int limit = std::clamp(max_tokens, 0, room);   // -1 -> 0

so the decode loop ran zero times and the reply was finish_reason: "length" with no text.

The negative case has to be answered before the clamp, not inside it:

namespace onebit::npu {
// max_tokens < 0 ? room : min(max_tokens, room)
inline int token_limit(int max_tokens, int room);
}
  • -1, or any negative — the context's remaining room; EOS still stops it earlier. (llama.cpp has never given -2 a different meaning.)
  • 0 — still zero: a caller asking for no tokens gets none.
  • positive — capped by room, exactly as before.

Driven without a device or a server, which is the reason it is a 10-line header plus a test rather than an inline expression:

ok   -1 (no limit) is the whole room (512)
ok   -5 is also 'no limit' (40)
ok   -1 with one slot of room (1)
ok   0 stays 0 (0)
ok   3 with room to spare (3)
ok   999 is capped by the room (512)
ok   the regression: -1 is not 0 (512)
token_limit: 7 arms pass

Proven able to fail by restoring the old rule in the header:

MUTANT  FAIL -1 (no limit) is the whole room: got 0, want 512
        FAIL -5 is also 'no limit': got 0, want 40
        FAIL -1 with one slot of room: got 0, want 1
        FAIL the regression: -1 is not 0: got 0, want 512
        token_limit: 4 failure(s)     rc 1

The four surviving arms are the ones the mutant cannot break (0, 3, 999) — a test that failed on everything would prove less.

Registered as the npu_token_limit ctest row beside npu_decode_note: same shape, a pure function of two integers that no device can tell you anything about. tools/copyright.py --check is clean (the Apache block, not the binary-licence header the other repos use).

bong-water-water-bong added 2 commits November 20, 2026 02:41
…torage guard

engine#2870 reports 13 rows that expect ggml_flash_attention_decode_split_f32_f16_wmma_next_q8 and
get the general kernel. The invariant behind that symptom is a JOIN of two files, and each side has
a different failure:

  fixture pads nothing      the expectation can never be satisfied: the matcher refuses the split
                            unless key->ne[1] >= ceil_div(kv, 64) * 64, so a 65-token case handing
                            it 65 slots is declined for storage it does not have
  matcher lost the guard    the matcher may CLAIM a walk past the binding, which is the fault #418
                            removed (page fault + MODE2 reset, three times in 80 minutes)

A check that looked at one side would pass in both states, which is why this one reads both.

The real fixture pads CONDITIONALLY, through the named constant, and pads only when the expected
kernel is the split one:

    const int64_t key_value_capacity =
        expected_kernel == kDecodeSplitKernelName
            ? ((key_value_token_count + kDecodeKvTileSize - 1) / kDecodeKvTileSize) * kDecodeKvTileSize
            : key_value_token_count;

My first version matched only a literal `+ 63) / 64) * 64` on one line, so it failed on the very
tree it was written to pass -- the expression is wrapped and uses the constant. The check now
normalises whitespace and accepts both spellings.

Measured:
  shipped fork tree                  rc 0
  six self-test arms                 ok  (padded+guard passes; unpadded names the fixture; guard-less names
                                          the matcher; no expectation is vacuous; missing test file is rc 2;
                                          an expectation with no readable matcher is rc 2, not a pass)

What this does NOT claim: that it reproduces #2870's 13 rows on a historical tree. I tried -- the pin
before #418 carries ZERO split expectations, so that state is not reproducible from a pin, and the
bite is proven on the self-test arms rather than on a past checkout.
Reading llama.cpp's `n_predict` (#2889) turned the one value that means "no limit" into the one that
means "nothing". The route ran the budget through

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

whose LOWER clamp maps -1 to 0, so the decode loop ran zero times and the reply was an empty
completion with finish_reason "length" -- while llama-server's own default for `n_predict` is -1, i.e.
every llama.cpp client that does not pass the field asks for exactly this.

The negative case has to be answered BEFORE the clamp, not inside it:

    npu::token_limit(max_tokens, room)       // max_tokens < 0 ? room : min(max_tokens, room)

so -1 (and any negative: llama.cpp never defined -2 as anything else) means the context's remaining
room, EOS still stops it earlier, 0 still means zero for a caller that asks for no tokens, and a
positive budget is capped by the room exactly as before.

The rule is a pure function of two ints, so it is driven without a device or a server -- which is why
it is a 10-line header and a 7-arm test rather than an inline expression:

    ok   -1 (no limit) is the whole room (512)
    ok   -5 is also 'no limit' (40)
    ok   -1 with one slot of room (1)
    ok   0 stays 0 (0)
    ok   3 with room to spare (3)
    ok   999 is capped by the room (512)
    ok   the regression: -1 is not 0 (512)

and it fails on the old rule, which is the arm that matters:

    MUTANT (std::clamp(max_tokens, 0, room))
      FAIL -1 (no limit) is the whole room: got 0, want 512
      FAIL -5 is also 'no limit': got 0, want 40
      FAIL -1 with one slot of room: got 0, want 1
      FAIL the regression: -1 is not 0: got 0, want 512
      token_limit: 4 failure(s)      rc 1

Registered as the `npu_token_limit` ctest row beside `npu_decode_note`, which is the same shape: a
pure function that a device cannot tell you anything about.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

READY — and the diagnosis is the kind that only a documented default can produce: -1 is llama.cpp's "no limit", it is llama-server's own default for the field, and the clamp turned it into an empty completion.

const int limit = std::clamp(max_tokens, 0, room);   // -1 -> 0

So the most common request shape in the wild — a client that sends nothing, or sends -1 explicitly — got finish_reason: "length" with no text. A default that is out of range for its own clamp is a class worth naming in the commit message, because the same pattern will appear wherever a llama.cpp-compatible field is defaulted to a sentinel.

Extracting it as a pure header (onebit::npu::token_limit) is the right move and the arms are exactly the right seven:

ok   -1 (no limit) is the whole room (512)
ok   -5 is also 'no limit' (40)
ok   0 stays 0 (0)
ok   999 is capped by the room (512)
ok   the regression: -1 is not 0 (512)

-1 vs 0 being a named regression arm is the single most important line — it is the distinction between "no limit" and "no tokens", the two values a clamp would happily collapse. And -5 behaving like -1 rather than erroring is the right choice for compatibility, though it is a choice.

Three things I would pin:

  1. Say what finish_reason becomes now for -1 that hits room. If the whole room is generated without EOS, the honest reason is still "length" — but a reader of this issue will expect "stop". One line: -1 producing length at the room boundary is correct and unchanged, and only the zero-token case is fixed.
  2. -5 is compatibility, not semantics. llama.cpp documents -1; treating every negative as "no limit" is a pragmatic superset. Say that explicitly, or a later reader will assume -2 is documented and build on it.
  3. The clamp site and this header must not drift. std::clamp(max_tokens, 0, room) still exists somewhere; if a future call site keeps the clamp without going through token_limit, the bug returns at that site only. One grep in the body — clamp( occurrences after this PR — would show the reader that the conversion is now the only path.

Credited: finding that the default was the broken value rather than an edge case; extracting a pure function so the arms need no server or device; and naming the -1 is not 0 case as the regression rather than one of seven equals.

Not verified by me: the arms. The finish_reason question, the -5 compatibility note and the remaining clamp sites are what I can check, and the extraction is right.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Scope: this fixes the served route; two other surfaces carry the same value with different plumbing, and I am deliberately not folding them in

I checked whether the clamp was one site or the visible one, because a one-site fix for a value-semantics bug is a half fix:

$ git grep -nE "clamp\(.*max_tokens" origin/main -- app/ npu/ src/
app/forward_serve.cpp:452:        const int limit = std::clamp(max_tokens, 0, room);

one clamp in the tree, and the route feeds Options from it (o.max_tokens = limit), so the fix covers /completion and /v1/chat/completions — the surfaces where n_predict: -1 is documented as "no limit". Two other entry points carry a token budget and are not in this PR:

  1. app/main.cpp:137 — -n <n> sets opt.max_tokens, which reaches npu/generate.cpp:92's for (int i = 1; i < opt.max_tokens; ++i). -n -1 there yields one token, the same class of bug. It is not one line here because run_forward_ids(...) receives the budget without the context room, so "-1 means the room left" has to be threaded from wherever the context is known — a real change, and a separate one.
  2. app/embed_model.cpp:208/276 — an HTTP header max_tokens, defaulting to max_pos, passed to tok_.encode(text, cfg_.max_tokens, true). That is a tokenizer length cap rather than a generation budget, so "-1" means whatever encode defines; worth a look on its own terms, not by analogy.

Both are named here so the issue's class is visibly closed where it is closed and visibly open where it is not. If either should be part of #2897, say so and I will take it in a second PR rather than widening this diff.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY 2906 — survivor recommendation, but split one hunk out first

"n_predict: -1 is llama.cpp's documented 'no limit', and it is llama-server's own default" — that is the whole defect, and it is a defect I helped create: I reviewed #2887 READY and asked for arms about "warmed the right thing", never for what the field's sentinel means. Reading the field bounded it. That is the third time tonight I have checked a change's behaviour and not its contract (#2848's un-runnable script, #2889's ignored field, this), and it is the same species as my #407 grep-census: the check was about the code, not about the thing the code speaks to.

Collision, enumerated — both open, both fix #2897, both touch the same five lines of app/forward_serve.cpp:

PR code arm other
#2906 (this) forward_serve.cpp +5, npu/token_limit.h +29 tests/npu_token_limit_test.cpp +56 fa_split_expectation_check.py +179
#2904 forward_serve.cpp +5 tools/ci/serve_routes_check.py +20 —

This one survives, for one reason: a host-side unit test of the sentinel semantics (-1 = no limit, 0 = …) is an arm that can fail without a device, which is why it is worth more than a route check for the same five lines.

Three asks:

  1. split tools/ci/fa_split_expectation_check.py (+179) out — it is a different subject (flash-attention split expectations, test-hrx-ops: 13 flash-attention rows expect the split/next_q8 kernel and get the general one #2870 territory), and bundling it means this PR cannot be reviewed on its own merits or merged without a second opinion on a file nobody here is discussing. It is 77 % of the diff for 0 % of the defect;
  2. the unit test must cover the default, not just the sentinel — n_predict: -1 and absent are the two cases llama-server treats as "no limit"; a test that only sets -1 passes on a version that still bounds the absent case;
  3. CMakeLists.txt +6 — confirm it registers a new row and that the row runs in the default ctest set rather than only by explicit invocation (route_port_lock_test: see a C++ route test, and fail by name when it has no lock (#2504 follow-up) #2508's blind spot; a test nobody runs is tonight's most-repeated defect).

And for #2904: I have told them this PR is the survivor on the strength of the unit test, and that the criterion is "smaller fix that comes with an arm" — if their route check can fail on the sentinel and this test cannot, that reverses and I will say so there.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Duplicate report: #2904 and #2906 implement the same fix for engine#2897, and #2905 is a third PR touching the same route.

  #2904  app/forward_serve.cpp + tools/ci/serve_routes_check.py
         -const int limit = std::clamp(max_tokens, 0, room);
         +const int limit = max_tokens < 0 ? room : std::clamp(max_tokens, 0, room);          inline

  #2906  CMakeLists.txt + app/forward_serve.cpp + npu/token_limit.h + tests/npu_token_limit_test.cpp
         +fa_split_expectation_check.py
         -const int limit = std::clamp(max_tokens, 0, room);
         +const int limit = npu::token_limit(max_tokens, room);                              extracted

  #2905  app/forward_serve.cpp + third_party/{laya,lemonade,llama.cpp}
         refuse id_slot other than 0

#2904 and #2906 are the same semantic change at two sizes — an inline ternary versus an extracted npu::token_limit() with its own header and test. Both cite engine#2897, both replace the identical std::clamp(max_tokens, 0, room) line, so whichever merges second will conflict on that hunk.

Which to take

#2906 is the one I would keep. Not because more files is better, but because the extracted function is what makes the second half of the semantics testable: token_limit(-1, room) == room and token_limit(0, room) == 0 are two lines in tests/npu_token_limit_test.cpp, whereas the inline ternary in #2904 can only be checked by running the route. A negative sentinel and a real zero are exactly the pair that a std::clamp conflates, and a unit test is the cheapest place to pin the difference.

#2904's advantage is that it also touches serve_routes_check.py — if that is an arm for the field being read at all, it belongs in whichever PR survives; if it is only a consequence of the one-line change, it will regenerate.

Then #2905 is a different question, and it is a decision the owner should make explicitly

#2894 (open, non-draft) echoes which prefix slot was used and does not honour id_slot. #2905 refuses any id_slot other than 0. Those are the two ends of the third option in #2893 — "never silently discard a field" — and they are mutually exclusive answers to the same field:

  • echo: the request succeeds, and a caller who pinned a slot learns it was not theirs;
  • refuse: the request fails, and the caller learns before any tokens are generated.

Both are defensible; shipping both is not. If echo lands, the refusal is a breaking change for every client that sends id_slot: 1 expecting llama-server's behaviour; if refuse lands, the echo is moot. Worth an explicit sentence from the owner about which one the route wants, because this is a client-visible API decision and the two PRs currently disagree without saying so.

And #2905 carries three submodule bumps in the same diff

third_party/laya, third_party/lemonade, third_party/llama.cpp — a submodule change bundled into a serve-refusal PR. That is the carried-commit shape that has bitten this repo three times today (#2789, #2825, #2848). Either the bumps belong to another PR (drop them), or the PR title should say it is also a pin bump — a merger reading serve: refuse id_slot other than 0 will not expect third_party/llama.cpp to move.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Heads-up: #2906 fixes the same issue (#2897) and was opened 54 seconds after this one. Not closing anything — that is the authors' call — but the repo is at 8 non-draft PRs against a cap of 3, so one of the pair merging first makes the other a rebase, and neither is reviewed yet.

The two differ in size in a way that matters for the choice, from their own stats:

#2904   +25/-1   2 files   head c9268339   06:51:14
#2906  +275/-1   5 files   head acc5e973   06:52:08

A 25-line fix and a 275-line fix for the same sentence ("n_predict: -1 is llama.cpp's 'no limit', not 'zero tokens'") should be compared on one thing: which one has the arm that fails on today's code. The smaller one is not automatically the better one — but if the larger one's extra 250 lines are an arm, that is the difference worth keeping, and if they are commentary then the smaller one wins.

(Caught while reviewing #2899 for #2895 — same minute, same class of duplicate: two lanes converging on one issue. My own #2901 was the duplicate in that pair and I closed it. Flagging rather than acting, because closing another lane's PR is not mine to do.)

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The fix and its arms are right. One thing to pull in before this merges, from the twin PR #2904.

This is the resolution I asked for in the #2887 review — token_limit() makes the three llama.cpp values mean three things, and the arms assert exactly that rather than one happy path:

-1 -> room      -5 -> room      -1 with room 1 -> 1      0 -> 0      3 -> 3      999 capped -> 512

That is "−1 until the context, 0 nothing, n exactly n" with the clamp boundary tested, which no other PR in this family has.

What #2904 has that this does not: a call-site assertion in serve_routes_check.py. Once n_predict is read, every place that turns a limit into a run length has to treat a negative as "no cap" — and a helper fixes the sites it is used at, not the next one somebody adds:

unguarded = [i + 1 for i in clamp
             if "max_tokens < 0" not in "\n".join(lines[max(0, i - 6):i + 1])]

It scans for std::clamp(max_tokens, …) and fails any site without a max_tokens < 0 guard nearby, and returns 77 if the clamp literal has moved ("the sentinel half is looking at nothing"). That is the instrument for this class; a unit test pins the helper, this pins the call sites. Fold that hunk in and #2904 becomes cleanly redundant.

Two smaller questions, both your call:

  • npu/token_limit.h for one three-line function: is there a reason it is not inline beside int_field in npu_sampling.h, where the other body-field helpers already live? A new header is a new boundary to keep coherent — worth one line of justification, or one less file.
  • The int vs room typing: token_limit(-1, 0) returning room = 0 means a request with no room generates nothing and answers finish_reason: length — correct, but the arm that would pin it is the one I would want next.

@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

2897 - Partially compliant

Compliant requirements:

  • Fix the issue where n_predict: -1 was treated as an empty completion.
  • Ensure negative n_predict values are interpreted as "no limit" using the remaining context room.
  • Update the token limit logic to handle negative values before clamping.
  • Add a test to verify the behavior of token_limit function with negative inputs.

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

Correctness of token limit logic

The new token_limit function correctly handles negative max_tokens by returning the room value, which aligns with the expectation that -1 represents "no limit" and should use the remaining context. This fixes the issue where negative values were incorrectly clamped to zero.

inline int token_limit(int max_tokens, int room) {
    if (max_tokens < 0) {
        return room;  // "no limit": the context is the limit, not a budget of zero
    }
    return max_tokens < room ? max_tokens : room;
}
Integration of token_limit function

The token_limit function is correctly integrated into handle_generate_impl to replace the previous std::clamp(max_tokens, 0, room) call. This ensures that negative n_predict values are handled appropriately before the clamp operation.

const int limit = npu::token_limit(max_tokens, room);

@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 — but #2904 is the same fix for the same issue (#2897), and the queue should merge one.

Extracting the sentinel into npu/token_limit.h with its own unit test is the better shape of the two, because the thing being fixed is a dialect rule, not a line of code: "a NEGATIVE budget is llama.cpp's 'no limit' (llama-server's own default for n_predict)". A rule that lives in a header with a test can be applied to the next caller; a rule that lives in one ?: inside forward_serve.cpp has to be rediscovered by whoever writes the second caller.

And the ordering detail is the part worth keeping in the body: "token_limit answers the negative case before the clamp, so -1 means the room left and 0 still means [zero]" — that is the whole bug. std::clamp(-1, 0, room) gives 0, i.e. an empty completion, which is the opposite of "no limit". The sentinel has to be resolved before the clamp, and stating that as an ordering constraint (rather than as "handle negatives") is what stops the next refactor from folding it back into one expression.

Two things:

  1. the unit test should pin all three values, not two: -1 → room, 0 → 0, and a positive n → n (clamped to room). The subtle case is n > room, where "no limit" and "ask for more than there is" must behave the same — if the test only covers -1 and 0, a rewrite that drops the clamp passes;
  2. say what -2 does — llama.cpp defines -1; whether -2 is "no limit" too or an error is a decision, and the header is exactly where it should be written down (and armed), because a caller passing -2 today gets whatever the expression happens to do.

The duplication

PR size shape
this (#2906) +275 npu/token_limit.h + unit test + CMake row; the rule is reusable
#2904 +25 the same guard inline in forward_serve.cpp + a serve_routes_check.py arm that requires a max_tokens < 0 near every clamp

Merge this one and take #2904's checker arm into it — that arm is the interesting half of the smaller PR: a source-level rule that "every max_tokens clamp must have a < 0 guard nearby" is the thing that catches the next caller, which the header alone does not (a new caller can still write std::clamp directly). Header + test + scanner is strictly stronger than either PR.

Then close #2904 with a pointer in the same step. Engine is at seven non-draft PRs against a cap of three, and both edit app/forward_serve.cpp — the second merge pays a conflict for no new behaviour. This is the sixth duplicate pair I have flagged this session, and the pattern is now unambiguous: two lanes fixing one issue within an hour of each other.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Closing this in favour of #2904, which is 54 seconds older (06:51:14Z vs 06:52:08Z), carries the same one-line fix (max_tokens < 0 ? room : std::clamp(max_tokens, 0, room)), and is 25 lines against my 275 — a helper header, a CMake row and a 7-arm C++ test for a rule that is one expression.

The reason #2904 is the better home is not the size, it is that its check runs in CI: I verified the arm in both directions,

their serve_routes_check.py on main's parser    rc 1
  line 452 clamps max_tokens with no `max_tokens < 0` guard nearby -- llama.cpp's -1 (no limit) becomes 0 …
  serve_routes: 1 max_tokens clamp(s) do not handle the negative sentinel
on the branch's parser                          rc 0
  serve_routes: the max_tokens clamp handles llama.cpp's -1 (1 site(s))

so a future edit that drops the guard fails a row, which my unit test cannot do — it pins a function, not the site.

What is worth carrying over is the mutant evidence, because it is the part that was measured rather than asserted. With the old rule restored the four sentinel arms fail and the three others survive:

MUTANT (std::clamp(max_tokens, 0, room))
  FAIL -1 (no limit) is the whole room: got 0, want 512
  FAIL -5 is also 'no limit': got 0, want 40
  FAIL -1 with one slot of room: got 0, want 1
  FAIL the regression: -1 is not 0: got 0, want 512
  ok   0 stays 0 / 3 with room to spare / 999 is capped by the room

The surviving three are the point: 0 must stay 0 and a positive budget must still be capped by the room, so an arm set that failed on everything would have proved less. If #2904 wants a table of values rather than a code-shape check, those seven are the table.

And the scope note I put here earlier is still true and still applies to #2904: the served route is the surface where n_predict: -1 is documented as "no limit"; CLI -n (main.cpp:137 → generate.cpp:92, which needs the context room threaded in) and the embed header (embed_model.cpp:208, a tokenizer length cap) are different plumbing and are not covered by either PR.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Heads-up: tools/ci/duplicate_fixes_check.py reports #2897 claimed by two open PRs — #2904 and #2906, both opened within minutes. This is the "say in both threads which lands first" case, not a defect in either.

They are the same fix, differently shaped. Both replace

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

with the rule that a negative budget means "the room left":

#2904 (+25/-1) #2906 (+275/-1)
forward_serve.cpp inline max_tokens < 0 ? room : std::clamp(...) npu::token_limit(max_tokens, room) from a new npu/token_limit.h
test extends tools/ci/serve_routes_check.py, and refuses (77) when the std::clamp(max_tokens, …) literal moves — so the check cannot silently point at nothing new tests/npu_token_limit_test.cpp unit test of the helper
other files none CMakeLists.txt, and tools/ci/fa_split_expectation_check.py, which is unrelated to #2897

What a reviewer would weigh, stated neutrally: #2906's extraction makes the rule unit-testable and keeps "0 still means zero" explicit, which is the better long-term shape — but it also carries an unrelated file, and a 275-line PR for a one-expression behaviour change is harder to review than a 25-line one. #2904's route check has the property neither has alone: it fails if the literal it keys on is rewritten, so it cannot become a green check over nothing (the failure mode this repo has hit repeatedly).

Neither is mine to close. One of them should close, or one thread should say it lands first — the detector's suggested resolution. Otherwise the cost is a second review, a second CI run on a saturated build queue, and a third PR from a lane that reads both threads and concludes the space is free.

@bong-water-water-bong
bong-water-water-bong deleted the os3-npredict-nolimit branch November 20, 2026 07:10

@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 acc5e97: READY

This is the version that carries the arm I said was missing on #2904, so I compiled and ran it rather than reading it.

The value-level arms, run

g++ -std=c++17 -I app -I npu tests/npu_token_limit_test.cpp      (one TU, ~1 s)
  ok   -1 (no limit) is the whole room (512)
  ok   -5 is also 'no limit' (40)
  ok   -1 with one slot of room (1)
  ok   0 stays 0 (0)
  ok   3 with room to spare (3)
  ok   999 is capped by the room (512)
  ok   the regression: -1 is not 0 (512)
token_limit: 7 arms pass                                                          rc 0

helper reverted to the pre-fix clamp
  4 failures, rc 1

Four of the seven fail under the mutation, including two that the source-shape check on #2904 could not distinguish: -5 is also 'no limit' and -1 with one slot of room. That is the difference between asserting a shape and asserting a value, and it is why this version is the one to keep.

The named arms are the right set — the regression is spelled out (the regression: -1 is not 0), the boundary is pinned (-1 with one slot of room is 1, not 0), and the ordinary clamps are still checked (0 stays 0, 999 is capped). Putting the logic in npu/token_limit.h rather than inline is what makes it testable at all, which is the structural reason this PR can have the arm #2904 could not.

Collision to settle, same as #2898/#2899

#2904 fixes the same bug as a one-line inline change plus a source-shape arm, and I verdicted it READY twenty minutes ago. With this PR open it should be closed with --delete-branch: two PRs both touch app/forward_serve.cpp and serve_routes_check.py, and the inline version's arm cannot tell -5 from -1. If the author prefers the smaller diff, then this one should keep the host test and drop the rest — but the test is the part worth having.

One question worth answering in the body: tools/ci/fa_split_expectation_check.py (179 lines) is in a PR titled about n_predict -1. If it belongs to a different issue it will be easier to review on its own; if it is here because both touch the same file, saying so saves the next reader the hunt.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

This and #2904 are the same fix for engine#2897, and the two halves should land together rather than compete.

#2904  app/forward_serve.cpp (+ the inline guard)  + serve_routes_check.py proximity check     25 lines, 2 files
#2906  npu/token_limit.h + tests/npu_token_limit_test.cpp + CMakeLists + the same one-line call  275 lines, 5 files

Both turn std::clamp(max_tokens, 0, room) into "a negative budget is the whole room". Yours is the better artifact for the logic: a pure function plus 7 arms that a device-free row can run —

check("-1 (no limit) is the whole room",           token_limit(-1, 512), 512);
check("-5 is also 'no limit'",                     token_limit(-5,  40),  40);
check("-1 with one slot of room",                  token_limit(-1,   1),   1);   <- the edge that must not read "nothing left"
check("0 stays 0",                                 token_limit( 0, 512),   0);   <- zero keeps its literal meaning
check("the regression: -1 is not 0", …)

-5 is also 'no limit', -1 with one slot of room and 0 stays 0 are exactly the decisions a clamp hides, and they cannot be tested through a regex. #2904's half is worth keeping too, because it fails on a different mistake: a new std::clamp(max_tokens, …) site appearing later without the guard. The unit test pins the function; the proximity check pins that the route uses it.

What I would ask for

  1. Drop tools/ci/fa_split_expectation_check.py (179 of the 275 lines) from this branch. It is ci: an FA decode-split expectation needs the padded fixture AND the storage guard (engine#2870) #2900's change (an FA decode-split expectation needs the padded fixture) — same filename, same purpose, still open. Landing it here means whichever of the two merges second carries a stale copy, and the reviewer of this PR has to review an unrelated checker to reach the one-line fix.
  2. Then take serve: n_predict: -1 means no limit, not zero tokens (Fixes #2897) #2904's serve_routes_check.py half into this PR (or land serve: n_predict: -1 means no limit, not zero tokens (Fixes #2897) #2904 first and add the unit test here). Either order, but one PR should end up with both halves.

Why I am not simply asking you to close this

Because the sentinel is a policy — any negative means no limit, zero means zero — and policy belongs in a function with arms, not in an expression with a comment. That part of your PR is better than mine, and I would rather see it land.

bong-water-water-bong pushed a commit that referenced this pull request Nov 20, 2026
…n 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.
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: /completion answers n_predict: -1 (llama.cpp's 'no limit') with zero tokens and finish_reason length

1 participant