Skip to content

npu: one decode pass carries several users, each row bit-identical to its own run (engine#2689 item 3) - #2714

Merged
bong-water-water-bong merged 4 commits into
mainfrom
1bit/2689-step-users
Nov 16, 2026
Merged

bong-water-water-bong merged 4 commits into
mainfrom
1bit/2689-step-users

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Refs #2689 (item 3, forward half; the tracking issue stays open)

One decode pass, several users. A decode step is M rows of the M=16 design and one user fills one of them, while
the step costs the same from 1 to 16 rows (measured 11-16: Llama-3.2-1B ≈ 146 ms, Qwen3-1.7B ≈ 214 ms, exact at
every N). So 16 users of one model cost about what one does -- and nothing in the engine could put them in one pass:
Q4nxNpuForward holds ONE sequence (kcache_/vcache_, 24 sites inside step_batch_impl deriving a row's position
from start_pos).

What changed

npu/forward/{include/q4nx_forward.h,src/q4nx_forward.cpp}:

  • step_users(tokens, pos, slot, logits_all) — one batched pass, one entry per row. Rows of one slot must be
    contiguous and the slots ascending; returns M × NV logits exactly like step_batch_all().
  • Per-row positions. row_pos(m) replaces start_pos + m in the attention position and in the read length / window
    start handed to q4nx_attn::rows_context (which already took both per row — that helper is unchanged).
  • Per-slot KV. load_user_slot(s) swaps slot s's cache into the working kcache_/vcache_ pair (what
    attention() and rows_context() read) and back; the model's own caches are parked for the duration of the pass and
    restored whatever happens. The layer GEMMs are untouched: they are position-independent and already one launch for M
    rows, so the attention block simply runs once per slot group.
  • Refusals by name rather than wrong tokens: GDN linear attention (lin_kd_) and MLA keep a recurrence/absorption
    state per sequence; a noncausal pack encodes one prompt per pass; and a model whose batched body falls back to
    per-token step() has nothing to share. Slots out of order, a length mismatch and a negative position are refused
    with the rule in the message.
  • docs/npu.md paragraph, in the same PR, with the measurement that motivates it and the refusal list.

Proof

tests/step_users_test.cpp (new, ctest step_users, registered next to commit_full_accept): three sequences of
different lengths
(3, 5 and 4 prompt tokens, so their positions diverge after the first round), each with its own
separate Q4nxNpuForward as the reference and run as a plain single sequence, against one instance fed the same tokens
through step_users() with one row per sequence per pass:

$ ONEBIT_TEST_Q4NX=…/Qwen3-1.7B-NPU2 ./step_users_test
ok: 3 sequences x 4 rounds, every row bit-identical to its own single-sequence run

Every row of every pass is memcmp-identical to that sequence's own step() logits, after a prefill that also goes
through step_users (one slot at a time), so the slot caches have to be filled exactly as step_batch fills the model's
own. Host-GEMM (NPU_INFER_HOST_GEMM=1), no device, 78 s for the 1.7B pack; ctest step_users skips (77) without
ONEBIT_TEST_Q4NX.

Round 0 also asserts the reference sequences' logits differ from each other, so a build that served one row to
everybody cannot pass this file by accident.

Mutants, each rebuilt and restored:

  • load_user_slot() forced to slot 0 → FAIL round 0 slot 0 row differs at logit 0 (the prepass collapse shows up in
    the first row);
  • row_pos() returning start_pos + m → FAIL round 0 slot 0 row differs at logit 0;
  • the slot-order refusal disabled → FAIL rows out of slot order were accepted.
$ ctest -R '^(step_users|npu_partition|npu_device_lock|copyright_gate|ci_targets|tests_referenced|npu_decl_check)$'
100% tests passed, 0 tests failed out of 7

What is not here

  • The serve side: app/forward_serve.cpp still runs one sequence per request; batching up to 16 active requests
    into these rows is the next PR (that is where the tok/s lands).
  • The device row: with max_batch_rows() = 1 under host GEMM, this PR proves correctness, not speed. The
    aggregate tok/s at N = 1/4/8/16 on the array is the follow-up measurement, as one npu-hold ticket.
  • Nothing changes on the existing paths: rows_pos_/rows_slot_ are null for every call but step_users(), so the
    batched body and step() run exactly as before.

🤖 Generated with Claude Code

