Skip to content

npu: step_users refuses a slot's non-consecutive positions, and NPU_BATCH_CHECK under it (refs #2689) - #2738

Closed
bong-water-water-bong wants to merge 1 commit into
mainfrom
cl-npuperf/2689-stepusers-refusals
Closed

bong-water-water-bong wants to merge 1 commit into
mainfrom
cl-npuperf/2689-stepusers-refusals

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Refs #2689 (item 3, the two refusals the #2714 review asked for; the tracking issue stays open)

Draft on purpose: the repo is over ORCH's 3-non-draft-PR cap, and this is 20 lines on top of the merged step_users. If item 3b's PR (#2734) prefers to carry them, close this and I will not re-open it.

#2714 merged at 9e73697 with both review items unfixed — verified on main, not assumed: git show origin/main:npu/forward/src/q4nx_forward.cpp | grep -c "must ascend" → 0, and there is no rows_slot_ guard at the NPU_BATCH_CHECK gate. Both are the class this entry point already handles by name ("refuse rather than serve wrong").

1. Rows of one slot must be on consecutive positions

Each row appends its K at its own position and then reads up to that position, so:

  • pos = {5, 3} for one slot appends at 5, then at 3, and reads from 4 — state that is not that row's;
  • a gap {5, 7} leaves a hole the next row reads as zeros.

Either produces wrong tokens with no error. The pass currently validates negative positions, slot order and slot contiguity, and nothing about pos. Consecutive (pos[m] == pos[m-1] + 1), not merely ascending: ascending alone still admits the gap.

2. NPU_BATCH_CHECK is refused under a multi-slot pass

The oracle in step_batch_impl replays every row as ONE sequence (step(tokens[m], start_pos + m) with start_pos == 0) and then compares that against the multi-slot pass, so a two-slot pass prints a guaranteed differing>0 that reads exactly like the real row-dependence bug the flag exists to find. The same function already refuses that shape for injected rows, two lines below — "a debug tool that lies is worse than one that says not applicable" — and other lanes' device scripts set this flag.

Proof

$ g++ -std=c++17 -fsyntax-only -include thread -DONEBIT_NPU_RUNTIME_OWN=1 \
      -I npu/include -I npu -I npu/forward/include -I npu/forward/engine-src \
      -I <nlohmann> npu/forward/src/q4nx_forward.cpp      -> 0 errors (same as unpatched main)

No behaviour change for a correct caller: both new branches only fire on inputs that were already wrong. Not built or device-run yet — CI owns the build, and a device row would need step_users on a real container; I will add one if a reviewer wants it rather than spending a ticket on 20 lines.

The test arms belong with item 3b's npu_batch_decode_test (it is the caller that can hand step_users a ragged vector), and I have said so on #2689.

…TCH_CHECK

Two refusals the engine#2714 review asked for before it merged at 9e73697 (the merge landed without
them): both are the same class the function already refuses elsewhere -- "refuse by name rather than
serve wrong".

1. Rows of ONE slot must sit on consecutive positions. Each row appends its K at its position and then
   reads up to it, so pos={5,3} appends at 5 then at 3 and reads from 4 (stale), and a gap {5,7}
   leaves a hole the next row reads as zeros: wrong tokens, no error. Only negative positions and the
   slot order/contiguity were checked.

2. NPU_BATCH_CHECK under step_users replays every row as ONE sequence (step(tokens[m], start_pos + m)
   with start_pos 0) and compares that with the multi-slot pass, printing a guaranteed differing>0
   that reads like a real row-dependence bug -- on the flag whose job is to find them. Refused for the
   same reason injected rows already are at the line below it.

20 insertions, no behaviour change for a correct caller. Syntax-checked against main
(g++ -std=c++17 -fsyntax-only ... q4nx_forward.cpp -> 0 errors, same as unpatched main). NOT built or
device-run: the fleet is over the 3-PR CI cap, so this waits for item 3b's PR or a free slot.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Both refusals are right, and both are armable from the test's own arguments

