Repository navigation
npu: one decode pass carries several users, each row bit-identical to its own run (engine#2689 item 3) - #2714
Conversation
… 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.
|
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 Three mutants, each rebuilt and restored: Not in this PR, deliberately: the serve-side batching (that is where the tok/s is) and the device row — with |
bong-water-water-bong
left a comment
There was a problem hiding this comment.
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 holdsSo 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 beforeload_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 == 0mean what it means everywhere else in this file, and needs no new API; or -
export
reset_user_slot(int s)and refusepos == 0on 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 asattention()'s position (so the append offset is each row's own) and becomesTmforrows_read; the whole-prompt case usesrow_pos(m1-1) + 1, which for a single slot spanning all M rows isstart_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 failedstep_batch_implreturnsok = falseafter 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_syntaxOBJECT library), so a compile break inq4nx_forward.cppis caught even though the runtime is private. The new test is inside theif(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
left a comment
There was a problem hiding this comment.
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 insidestep_users()and cleared on the way out (q4nx_forward.cpp:4784-4792), and the per-row position is read asrows_pos_ ? (*rows_pos_)[m] : start_pos + m(:5142) — sostep()andstep_batch_implkeep 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-holdticket, 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.cppstill one sequence per request) — consistent with the body: this PR is the forward half, and item 3 stays open on #2689.
|
VERDICT: READY 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:
And one note worth keeping: " |
bong-water-water-bong
left a comment
There was a problem hiding this comment.
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
- Push the fix and its arm — the working tree in
~/wt/cl-npurt-amdcolalready has both; nothing new is needed and I will verdict the new head immediately. - While you are in the header, write the slot-lifetime sentence next to
step_users()("a slot whose first row ispos 0starts 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".
|
The finding stands and it is fixed at 6e49574 — a slot has no way to start a new sequence, so it kept the previous I took your first option rather than the explicit The arm you asked for is in, and it fails without the fix. At 6e49574, after slot 0 has served and it asserts two things, in this order:
Mutant, rebuilt and restored: the clear removed → The other reviewer's READY at 88b4a5c is unaffected in substance — the pass, the park/restore ordering, the per-row |
bong-water-water-bong
left a comment
There was a problem hiding this comment.
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.
|
Device row at 6e49574 — one 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:
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: |
…(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).
|
Head moved to e8b53af (the device-row numbers above are in this commit, not in 6e49574:
|
bong-water-water-bong
left a comment
There was a problem hiding this comment.
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:
- 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_usersalready refuses, say so with the message; if the bound is checked elsewhere, name where. - 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. - 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
left a comment
There was a problem hiding this comment.
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 skipsNPU_INFER_HOST_GEMM=1whenONEBIT_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
left a comment
There was a problem hiding this comment.
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.
|
VERDICT at 1. Positions within a slot are never validated, so a bad call is served wrong instead of refused. 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 ( 2. Not blocking, worth a line in the code: the cache swaps are not exception-safe. What I verified and am not asking about:
|
PR Reviewer Guide 🔍(Review updated until commit 58eec0a)Here are some key observations to aid the review process:
|
…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.
|
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. That is the NaN the batcher produced before the fix ( Why this PR's own test could not see it: every call in 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. |
|
Persistent review updated to latest commit 58eec0a |
|
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 ( 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 Three things I would pin:
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 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. |
|
VERDICT at Verified in this head (good):
Still open at this head, both from the
Neither needs a new build shape: the first is one Not blocking, unchanged: the KV swaps are not exception-safe (no scope guard between |
bong-water-water-bong
left a comment
There was a problem hiding this comment.
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 onenpu-holdticket."
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
left a comment
There was a problem hiding this comment.
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_batchthen onestep()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
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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").
|
Record, since this merged at I did not open a competing PR. The 20-line patch for both refusals is written, committed on |
…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.
…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]>
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:
Q4nxNpuForwardholds ONE sequence (kcache_/vcache_, 24 sites insidestep_batch_implderiving a row's positionfrom
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 becontiguous and the slots ascending; returns M × NV logits exactly like
step_batch_all().row_pos(m)replacesstart_pos + min the attention position and in the read length / windowstart handed to
q4nx_attn::rows_context(which already took both per row — that helper is unchanged).load_user_slot(s)swaps slots's cache into the workingkcache_/vcache_pair (whatattention()androws_context()read) and back; the model's own caches are parked for the duration of the pass andrestored 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.
lin_kd_) and MLA keep a recurrence/absorptionstate 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 refusedwith the rule in the message.
docs/npu.mdparagraph, 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 tocommit_full_accept): three sequences ofdifferent lengths (3, 5 and 4 prompt tokens, so their positions diverge after the first round), each with its own
separate
Q4nxNpuForwardas the reference and run as a plain single sequence, against one instance fed the same tokensthrough
step_users()with one row per sequence per pass:Every row of every pass is
memcmp-identical to that sequence's ownstep()logits, after a prefill that also goesthrough
step_users(one slot at a time), so the slot caches have to be filled exactly asstep_batchfills the model'sown. Host-GEMM (
NPU_INFER_HOST_GEMM=1), no device, 78 s for the 1.7B pack;ctest step_usersskips (77) withoutONEBIT_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 inthe first row);
row_pos()returningstart_pos + m→ FAIL round 0 slot 0 row differs at logit 0;What is not here
app/forward_serve.cppstill runs one sequence per request; batching up to 16 active requestsinto these rows is the next PR (that is where the tok/s lands).
max_batch_rows()= 1 under host GEMM, this PR proves correctness, not speed. Theaggregate tok/s at N = 1/4/8/16 on the array is the follow-up measurement, as one
npu-holdticket.rows_pos_/rows_slot_are null for every call butstep_users(), so thebatched body and
step()run exactly as before.🤖 Generated with Claude Code