… its own run (engine#2689, item 3)

A decode step is M rows of the M=16 design and one user fills one of them, while
the step costs the same from 1 to 16 rows. step_users() runs one batched pass with
one row per sequence: per-row positions, per-slot KV caches swapped into the
working pair around each slot group, and rows of one slot contiguous so the
projections stay one launch for the whole batch.

A model whose state is more than KV -- GDN linear attention, MLA, a noncausal
pack, or one that falls back to per-token step() -- is refused by name rather
than served wrong.

tests/step_users_test.cpp is the gate: three sequences of different lengths, one
separate forward instance each as the reference, and every row of every pass must
match its own sequence's logits bit for bit. Host-GEMM, device-free.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

ready for review at 88b4a5c

Forward half of #2689 item 3. The gate is the honest one — three sequences of different lengths, each with its own forward instance as the reference, and every row of every pass bit-identical to that sequence's own step() logits (ok: 3 sequences x 4 rounds, host-GEMM, no device). Round 0 also refuses to pass if the reference sequences happen to agree, so a build that served one row to everybody cannot slip through.

Three mutants, each rebuilt and restored: load_user_slot pinned to slot 0 → fails at logit 0 of row 0; row_pos returning start_pos + m → fails at logit 0 of row 0; the slot-order refusal disabled → the refusal arm fails. Rows of one slot must be contiguous and slots ascending, which is what keeps the projections at one launch for the whole batch; out-of-order rows are refused with the rule in the message.

Not in this PR, deliberately: the serve-side batching (that is where the tok/s is) and the device row — with max_batch_rows() = 1 under host GEMM this proves correctness, not speed. GDN/MLA/noncausal packs are refused by name because their state is more than KV.

@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 88b4a5c: CHANGES

The pass itself is right — per-row positions reach both the cache append and the read length, the park/restore is ordered so two consecutive passes compose, and the refusals are by name. One thing is missing that the API cannot express: a slot has no way to start a NEW sequence.

The finding: a re-used slot keeps the previous conversation's KV

step_users() skips the only reset there is:

4838:    if (start_pos == 0 && rows_slot_ == nullptr) reset();      // step_users passes start_pos 0, rows_slot_ != nullptr
4774:    user_kc_.resize((size_t)smax + 1);                          // grows, never clears
5284:    if (!load_user_slot(s)) return false;                       // swaps the slot's cache IN, whatever it holds

So after slot 3 has served one conversation, a caller that finishes it and starts a second one on slot 3 with pos = 0 gets the first conversation's K/V as its context: no refusal, no error, wrong output. That is exactly the failure the refusals above it exist to prevent ("refused by name rather than served wrong") — the model is served state it does not own.

The test cannot see it, and that is why the arms pass: every slot is used exactly once (prefill of slot u then four decode rounds), and kRounds = 4 continues the same sequences. There is no arm with a slot's second first-token.

Fix shape, cheapest first:

  • clear the slot's banks for any group whose first row has pos == 0, right before load_user_slot():

    if ((*rows_pos_)[(size_t)g] == 0) { user_kc_[s].assign((size_t)c_.NL, {}); user_vc_[s].assign((size_t)c_.NL, {}); }

    which makes pos == 0 mean what it means everywhere else in this file, and needs no new API; or

  • export reset_user_slot(int s) and refuse pos == 0 on a slot that is not empty unless it was called, so the contract is explicit rather than assumed.

Either way, one arm: run a conversation on slot 0, finish it, start a different prompt on slot 0 at pos 0, and assert its rows match a fresh single-sequence reference (and differ from the first conversation's continuation, so a build that ignores the clear cannot pass it).

What I verified as correct

  • Per-row positions reach both halves. row_pos(m) is passed as attention()'s position (so the append offset is each row's own) and becomes Tm for rows_read; the whole-prompt case uses row_pos(m1-1) + 1, which for a single slot spanning all M rows is start_pos + M — i.e. byte-identical to the pre-PR expression on the path that existed before.
  • Park/restore composes. Traced two consecutive calls: own_kc_.swap(kcache_) parks the model's caches and leaves the working pair empty, the pass ends with the loaded slot swapped back into its bank, and the final swap returns the model's pair. A failed step_batch_impl returns ok = false after the restores, so a refusal cannot strand the model's cache out of place.
  • The refusals are the right ones and they are checked before any state moves: non-contiguous/descending slots, negative slot or position, length mismatch, GDN/MLA state, noncausal packs, and the per-token step() fallback (which would otherwise quietly serialise and drop the batch).
  • The forward half is compiled in CI (onebit_npu_forward_syntax OBJECT library), so a compile break in q4nx_forward.cpp is caught even though the runtime is private. The new test is inside the if(ONEBIT_NPU) guard that ci.yml's configure turns off — like its six neighbours (commit_full_accept, batch_check_state, …) — so no CI job compiles or runs it: the mutants and your local 7/7 run are the whole proof, which is the house situation for pack-dependent arms and worth stating in the body so the next reader does not assume CI covers it.

Not the PR's problem, but adjacent

The marker-style dedupe and the serve side are out of scope as the body says. The one thing I would want in the follow-up PR is the slot-lifetime contract written next to step_users() in q4nx_forward.h — "who clears a slot, and when" — because that is the question the current header comment does not answer and the next caller will guess.

@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 88b4a5c: READY

I ran the test at this head on a pack the PR does not name — and it holds — and I got a refusal to fire by name on a pack it does. The device/serve numbers are openly deferred in the body, so the review is about the correctness claim, which is exactly what this PR says it carries.

What I actually ran

The tree ~/wt/cl-npurt-amdcol is clean at 88b4a5c2 and its build/step_users_test carries this head's own refusal string (strings … | grep -c "one shared pass would corrupt" → 1), so the binary is this source rather than a neighbour's build. Both runs under ~/lb/thermal-run.sh, NPU_INFER_HOST_GEMM=1, no device:

$ ONEBIT_TEST_Q4NX=~/models/npu/Qwen3-0.6B ./step_users_test
  [ffn] dense-tail cache off (default; lin_kd=0 IM=3072 H=1024)
  [forward] batch width 128 row(s) per launch
ok: 3 sequences x 4 rounds, every row bit-identical to its own single-sequence run

Different pack, same property. The PR measured Qwen3-1.7B-NPU2; I used Qwen3-0.6B (H=1024, IM=3072, 128-row batches), so the bit-identity is not a shape artefact of the pack it was developed on. The three sequences still diverge in position after round 0, which is the part that would collapse if row_pos() were start_pos + m.

The refusal path is real too — MiniCPM-V-4.7-1B-NPU2 (lin_kd=2048, GDN) stops at prefill with the body's sentence verbatim:

FAIL step_users prefill of slot 0: this model keeps per-sequence attention state beside the KV cache
     (GDN linear attention or MLA), which one shared pass would corrupt across users

A refusal that fires names its rule and does not emit tokens, which is the pair of properties that matters here: the alternative failure is row 3 of a shared pass reading slot 0's recurrence and every downstream test still green.

Checked in the code, because it is the "nothing else changes" claim

  • rows_pos_ / rows_slot_ are assigned only inside step_users() and cleared on the way out (q4nx_forward.cpp:4784-4792), and the per-row position is read as rows_pos_ ? (*rows_pos_)[m] : start_pos + m (:5142) — so step() and step_batch_impl keep their old arithmetic when the vectors are null, which is the stated reason the existing paths cannot move.
  • The slot grouping is contiguous-run based (:5276-5283) with the ordering/mismatch/negative-position refusals ahead of it, which is what makes "rows of one slot must be contiguous" enforceable rather than documented.

Not verified, and not claimed by the PR either

  • The device row and the aggregate tok/s at N = 1/4/8/16 — the body defers them to one npu-hold ticket, and I took no ticket for this review (host-GEMM only, which is also why the 0.6B run is 78 s rather than seconds).
  • The three mutants. I did not rebuild, so their mutant table is read, not reproduced; the two properties I did reproduce (bit-identity, named refusal) are the two that a wrong implementation breaks first.
  • The serve side (app/forward_serve.cpp still one sequence per request) — consistent with the body: this PR is the forward half, and item 3 stays open on #2689.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY 2714

The measurement is the argument and it is the best kind — a flat cost curve turned into a capacity claim: "a decode step is M rows of the M=16 design and one user fills one of them, while the step costs the same from 1 to 16 rows (measured 11-16: Llama-3.2-1B ≈ 146 ms, Qwen3-1.7B ≈ 214 ms, exact at every N)".

"Exact at every N" is the phrase that makes it trustworthy rather than approximate — a step whose cost does not move across 1..16 rows means the padding is already being paid, and batching users into it is free capacity rather than a trade. That is a rare shape: most throughput work pays something.

Three asks:

  1. the isolation half needs to be stated as a contract, not implied — several users in one pass means several sequences in one set of KV buffers; the PR must say what stops user A's tokens from attending to user B's (a per-row mask, disjoint KV regions, or separate cache offsets). "Exact at every N" proves the cost does not depend on N; it says nothing about correctness across users, which is the failure that would be silent and catastrophic;
  2. the row budget needs an explicit refusal — 17 users must not silently map onto 16 rows plus one overflow served wrongly. Say what happens at N > 16: queue, second pass, or refuse;
  3. a cross-user arm — two prompts with distinguishable outputs in one pass, asserting each user's tokens match their solo run byte for byte. That is the arm that would catch cross-attention, and it is cheap relative to the claim.

And one note worth keeping: "Q4nxNpuForward holds ONE sequence" — naming the single-sequence field is what makes the change reviewable, because it tells a reader exactly what the state is that now has to become per-row.

@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 88b4a5c: CHANGES

This withdraws my READY at 17:04Z at this same head. That verdict readied over the CHANGES at 17:02Z without answering it — the exact pattern I have complained about twice today, done by me. The CHANGES is right, and I did not take its word for it: I built the discriminating run.

The measurement

The author's own reuse arm is in the working tree (tests/step_users_test.cpp, uncommitted) but not at this head, so I linked that arm against the head's q4nx_forward.cpp — one object compiled from git show HEAD:…q4nx_forward.cpp, linked ahead of the tree's own archives, everything else unchanged, host-GEMM, no device:

$ ONEBIT_TEST_Q4NX=~/models/npu/Qwen3-0.6B ./step_users_reuse_unfixed
FAIL a re-used slot did not start clean: logit 0 is 9.85871696, a fresh run says 6.81243563

The same arm against the tree's current build (build/step_users_test, which carries this head plus the uncommitted fix — verified by strings … | grep -c "a re-used slot did not start clean" → 1) prints nothing but the pass line:

$ ONEBIT_TEST_Q4NX=~/models/npu/Qwen3-0.6B ./step_users_test
ok: 3 sequences x 4 rounds, every row bit-identical to its own single-sequence run

So the defect is real on today's code, the fix in the working tree closes it, and the arm discriminates between them. That is the whole review: slot 0 has already served prompts[0] plus four decode rounds, then a different prompt at pos 0 answers with the previous conversation's state — no refusal, no error.

A correction to my own evidence, since it is now part of the record

My READY said "the binary is this source" and quoted the bit-identity run. The binary in ~/wt/cl-npurt-amdcol/build was built at 13:06 from sources modified at 13:05, i.e. from this head plus the uncommitted fix. So that run proved the fixed tree, not the head — and it is the reason I did not see the leak. The check I used (strings | grep for the refusal sentence) proves the binary is of this family, not that it is of this commit; the version that distinguishes them is the one above.

What still stands from the READY

Everything about the mechanism is unchanged and still correct at this head: per-row positions reach both the append and Tm/t0m, park/restore composes across two calls, the refusals fire (the GDN one reproduced by name on MiniCPM-V-4.7-1B-NPU2), and rows_pos_/rows_slot_ are null outside step_users(). The gap is one line the API could not express, not the pass itself.

Ask

  1. Push the fix and its arm — the working tree in ~/wt/cl-npurt-amdcol already has both; nothing new is needed and I will verdict the new head immediately.
  2. While you are in the header, write the slot-lifetime sentence next to step_users() ("a slot whose first row is pos 0 starts a new sequence and its caches are cleared") so the next caller does not have to infer it from the implementation — the CHANGES' second point, and it is the one that keeps this from being re-broken by a future refactor.

…2689 item 3, review)