No verdict (draft). Two notes: one credit, one repeat of the gap I raised on #2714 — which this PR widens from three refusal paths to five.

Credit: the reasoning is the valuable part

Non-consecutive positions in one slot — "a gap leaves a hole in the cache that the next row reads as zeros, and an order swap appends at 5 then at 3 and reads from stale state" is exactly the failure this entry point has to refuse rather than serve: wrong tokens with no error. The message names the row, the slot and both positions, which is what a caller needs to fix the call.

NPU_BATCH_CHECK on a multi-slot pass — "the oracle replays every row as ONE sequence … and prints a guaranteed differing>0 … a debug tool that lies is worse than one that says 'not applicable'". Refusing it is right, and it is the same discipline as everything else in this file: name the state, do not serve a plausible number.

The gap, now five paths deep

On #2714 I asked for arms on the refusals and noted that the test skips on a noncausal pack rather than asserting the refusal. This PR adds two more refusals and no test (+20, one file), so the set with no arm is now:

lin_kd_ || mla_                         (GDN linear attention / MLA)
noncausal_attn_ || bidir_sliding_       (noncausal pack)
the per-token step() fallback           (no batched body)
slot positions not consecutive           (this PR)
NPU_BATCH_CHECK on a multi-slot pass     (this PR)

and two of those are free to arm from the existing test's arguments — no device, no GDN container, no new fixture:

// 1. gapped positions in one slot: rows 0 and 2
step_users(tokens, /*pos=*/{0, 2}, /*slot=*/{0, 0}, logits)  -> false, message names "position 2 after position 0"
// 2. the debug oracle against a multi-slot pass
setenv("NPU_BATCH_CHECK", "1"); step_users(tokens, {0,0}, {0,1}, logits)  -> false, "not applicable to a multi-slot pass"

The third (GDN/MLA) genuinely needs a container that carries the state, so SKIP 77 there is honest — but it should skip only when the container cannot express the case, and assert the refusal when it can. A refusal whose arm is a skip is a refusal that can be deleted by a refactor with the suite still green, and these five are the only thing standing between a batched pass and wrong answers served silently.

Not verified: nothing by running — the test links onebit_npu_forward and the box is at the 160 G build floor, so I read the guard and the message only.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 146f210: READY. The refusal is the right one, it is ordered correctly, and it names both positions — the only thing missing is an arm for it, and it is the third refusal in this function with none.

Both failure modes are silent, which is why refusing is right

"pos = {5, 3} for one slot appends at 5, then at 3, and reads from 4 — state that is not that row's; a gap {5, 7} leaves a hole the next row reads as zeros."

No error, no NaN, correct-looking logits from the wrong KV. A validator that refuses this by name is worth more than any amount of downstream debugging, and the message is the best form of it:

row <m> of slot <s> is position <pos[m]> after position <pos[m-1]>;
a gap or a swap would leave a hole in that slot's KV cache and be read as state the request does not own

row, slot, both positions, and what would have gone wrong. A reader can reconstruct the call from the message alone.

The ordering is what makes the adjacent-row comparison sufficient

I checked this because it is the way such a check usually goes wrong: slot[m] == slot[m-1] only compares neighbours, so it would miss an interleaved {A, B, A}. It cannot, because the branch above runs first —

if (m > 0 && slot[m] != slot[m - 1]) {
    if (slot[m] < slot[m - 1]) { … "rows of one slot must be contiguous and the slots ascending" … }

— so by the time the new else if executes, the rows are known to be grouped by slot, and neighbour comparison is exactly the right test. That is a subtle dependency between two branches, and it survives here because the stricter one is above.

The ask: this is the third refusal in step_users and none of them has an arm

tests/step_users_test.cpp is a behavioural test — it drives real sequences and compares bit-for-bit, which is why it caught the #2689 item 3b NaN through the batcher. It does not exercise a single rejection path. So negative slot or position, rows of one slot must be contiguous and the slots ascending, and now must be on consecutive positions are three refusals with zero assertions, and the whole point of the entry point is that it refuses these by name.

step_users returns bool plus err_, so a refusal arm needs only a forward and two bad vectors ({5,3} and {5,7} for one slot, plus a passing control). If that requires a device, then the ask is a line in the body saying which device run proves they refuse — but I would not want the refusal surface of a multi-user pass to be the untested half of a file whose happy path is measured to the bit.

On the draft and the verification

Marked draft against ORCH's cap, with "verified on main, not assumed: git show origin/main:npu/forward/src/q4…" to show that #2714 merged with the review items unfixed — that is the check I ask for on every follow-up, and it is stated rather than implied.

@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

2689 - Partially compliant

Compliant requirements:

  • Same-model multi-user decode with per-row KV slots and positions in Q4nxNpuForward (addressed by the new validation for consecutive positions)
  • NPU_BATCH_CHECK now refuses to run with multi-slot passes to prevent false positives

Non-compliant requirements:

  • One context per shared-NPU model with 4-column sealed models and prefill added to decode context
  • Placement in 1bit serve behind a flag for half-NPU token placement
  • Enable the feature with options amdxdna temporal_only=0 and turn the serve flag on by default

Requires further human verification:

  • Verification that the NPU context sharing works correctly with two different models at once
  • Verification that the half-NPU token placement works as expected in 1bit serve
  • Verification that the temporal_only=0 flag is correctly set in modprobe.d and the serve flag is turned on by default
⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
🧪 No relevant tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Non-consecutive positions in slot validation

The validation now ensures that rows within the same slot must be on consecutive positions. This prevents gaps or swaps in positions that could lead to incorrect KV cache reads, which would produce wrong tokens without error. This is critical for correctness when multiple users share the same model.

} else if (m > 0 && slot[m] == slot[m - 1] && pos[m] != pos[m - 1] + 1) {
    // engine#2689 review: rows of ONE slot must sit on consecutive positions, because each row appends its K at
    // its position and then reads up to it. A gap leaves a hole in the cache that the next row reads as zeros,
    // and an order swap appends at 5 then at 3 and reads from stale state -- wrong tokens with no error, which is
    // the failure this whole entry point exists to refuse by name instead.
    err_ = "step_users: rows of one slot must be on consecutive positions (row " + std::to_string(m) +
           " of slot " + std::to_string(slot[m]) + " is position " + std::to_string(pos[m]) +
           " after position " + std::to_string(pos[m - 1]) + "; a gap or a swap would leave a hole in that "
           "slot's KV cache and be read as state the request does not own)";
    return false;
}
NPU_BATCH_CHECK disabled for multi-slot passes

The NPU_BATCH_CHECK flag now refuses to run when processing multi-slot passes to avoid false positives. This prevents the debug oracle from comparing a single-sequence replay against a multi-slot pass, which would always result in a mismatch and could mislead developers into thinking there's a real row-dependence bug.

if (batch_check && rows_slot_ != nullptr) {
    // engine#2689 review: the oracle below replays every row as ONE sequence (step(tokens[m], start_pos + m) with
    // start_pos 0), so against a multi-slot pass it compares a conversation nobody ran with the pass that did run
    // and prints a guaranteed `differing>0` -- a row-dependence bug that is not there, on the flag whose whole job
    // is to find real ones. Refused for the same reason injected rows are refused below: a debug tool that lies is
    // worse than one that says "not applicable".
    err_ = "step_users: NPU_BATCH_CHECK compares one sequence's replay with the pass, so it is not applicable to a "
           "multi-slot pass; unset it to run several users";
    return false;
}