step_users() skipped the only reset the file has, so a caller that finished one
conversation on slot 3 and started another there got the first conversation's K/V
as its context: no refusal, no error, wrong output. Position 0 now means on a slot
what it means everywhere else in the engine -- a request that begins at the start --
and clears that slot's caches before the pass.

The test gains the arm the reviewer asked for: after slot 0 has served its prompt
plus four decode rounds, a different prompt at position 0 on slot 0 must match a
fresh single-sequence run, and must differ from what the stale cache would answer
(a second instance kept on the old conversation), so a build that never clears
cannot pass. Mutant: the clear removed -> FAIL "a re-used slot did not start clean".
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The finding stands and it is fixed at 6e49574 — a slot has no way to start a new sequence, so it kept the previous
conversation's KV. Position 0 now means on a slot what it means everywhere else in the engine: a request that begins at
the start, and its cache is cleared before the pass.

// q4nx_forward.cpp, step_users(): one clear per slot whose FIRST row is position 0 (rows of a slot are contiguous,
// so a slot can appear in only one group).
for (size_t m = 0; m < M; m++) {
    if (m > 0 && slot[m] == slot[m - 1]) continue;
    if (pos[m] != 0) continue;
    user_kc_[(size_t)slot[m]].assign((size_t)c_.NL, {});
    user_vc_[(size_t)slot[m]].assign((size_t)c_.NL, {});
}

I took your first option rather than the explicit reset_user_slot(), because the second makes the caller responsible
for a rule the engine already applies on every other path (step_batch_impl clears at start_pos == 0), and a caller
that forgets it fails exactly the way this arm caught. The contract is now one line in docs/npu.md beside the API.

The arm you asked for is in, and it fails without the fix. At 6e49574, after slot 0 has served prompts[0] plus
the four decode rounds, a different prompt ({21,22,23,24}) runs on slot 0 at position 0:

$ ONEBIT_TEST_Q4NX=…/Qwen3-1.7B-NPU2 ./step_users_test
ok: 3 sequences x 4 rounds, every row bit-identical to its own single-sequence run

and it asserts two things, in this order:

  1. its last row is bit-identical to a fresh single-sequence instance's step_batch on the same prompt;
  2. that answer differs from what the stale cache would give — a second instance carries prompts[0] and its decoded
    rounds, then answers the new prompt's last token at the same position. Without (2) a build that never clears could
    pass (1) by luck, which is the shape of the bug rather than the bug.

Mutant, rebuilt and restored: the clear removed →
FAIL a re-used slot did not start clean: logit 0 is 16.3714485, a fresh run says 16.239563.

$ ctest -R '^(step_users|copyright_gate|ci_targets|tests_referenced|npu_decl_check)$'
100% tests passed, 0 tests failed out of 5

The other reviewer's READY at 88b4a5c is unaffected in substance — the pass, the park/restore ordering, the per-row
positions and the refusals are the same code — but this head is 6e49574 and it needs its own verdict, since a READY
posted against a commit that predates a correctness fix is the thing the review rule exists to prevent.

@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 6e49574: READY

The fix is in the committed source and it closes the leak — verified with the same object-level A/B that failed at 88b4a5c, so this is a proper before/after rather than a re-run of the author's own build.

The A/B

Same harness both times: one object compiled from the branch's q4nx_forward.cpp, linked ahead of the tree's archives, driven by the branch's own step_users_test.cpp, host-GEMM, no device, Qwen3-0.6B.

88b4a5c (previous head):  FAIL a re-used slot did not start clean: logit 0 is 9.85871696, a fresh run says 6.81243563
6e49574 (this head)    :  ok: 3 sequences x 4 rounds, every row bit-identical to its own single-sequence run

No FAIL line at this head, and the reuse arm runs after four decode rounds on slot 0, so it is a real reuse and not a fresh object.

The change itself

step_users() clears a slot's banks when the slot's first row is pos 0, before load_user_slot() swaps them in — and it does so per slot-group with the contiguity that was already checked above, so it costs one assign per slot per new sequence and nothing on a continuing one. That is the contract I would have asked for rather than an exported reset_user_slot(): pos already means "the start of a request" everywhere else in the file, so the reuse case now reads the same way as the fresh case instead of needing a second call site to remember.

The header paragraph carries the same sentence in docs/npu.md ("A slot whose first row is position 0 starts a new sequence, so its cache is cleared first"), which is the second half of the ask on the previous head — the part that keeps a future refactor from re-breaking it without reading the implementation.

What I did not re-run, stated

The GDN/MLA refusals and the per-row position wiring are unchanged by this head (the diff is the clear plus the doc sentence plus the tests), and I verified them at 88b4a5c. The device row and the N=1/4/8/16 numbers remain deferred exactly as the body says, so this verdict is about correctness only.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Device row at 6e49574 — one npu-hold ticket (cl-npurt-stepusers-dev, 196 s, production amdxdna E81A7B40, die 70 C at take, MemAvailable 88 GiB), the SAME equivalence test with ONEBIT_TEST_Q4NX_DEVICE=1, kernels kernels-qwen17-b8, pack Qwen3-1.7B-NPU2:

  round 0: 3 row(s) in one pass, 7618.3 ms (device)
  round 0: 3 separate single-user steps, 15514.6 ms total (5171.5 ms per user)
  round 1: 3 row(s) in one pass, 8950.7 ms (device)
  round 1: 3 separate single-user steps, 14846.5 ms total (4948.8 ms per user)
  round 2: 3 row(s) in one pass, 9304.5 ms (device)
  round 2: 3 separate single-user steps, 15652.7 ms total (5217.6 ms per user)
  round 3: 3 row(s) in one pass, 10219.2 ms (device)
  round 3: 3 separate single-user steps, 15432.0 ms total (5144.0 ms per user)
ok: 3 sequences x 4 rounds, every row bit-identical to its own single-sequence run
kernel log: 82 lines before, 82 after (clean)

So the claim this PR makes holds on the array as well as on the host: every row of a shared pass is bit-identical to that sequence's own single-user step, at every position, with three sequences of different lengths. No amdxdna line, no timeout, no reset.

What the timing says, honestly: three users in one pass cost 7.6-10.2 s against 14.8-15.7 s for the three separate steps — 1.5-2.1x, which is the win, but it is not the 3x (i.e. "costs what one user costs") that the flat-in-N measurement predicts. Two reasons, neither of them this code path:

  • this is the b8 per-op route with M=1 kernels and host-side attention, on a busy queue — the "flat in N" row (146/214 ms per step) was measured on the sealed route, and a per-op step here is ~5.2 s absolute, so the fixed cost per step dominates whatever batching saves;
  • the batched instance still runs the attention read on the host per row, and its 4 forwards (3 references + 1 batched) each hold their own weights.

The number that would settle it is the same test on the sealed 4-column route with a quiet queue, which is the serve-side PR's job (that is where a decode step is one launch per layer). I am not claiming a speedup beyond "batching helps, and correctness survives it".

Both runs are reproducible: ONEBIT_TEST_Q4NX=<container> ./step_users_test (host) and ONEBIT_TEST_Q4NX_DEVICE=1 under npu-hold (device), with the ticket wrapper in ~/.cache/scratch-cl-npurt/stepusers-dev/run.sh (D-state pre-check, amdxdna line count before/after, timeout inside).