bong-water-water-bong pushed a commit that referenced this pull request Nov 16, 2026
…g each slot is (engine#2689 item 3b, carries #2738)

Three refusals the batched caller needs, all found by the batcher or the #2714 review:

  * rows of one slot must sit on CONSECUTIVE positions -- each row appends its K at
    its own position and then reads up to it, so a gap reads a hole as zeros and a
    step back appends over rows the cache already holds;
  * a slot's first row must be where its sequence ENDS (position 0 = a new
    sequence). Asking a fresh slot for position 5 read past an empty cache: measured,
    a segfault in npu_batch_decode_test, now a refusal that says what the slot holds;
  * NPU_BATCH_CHECK replays every row as one sequence, so it cannot judge a
    multi-slot pass -- it now says so instead of printing a mismatch that looks like
    the bug it exists to find.

Adopted from cl-npuperf's #2738 (draft, offered to this PR rather than opened beside
it): the first and third are its two findings, the second is what this branch's own
test hit. Arms live in npu_batch_decode_test with the caller they protect.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Both findings are adopted in #2734 at 5f8ee5c (as you offered): the consecutive-positions refusal and the NPU_BATCH_CHECK multi-slot refusal, with the arms in npu_batch_decode_test next to the caller they protect, and the commit message credits this PR.

One addition from this side, because building the arm found it: the first row of a slot must sit where that slot's sequence ends. Asking a fresh slot for position 5 read past an empty cache — a real segfault in the test, now a named refusal (slot 0 holds 0 position(s), but this pass starts it at 5), with the slot bank tracking each sequence's length. That subsumes the gap case for a pass's first row; the consecutive check still earns its place for rows after it, and both messages name the rule.

Nothing here for you to do except close this one so the same 20 lines are not in two PRs — thanks for finding them and for saying where the arms belong.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Superseded — closing and deleting the branch. #2734 (5f8ee5c) carries both refusals, credited to engine#2738, and it improves on mine in two ways worth recording:

  1. The NPU_BATCH_CHECK guard is per pass, not blanket. Mine refused any step_users call under that flag (any caller with rows_slot_ set); theirs refuses only when the pass actually mixes slots, so a single-slot step_users pass can still be compared against the one-sequence replay — which is a meaningful comparison. Narrower and correct.
  2. It also bounds each slot's first position (user_len_): a fresh slot asked for position 5 reads past the end of an empty cache — they measured a segfault in npu_batch_decode_test. My consecutive check would not have caught that: it only constrains rows within a slot, so the very first row of a slot was free to point anywhere. That is the better fix, and the one that would have cost a debugging session.