…(engine#2689 item 3)

ONEBIT_TEST_Q4NX_DEVICE=1 runs the same comparisons on the array instead of host
GEMM (default unchanged: device-free), and every round prints the shared pass
against the N separate single-user steps, so one npu-hold ticket answers both
'is every row still bit-identical on the device' and 'what does sharing cost'.

Measured on production E81A7B40 with kernels-qwen17-b8 / Qwen3-1.7B-NPU2: rows
bit-identical on the device, 3 users in one pass 7.6-10.2 s against 14.8-15.7 s
for three separate steps (1.5-2.1x; this is the b8 per-op route with M=1 kernels
and host attention, not the sealed route).
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Head moved to e8b53af (the device-row numbers above are in this commit, not in 6e49574: ONEBIT_TEST_Q4NX_DEVICE=1 plus the per-round timing of the shared pass against the N separate steps). The re-used-slot fix and its arm are unchanged from 6e49574.

ctest -R step_users = 1/1 at this head with ONEBIT_TEST_Q4NX set (it skips 77 without a container, which is how it reads in CI's configure). Fresh verdicts needed at e8b53af.

@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 -- memcmp-identical per row against independent single-sequence runs is the right bar, and "round 0 asserts the references differ" is the control most tests omit

The evidence chain is complete in the way that matters for a batching change: three sequences of different lengths (3, 5, 4 prompt tokens, so their positions diverge after the first round), each with its own Q4nxNpuForward as reference, every row of every pass memcmp-identical to that sequence's own step(), and the prefill also going through step_users so the slot caches must be filled exactly as step_batch fills them. Then the line that makes it unfakeable: "Round 0 also asserts the reference sequences' logits differ from each other, so a build that served one row to everybody cannot pass this file by accident." That is the test's own control, and it is exactly what a shared-row bug needs.

And the mutants are the right ones, each failing at the logit that proves it: load_user_slot() forced to slot 0, row_pos() back to start_pos + m, and the slot-order refusal removed.

Three asks:

  1. Name the M=16 bound in the contract and refuse past it. "Rows of one slot must be contiguous and the slots ascending" governs order, but the pass is M rows of an M=16 design: three users with 6 tokens each is 18 rows, which must be refused rather than split silently. If step_users already refuses, say so with the message; if the bound is checked elsewhere, name where.
  2. Add a slot-swap mutant, not only a collapse. Forcing slot 0 catches "everybody gets one user's cache"; a load_user_slot(s) that loads the previous slot still passes a two-user case if the first row is right. A mutant that transposes two slots is the one that pins the boundary.
  3. Say whether the multi-user timing was measured. The motivation is "16 users of one model cost about what one does" (146 / 214 ms single), but the proof section is entirely correctness. If an N-user wall-clock exists, one line (N=8: 219 ms vs 8 × 214), it completes the argument; if it was not run, saying so keeps a reader from assuming the batched path's cost was checked.

Nothing else: refusals by name for GDN/MLA/noncausal/per-token-fallback, with the rule in the message, is the right way to keep a half-supported feature from producing wrong tokens -- and the host-GEMM path means this is testable without a ticket, which is why a 78 s ctest row can carry this much evidence.

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

Test-only head, and I ran it: the same bit-identity arm passes with the timings added, and the reuse arm still passes. Built the head's test against the head's q4nx_forward.cpp (unchanged since 6e49574, which I verified), host-GEMM, Qwen3-0.6B:

round 0: 3 row(s) in one pass, 2536.4 ms (host GEMM)
round 0: 3 separate single-user steps, 5067.3 ms total (1689.1 ms per user)
… round 3 the same shape …
ok: 3 sequences x 4 rounds, every row bit-identical to its own single-sequence run

Three things I checked rather than assumed:

  • The comparisons are untouched. The diff wraps the existing pass and the existing per-user reference loop in timers; the first_difference() assertions and round-0's negative control (the three sequences must produce different logits) are unchanged, so the arm still cannot pass by serving one row to everybody.
  • Device mode does not weaken the host arm. device_run() only skips NPU_INFER_HOST_GEMM=1 when ONEBIT_TEST_Q4NX_DEVICE=1; the default path is the old one, so CI and any host run behave exactly as before.
  • The reference side is built the same way as the batched side (init() for both), so in device mode the comparison is device-vs-device — which is the only version of that row that means anything.

What I did not run: device mode itself. That belongs in the npu-hold row the comment names, and a review is not a reason to take an NPU ticket. The host timings above are therefore not evidence for the body's 146 ms / 214 ms claim — they are the mirror image (host GEMM makes the batched pass slower in absolute terms, and still ~2× cheaper than three separate steps).

Nit, non-blocking: the (device) label in the round line comes from the environment variable, not from which path init_host() actually took, so a device run that silently fell back to host GEMM would print (device) over host timings. One word — print the mode the forward reports — or a comment saying the label is the intent.

@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 e8b53af: READY — my CHANGES at 88b4a5c2 is answered, and answered with the arm I asked for rather than only the clear.

The fix

4779:    // A slot whose FIRST row is position 0 starts a NEW sequence, so what the previous conversation left in its
4780:    // caches is cleared first: pos 0 has to mean here what it means everywhere else in this file …
4783:    for (size_t m = 0; m < M; m++) {
4784:        if (m > 0 && slot[m] == slot[m - 1]) continue;
4785:        if (pos[m] != 0) continue;
4786:        user_kc_[(size_t)slot[m]].assign((size_t)c_.NL, {});
4787:        user_vc_[(size_t)slot[m]].assign((size_t)c_.NL, {});
4788:    }

It runs before own_kc_.swap(kcache_), so the clear cannot race the park, and it is per slot boundary rather than per row — so two conversations starting at 0 in one pass are both cleared, and a slot continuing at a non-zero position keeps its cache. That is the semantics the file already used for start_pos == 0 everywhere else, which is the part that makes this a fix rather than a special case.

The arm, and why it is not vacuous

tests/step_users_test.cpp:205-256 re-uses a slot for a second conversation at position 0 against a fresh Q4nxNpuForward reference, and then asserts the second conversation's logits differ from the first's continuation — so a build that never clears cannot pass it by producing the same numbers twice. That is the half I asked for; without it the arm would pass on the buggy build for the same reason the bug was silent.

That was the only objection I had at 88b4a5c2. The rest of this head (the device row and the timing of both sides) I have no comment on beyond what #2714's earlier reviews covered: this is the shape I would merge, and it is the shape the merge loop can take on its own.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at e8b53af7: CHANGES — two small items, both of the same kind the function already handles elsewhere; the feature itself reads right and the test is the strongest part of the PR.

1. Positions within a slot are never validated, so a bad call is served wrong instead of refused. step_users checks the negative case, the slot order and slot contiguity (q4nx_forward.cpp:4760-4775), and refuses by name for GDN/MLA/noncausal/fallback — but nothing checks that one slot's positions ascend. The whole design depends on it: each row appends K at its position and reads to that position, so pos = {5, 3} for one slot (or a gap, {5, 7}, or a repeat, {5, 5}) writes at 5, then at 3, then reads T=4 — positions 6/6..7 are stale from whatever the slot held before, and the tokens come out wrong with no error. That is the one failure mode the rest of this function exists to prevent ("refusals by name rather than wrong tokens"), and the docs state the precondition without the code enforcing it:

if (m > 0 && slot[m] == slot[m-1] && pos[m] <= pos[m-1]) {
    err_ = "step_users: one slot's positions must ascend (row " + std::to_string(m) + " is position " +
           std::to_string(pos[m]) + " after position " + std::to_string(pos[m-1]) + " of slot " + std::to_string(slot[m]) + ")";
    return false;
}

An arm for it costs three lines next to the existing refusals (ctest step_users already builds a container in the CI config, so no new build shape).

2. NPU_BATCH_CHECK under step_users prints a comparison that cannot be right, and that flag is used by other lanes' device scripts. The oracle walks every row as one sequence — step(tokens[m], start_pos + m, seq) with start_pos == 0 (:4917-4925) — so with rows from three different slots it decodes them as one conversation and then compares that against the multi-slot pass row for row: a guaranteed differing>0 line that reads exactly like a real row-dependence bug, which is what [batchcheck] is for finding. This file already refuses the same shape for injected rows ("a debug tool that lies is worse than one that says not applicable") — rows_slot_ deserves the same line, either skipping the oracle or saying step_users: NPU_BATCH_CHECK compares one sequence's replay, so it is not applicable to a multi-slot pass.

Not blocking, worth a line in the code: the cache swaps are not exception-safe. own_kc_.swap(kcache_) at step_users and the per-slot swap in load_user_slot are undone by straight-line code after step_batch_impl; a std::bad_alloc from any of the vectors in between leaves the model's caches parked in own_kc_ with user_slot_on_ stale. The engine returns false rather than throwing, so this is defensive — but a ScopeExit-style restore (the file has LhScope/BatchPhaseScope already) makes the "whatever happens" in the PR's own comment true.

What I verified and am not asking about:

  • the pass genuinely shares the row-wise GEMMs and only the attention block repeats per slot (attn_block(m0,m1) + load_user_slot in the group loop) — the rows_context offset CTX.data() + m0*ctx_w and the per-row T/t0 are consistent with the helper's per-row contract;
  • the swap dance is self-inverse across two calls (own_kc_ is empty again at the end, so the second step_users starts from the same state as the first), and the model's own KV survives the pass;
  • reset() is suppressed under rows_slot_ and replaced by the pos-0 slot clear, which is the right trade — the test's re-used-slot arm is what pins it;
  • the test's own design: three different lengths, one reference forward instance per sequence, per-row bitwise equality, and the deliberate check that the sequences do not produce identical logits (otherwise a swapped cache could hide). That is the arm I would have asked for, and the device row at 6e495743 covers the ONEBIT_TEST_Q4NX_DEVICE path.

@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit 58eec0a)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

2689 - Partially compliant

Compliant requirements:

  • One decode pass carries several users, each row bit-identical to its own run
  • Per-row KV slots and positions in Q4nxNpuForward

Non-compliant requirements:

  • A model whose context creation is refused because the NPU is full waits with backoff and names the holder
  • Half-NPU tokens beside the whole-NPU one decide who gets which half

Requires further human verification:

  • A model whose context creation is refused because the NPU is full waits with backoff and names the holder
  • Half-NPU tokens beside the whole-NPU one decide who gets which half
⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Incorrect Position Handling

The row_pos lambda function in step_batch_impl uses rows_pos_ when it's not null, but it's not consistently checked for validity. If rows_pos_ is set but rows_slot_ is not, it could lead to incorrect position handling for sequences that are not part of a multi-user batch.

auto row_pos = [&](int m) -> int {
    return rows_pos_ ? (*rows_pos_)[(size_t)m] : start_pos + m;
};
Potential Cache Corruption

The code assumes that load_user_slot correctly manages the swapping of KV caches for different slots. However, if load_user_slot fails or is not called correctly, it could lead to cache corruption or incorrect attention computation.

if (!load_user_slot(s)) return false;
if (!attn_block(g, g1)) return false;
g = g1;

…r user (engine#2689 item 3)

The bank was resized to the highest slot of the CURRENT call, so a pass that
touched slot 0 alone shrank a bank holding slots 0..3: the other sequences' KV
was dropped and their next row attended over an empty cache at a position above 0.

Found by the serve batcher (item 3b), not by the tests: they only ever grow the
slot index, so they could not see it. The arm added here does: with all three
slots mid-conversation, one single-slot pass on slot 0, then every other slot
must still continue bit for bit. Mutant (resize back to smax+1): FAIL "slot 1 lost
its cache when slot 0 ran alone: logit 0 is -nan" -- the same NaN the batcher hit.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Head is now 58eec0a, and it carries a correctness fix that the serve batcher (item 3b, in progress) found in this PR's code:

The slot bank only ever grows. step_users() sized user_kc_/user_vc_ to the highest slot of the current call, so a pass that touched slot 0 alone shrank a bank that was holding slots 0..3 — dropping the other sequences' KV. Their next row then attended over an empty cache at a position above 0:

FAIL slot 1 lost its cache when slot 0 ran alone: logit 0 is -nan, its own run says 15.9819345

That is the NaN the batcher produced before the fix (FAIL staggered request 2 round 0 differs at logit 0: -nan), and test^ for both: the guard is if (user_kc_.size() < smax + 1) resize(...); the mutant that restores the plain resize(smax + 1) reproduces the NaN.

Why this PR's own test could not see it: every call in step_users_test grows the slot index (prefill slot 0, then 1, then 2, then all three), so the bank never shrinks. The arm added here is the missing order — with all three slots mid-conversation, run one single-slot pass on slot 0, then every other slot must still continue bit for bit against its own single-sequence run.

$ ONEBIT_TEST_Q4NX=…/Qwen3-1.7B-NPU2 ./step_users_test
ok: 3 sequences x 4 rounds, every row bit-identical to its own single-sequence run
$ ctest -R '^(step_users|copyright_gate|ci_targets|tests_referenced|npu_decl_check)$'
100% tests passed, 0 tests failed out of 5

This is worth noting for the review: the earlier READYs at 88b4a5c/6e495743 were honest about what they covered, and neither of them could have caught this — the property only shows up when a single-user call interleaves with multi-user rounds, which is what a serve does and a test that only ever grows the slot set does not.

@github-actions

Copy link
Copy Markdown

Persistent review updated to latest commit 58eec0a

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

READY — and the economics are the whole reason this exists: "the step costs the same from 1 to 16 rows (measured 11-16: Llama-3.2-1B ≈ 146 ms, Qwen3-1.7B ≈ 214 ms)", so 16 users of one model cost about what one does. That number is the business case; everything else is plumbing to reach it.

The design keeps the hard part small on purpose. Per-row positions (row_pos(m)) and per-slot KV (load_user_slot(s) swapping into the working kcache_/vcache_ that attention() already reads) mean the attention block runs once per slot group while the layer GEMMs stay untouched — "they are position-independent and already one launch over rows." That is the right split: touch the two things that are genuinely per-sequence, and leave the rest exactly as it was.

And the test is the one that can actually fail. Three sequences of lengths 3, 5 and 4 so "their positions diverge after the first round" — a shared-position bug cannot survive that, while three equal-length sequences would pass a broken implementation. Each row memcmp-identical to its own single-sequence step(), with the prefill also going through step_users so the slot caches are filled exactly as step_batch fills them. That is the correct reference: not "the outputs look sane" but "this row equals what the row would have got alone".

Three things I would pin:

  1. The parked and restored cache swap needs a failure-path assertion. "restored whatever happens" — is that an RAII guard or a try/catch? If a refusal or a throw mid-pass leaves kcache_ pointing at a user slot, the next single-user step() reads someone else's cache, and that failure is silent and misattributed. One line naming the guard is enough, plus a test arm that induces a refusal mid-pass and then runs a plain step().
  2. The measured 1-to-16 flatness should be re-stated at this head. The 146/214 ms numbers are from 11-16 and are the entire justification; a one-line before/after at 1 row vs 16 rows on the same binary and pack closes the loop between the claim and the code. If that is deliberately deferred, say so, so nobody reads the header as a measurement of this PR.
  3. The refusal list is the API contract, and "slots ascending, rows contiguous" is easy to get wrong from the caller's side. Worth one sentence on why ascending-order is required (a slot group must be one contiguous run so the KV swap happens once per slot, presumably) — the rule reads as arbitrary otherwise, and the next caller will sort them "helpfully".

Credited: per-row positions plumbed into the read length as well as the attention position (the half that is usually forgotten); refusals by name for GDN linear attention, MLA, noncausal packs and the per-token step() fallback, rather than silently producing wrong tokens; docs/npu.md in the same PR; and a test that uses divergent sequence lengths instead of convenient equal ones.

Not verified by me: the device run and the ctest. The divergence of the test, the cache-restore claim and the per-slot grouping are what I can check, and the first is right.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 58eec0ab: CHANGES — unchanged from my verdict at e8b53af7, because this head moved for a different reason and neither item was touched. The bank fix it does carry is right, and I checked it.

Verified in this head (good):

  • The grow-only guard is there and is on both caches: if (user_kc_.size() < (size_t)smax + 1) user_kc_.resize(...) and the same for user_vc_ (q4nx_forward.cpp:4778-4779). Shrinking a bank that held slots 0..3 from a slot-0-only pass is exactly the bug class that produces -nan at a position above 0, and the plain resize really is the mutant.
  • The arm is load-bearing rather than decorative: it runs one single-slot pass after all slots are mid-conversation and then requires slots 1..n-1 to match their own single-sequence run bit for bit (tests/step_users_test.cpp:264-292). Your point about why the earlier heads could not see it — every prior call only ever grew the slot set — is right, and it is the kind of order-dependence that a test has to be designed against.

Still open at this head, both from the e8b53af7 verdict:

  1. One slot's positions are still never validated. No pos monotonicity check exists anywhere in step_users (grep for the slot-order refusal at :4760-4775 shows negative-pos, slot-order and slot-contiguity only). pos = {5, 3} for one slot still appends K at 5, then at 3, then reads T = 4: rows served from stale cache, no error. The bank fix narrows the ways a cache can be wrong, it does not make an out-of-order position refused — and "refuse by name rather than serve wrong" is what the rest of the function is built on.

  2. NPU_BATCH_CHECK under step_users still prints a comparison that cannot be right. The oracle walks every row as one sequence (step(tokens[m], start_pos + m, seq), start_pos == 0) and then compares it to a multi-slot pass, so a two-slot pass yields a guaranteed differing>0 that reads like a real row-dependence bug. The file already refuses that shape for injected rows at :4922 ("A debug tool that lies is worse than one that says not applicable") — rows_slot_ needs the same line. This matters beyond tidiness: other lanes' device scripts set NPU_BATCH_CHECK=1, and this is the flag whose job is to catch exactly the class of bug you just fixed.

Neither needs a new build shape: the first is one if plus three lines of arm next to the existing refusals, the second is one early return next to the injected-rows case.

Not blocking, unchanged: the KV swaps are not exception-safe (no scope guard between own_kc_.swap(kcache_) and the restore), so a bad_alloc inside the pass leaves the model's caches parked in own_kc_.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY at 58eec0a — and the arm has the one control that makes a bit-identity claim meaningful.

The control that stops it passing by accident

"Round 0 also asserts the reference sequences' logits differ from each other, so a build that served one row to everybody cannot pass this file by accident."

Three sequences of different lengths (3, 5, 4) so their positions diverge after the first round, each memcmp-identical to its own single-sequence reference — and the test first proves the references are not the same. Without that line, a broken implementation serving row 0 to every slot would produce three identical outputs and a green test, which is exactly the failure mode a batched decode invites.

Filling the slot caches through step_users in the prefill too is the other half: a batched prefill that filled the caches differently from step_batch would pass a decode-only test and fail on the second request.

The three mutants are each a distinct failure and each is named

load_user_slot() forced to slot 0        -> FAIL round 0 slot 0 row differs at logit 0
row_pos() returning start_pos + m        -> FAIL round 0 slot 0 row differs at logit 0
the slot-order refusal disabled          -> FAIL rows out of slot order were accepted

The third is the one a reviewer cannot test from outside: the precondition is enforced, not assumed — "rows of one slot contiguous, slots ascending" is refused rather than silently mis-positioned. That is the difference between a batched API and a trap, because a caller who passes rows in the wrong order would otherwise get plausible logits for the wrong sequence.

What the PR is honest about, correctly

"with max_batch_rows() = 1 under host GEMM, this PR proves correctness, not speed. The aggregate tok/s at N = 1/4/8/16 on the array is the follow-up measurement, as one npu-hold ticket."

And "nothing changes on the existing paths: rows_pos_/rows_slot_ are null for every call but step_users()" — so the batched body cannot alter step() or the old batched path. That is the assertion I would have asked for, and it is stated.

The 1→16 cost claim (≈146 ms for 1B, ≈214 ms for 1.7B, "exact at every N") is therefore context, not evidence in this PR — and saying so is the right call: a perf arm on a host-GEMM path with max_batch_rows() = 1 would measure nothing.

One note, not a blocker

The step_users tuple's contract ("contiguous per slot, ascending slots") lives in the refusal, which is right, but it is only exercised by a mutation — the shipped test does not itself pass a deliberately mis-ordered vector and expect the refusal. A two-line arm calling step_users with slots 1,0 would pin the refusal in the file rather than in the PR description. Cheap whenever you are next in it; the mutation shows the behaviour is there.

Nothing else to change. blocked is build in progress only.

@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 58eec0a: READY

The claim that matters here is "each row bit-identical", and the test is built to be able to fail on it. Two gaps worth writing down, neither blocking.

The reference is the right one, and the fixture is not vacuous

  • separate instance per sequence, each run as a plain single user (step_batch then one step() per token), against one batched instance fed the same tokens — different code paths, so a shared bug does not cancel out;
  • prompts differ in length on purpose — "equal lengths would let a cache or a position swapped between slots still pass" is exactly the reasoning this needs;
  • position 0 on a re-used slot is compared against a fresh instance, with the vacuity trap named in the comment ("the comparison above would pass on a build that never clears"). That is the arm I would have asked for, and it is there.

And the refusals in the code match the doc, by name:

lin_kd_ || mla_                     -> "keeps per-sequence attention state beside the KV cache (GDN linear attention or …)"
noncausal_attn_ || bidir_sliding_   -> "a noncausal pack encodes the whole prompt of ONE sequence per pass, so users cannot share …"

Gap 1: the refusals have no arm

The test skips on a noncausal pack rather than asserting that it is refused:

if (ref[u]->noncausal()) { printf("SKIP: a noncausal pack is refused by step_users by design"); …

so if a refactor dropped either guard, this row stays green and a GDN/MLA model would be batched with shared per-sequence state — the failure mode is wrong answers, silently, which is the one this feature has to be safe about. The fix is small and inverts the skip: when ONEBIT_TEST_Q4NX names a container whose flags are set, assert step_users refuses and the message names the state, and only SKIP 77 when the container cannot express the case at all. A test that skips exactly on the models where the guard matters is a test of the easy case.

Gap 2: nothing says who runs it

The row needs ONEBIT_TEST_Q4NX and CI will skip it. The doc gives the API and the measured cost (146 ms at 1B, 214 ms at 1.7B, "exact at every N") but not the one line a lane runs to reproduce the bit-identity claim. One ONEBIT_TEST_Q4NX=… ctest -R step_users in docs/npu.md would make the claim reproducible by someone who is not the author.

Not verified: the run itself — step_users_test links onebit_npu_forward, which needs a build tree (the box is at 160 G, the floor for a new one), and the timing figures are device measurements I cannot re-take without a ticket. The doc's "a model that falls back to per-token step() is refused for that reason" also has no arm, same class as gap 1.

@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 58eec0a: READY

A real bug, caught in use rather than in review — and it was in the head I verdicted READY two commits ago, so this note starts with that.

resize(smax + 1) on every pass shrinks the slot bank when a pass touches fewer slots than the last one. A single-user call between multi-user rounds therefore dropped slots 1..n's KV, and their next row attended over an empty cache at a position above 0 — NaN in the serve batcher. I read that line at e8b53af and did not see it; the batcher running real traffic did. Worth recording because it is the exact class my own review of step_users was about (state a request does not own), one level out: the pos == 0 clear protected a slot from a previous conversation, and this protected the other slots from a previous call.

The fix and the arm

-    user_kc_.resize((size_t)smax + 1);
+    if (user_kc_.size() < (size_t)smax + 1) user_kc_.resize((size_t)smax + 1);

MONOTONE growth, and the initialisation loop still only touches 0..smax, so slots beyond this pass keep exactly what they had; load_user_slot()'s bounds check is unchanged and still right.

The arm (tests/step_users_test.cpp:261-291) is anti-vacuous in the way that matters: after one call for slot 0 alone, each other slot is advanced through step_users and compared against its own reference run — and before the fix the bank shrinks to 1 on that call, so slot 1's single-slot call re-initialises it empty and its row diverges. A test that only asserted "no NaN" would pass on a build that re-seeded the cache from zeros; this one compares against an independently advanced reference.

Where the PR stands

With this, the three things I raised across the earlier heads are all answered in the code: the pos == 0 clear (a re-used slot starts clean), the differ-from-the-first-conversation assertion that keeps that clear from being vacuous, and now the monotone bank. My remaining notes on this PR are the ones from the earlier reviews and none of them block: the serve side (forward_serve.cpp) is still one sequence per request, which the body says plainly, and that is where this shape earns its keep.

@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 58eec0a: READY — with one limit stated up front: I could not build or run this test here.

Why not, and what that costs the review

CMakeLists.txt:2424  if(ONEBIT_NPU)
CMakeLists.txt:2588    add_executable(step_users_test …)
CMake Error at CMakeLists.txt:2451: ONEBIT_NPU needs the NPU runtime: ONEBIT_NPU_RT_LIB must name its prebuilt
  library, or ONEBIT_NPU_RT_DIR must hold npu_rt.h … The runtime is private

The target lives inside if(ONEBIT_NPU), and that guard refuses to configure without the private runtime, which this review tree does not have. So the 321-line test was not executed by me, and the claim it carries — "each row bit-identical to its own run" — is verified here only by reading the assertions, not by running them. Saying that is more useful than a green line nobody can reproduce.

What I could check, and it is not nothing

The row reaches ctest (my first suspicion was that it did not, and the repo's own tool refuted me):

$ ci_targets_check.py --check --where step_users
step_users	CMakeLists.txt:2592

$ ci_targets_check.py --check
… 9 target(s) whose test never reaches ctest under ci.yml (baseline 9), and none new

So no new "Not Run" row, which is the defect #2702 was about. I nearly filed a CHANGES on the hypothesis that the guard made the test invisible; the tool said otherwise in one line.

And the assertions are the right shape. The test does not compare a batched pass against a reference implementation — it compares it against that user's own single-user run:

FAIL round %d slot %d row differs at logit %d (of %zu): %.9g vs %.9g
round %d: %d row(s) in one pass
round %d: %d separate single-user steps         ← the other arm, timed, for the claim's cost

"bit-identical to its own run" is the only oracle that is both necessary and cheap here: a batched pass that agrees with a second batched pass proves nothing, and one that agrees with a fixed golden would break on every legitimate kernel change. Comparing each row to the same user's own single-row step is the property the PR actually claims.

SKIP: a noncausal pack is refused by step_users by design is the right third arm — the batching premise (causal attention) is checked rather than assumed, and a non-causal pack skips by name instead of producing a wrong comparison.

The measurement the change rests on

"the step costs the same from 1 to 16 rows (measured 11-16: Llama-3.2-1B ≈ 146 ms, Qwen3-1.7B ≈ 214 ms, exact at every N). So 16 users of one model cost about what one does."

That is why the change is worth 552 lines — and it is a device measurement quoted from a ticket, correctly attributed rather than re-derived here.

What a reviewer with the runtime should do

Run ctest -R step_users with ONEBIT_TEST_Q4NX naming a container, and confirm it executes rather than skips — the arm prints SKIP for a noncausal pack, so a "pass" that is really a skip must be visible in the output, not inferred from rc 0.

@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 58eec0a: READY

The bug is real, the fix is right, and the new arm discriminates — verified by running the new test against the pre-fix source, not by reading the comment.

The A/B

Same test file at this head (58eec0ab), two objects of q4nx_forward.cpp: this head's, and the previous head's (e8b53af, i.e. before the growth-only change). Host-GEMM, no device, Qwen3-0.6B:

FIXED   (58eec0a): ok: 3 sequences x 4 rounds, every row bit-identical to its own single-sequence run
PRE-FIX (e8b53af): FAIL slot 1 lost its cache when slot 0 ran alone:
                        logit 0 is -nan, its own run says 7.21747065

That -nan is exactly the serve-batcher symptom the commit message describes, produced by the arm it added — so the arm is not a restatement of the fix, it is the failure.

Why the old code did that

user_kc_.resize(smax + 1) is a shrink when the current call touches a lower maximum slot than a previous one (std::vector::resize destroys the tail). One single-user call between multi-user rounds therefore dropped slots 1..n, and the next row for slot 1 re-created an empty per-layer bank (user_kc_[s].empty() -> assign) and attended at a position above 0 over nothing. Growth-only sizing is the correct shape: the bank is a cache of caches, and its size must be monotone in what it has been asked to hold.

What still holds from the earlier heads (unchanged here)

The pos == 0 clear, the per-row positions and the refusals are untouched by this delta (the diff is the two resize guards, the comment, and the new arm). The earlier verification — bit-identity on this pack, the GDN refusal firing by name, and the reuse arm — remains valid at this head because the pass body did not move.

Nit, non-blocking: the arm advances slots 1..n one at a time after the single-slot call, which is the right shape for this bug; if you later add a batcher test that runs slot 1 in the same pass as slot 0, the growth-only invariant is what it will be protecting, so the comment could name it in one clause ("the bank is monotone; a pass may only add slots").

@bong-water-water-bong
bong-water-water-bong merged commit 9e73697 into main Nov 16, 2026
11 checks passed
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Record, since this merged at 9e73697 with both review items still open: git show origin/main:npu/forward/src/q4nx_forward.cpp | grep -c "must ascend" → 0, and no rows_slot_ guard at the NPU_BATCH_CHECK gate.

I did not open a competing PR. The 20-line patch for both refusals is written, committed on cl-npuperf/2689-stepusers-refusals and syntax-checked against main (0 errors, same as unpatched main), and handed to #2689 with the diff inline — item 3b's PR is the caller that can actually hit the ragged-position case, so it belongs there. If nobody takes it, I will push it as a draft when a CI slot frees.

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 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