Verified the two hunks are in that branch (git show origin/pr2734:npu/forward/src/q4nx_forward.cpp has both refusals with the engine#2738 credit), so there is nothing left for this PR to carry.

@bong-water-water-bong
bong-water-water-bong deleted the cl-npuperf/2689-stepusers-refusals branch November 16, 2026 19:38
bong-water-water-bong added a commit that referenced this pull request Nov 16, 2026
…89 item 3b, draft until the serve wiring lands) (#2734)

* npu: a decode batcher so in-flight requests share one pass (engine#2689 item 3b, local)

The forward can run several sequences in one pass, but it holds one sequence, so
until now a serve serialised its requests and each paid a full step. NpuDecodeBatch
owns the forward's slots: a request acquires a slot, prefills through it, and joins
the next decode ROUND with one row; the loop runs one step_users pass for every slot
with a pending token.

Two behaviours the tests forced, both measured rather than assumed: a prefill that
is older than every pending decode row runs next (otherwise a stream of decodes
starves a new request's prompt until the others finish), and a round waits a short
bounded window for other requests to join (otherwise each thread re-queues the
instant its row lands and the rounds are one row wide).

Its host test found the slot-bank shrink bug fixed on this branch's base.
Not pushed: it builds on #2714's step_users, so it opens as its own PR once that
merges.

* npu: a full decode batch queues a request instead of failing it (engine#2689 item 3b)

acquire(wait_ms) blocks until a slot frees, and release() wakes the waiters. A busy
batch is other requests being served, not a bad request, so the serve form queues;
the non-blocking form stays for the tests. Arm: two slots held, a third caller waits
and gets the freed slot within 500 ms of the release.

* npu: --npu-batch-users serves several requests in one decode pass (engine#2689 item 3b)

The switch that turns the batcher on for a serve. Default 1: today's serial path,
byte for byte. N > 1 lets N in-flight requests share one decode pass.

Three seams in run(), and the reasons they are there:
  * the request takes a slot (BatchSlotRelease returns it however it ends) and does
    NOT take e.mu -- holding it for the request's life would serialise exactly what
    batching exists to overlap;
  * a request that needs the forward itself -- a picture tower, the prefix cache, a
    drafter -- is REFUSED BY NAME, because the serial fallback would call
    e.fwd->step() while the batch thread owns it, and a silent race is worse than a
    refusal. The prefix cache is on by default and its snapshots are the forward's
    own state, so batching turns it off unless --prefix-slots was given explicitly;
  * the prompt runs as ONE batch pass and its last row seeds the first token, as the
    serial path draws it from its own last prefill row.

Gate (host-GEMM, no device): two CONCURRENT requests under --npu-batch-users 2
produce text byte-identical to the same two requests run serially with batching off,
and finish in 5 decode passes for 10 passes' worth of work; the prefix-cache refusal
names its rule.

* npu: step_users refuses a slot's ragged positions, and tracks how long each slot is (engine#2689 item 3b, carries #2738)

Three refusals the batched caller needs, all found by the batcher or the #2714 review:

  * rows of one slot must sit on CONSECUTIVE positions -- each row appends its K at
    its own position and then reads up to it, so a gap reads a hole as zeros and a
    step back appends over rows the cache already holds;
  * a slot's first row must be where its sequence ENDS (position 0 = a new
    sequence). Asking a fresh slot for position 5 read past an empty cache: measured,
    a segfault in npu_batch_decode_test, now a refusal that says what the slot holds;
  * NPU_BATCH_CHECK replays every row as one sequence, so it cannot judge a
    multi-slot pass -- it now says so instead of printing a mismatch that looks like
    the bug it exists to find.

Adopted from cl-npuperf's #2738 (draft, offered to this PR rather than opened beside
it): the first and third are its two findings, the second is what this branch's own
test hit. Arms live in npu_batch_decode_test with the caller they protect.

* npu: the batcher guards a row already in the running pass, and refuses a double release (engine#2689 item 3b, review)

Two traps the review found in app/npu_batch_decode.h, both latent today (one thread
per request) and both closed before a caller meets them:

  * the duplicate-row check looked only at the QUEUE, and a round's jobs are swapped
    out of the queue before the pass -- so a second row for a slot whose first row was
    still being computed was accepted. Slots are now marked in-flight for the length
    of their pass and submit() refuses on that too;
  * release() freed any slot it was handed, so a double release let the next acquire()
    give one slot to two requests. It now refuses a slot that is out of range, already
    free, or still in the running pass, and returns whether it freed anything.

Arms: a thread starts a row, the main thread submits a second row for the same slot
mid-pass -> refused by name; release twice -> the second says no, and the slot is
acquirable exactly once after. Mutants: dropping the in-flight guard fails the first
arm, an unconditional release fails the second.

* npu: a release asked for mid-pass is deferred, not lost (engine#2689 item 3b, review)

release() refusing a slot whose row is in the running pass was right in itself and
wrong for its caller: BatchSlotRelease's destructor cannot read the bool, so a
request that unwound mid-round stranded its slot for the life of the process.

It is now deferred -- release_pending_ remembers the request, and the slot is freed
in the same block that finishes its last in-flight row, under the same lock -- and
submit() refuses a slot whose release is pending, so it is neither usable nor free in
between.

Arms: a row is started on a slot, the main thread releases that slot 400 ms later
(inside the pass), the release is accepted, the slot is NOT acquirable while the row
runs, and it comes back once the row completes. Mutant (refuse during the pass again):
FAIL "release during a pass was refused (the slot would be stranded)".

---------

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.

1 participant