Skip to content

npu: the GDN head loop goes parallel, contiguous and off the whole box (prefill 6.0 -> 21.0 tok/s) - #944

Merged
bong-water-water-bong merged 9 commits into
mainfrom
npu/gdn-head-omp
Nov 4, 2026
Merged

bong-water-water-bong merged 9 commits into
mainfrom
npu/gdn-head-omp

Conversation

@bong-water-water-bong

@bong-water-water-bong bong-water-water-bong commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Prefill on the 27B is host-bound, and 76.5 % of it is one loop. perf on a 27B prefill puts
Q4nxNpuForward::gdn_layer_batch at 76.51 % of CPU cycles (next: 3.65 % I8Ctx::launch_async_with_bo_rows,
2.86 % npu_gemm_rows, 2.53 % hadamard_rotate). 48 of the 64 layers are GDN linear attention and the delta-rule
recurrence runs host-only — plan.json and the NPU designs cover only the projections (qkv, attn_gate/Z, ssm_out,
gate_up, down), so there is no ELF to blame. Per head the state update is sh *= eg over KHD*VHD plus two 128x128 MAC
passes: NVH=48 heads x 48 layers ≈ 113 M scalar FLOPs per token, which is the ~105 ms/token the phase profile could not
attribute.

Three changes, all in that one loop. Greedy text is byte-identical throughout (b634703a1a8ae098 at every arm and
every thread count), which is the gate for all of them.

  1. Parallelise it. Heads are independent — disjoint rec_state_ rows, disjoint CORE rows — so the loop
    parallelises as-is; kvm was shared scratch reused per head, so it moves inside and becomes per-head. No maths, no
    relayout, no new buffer.
  2. Make it contiguous. The three delta-rule passes were stride-VHD gathers (sh[kd*VHD+vd] inside a loop over
    vd). Loop exchange (kd outer, vd inner) makes the inner pass walk sh/vh contiguously, which is what lets
    the compiler vectorise it; each pass gets #pragma omp simd. kvm and the delta share one allocation per head —
    allocating inside a parallel region contends on the allocator between the threads the region just created, and this
    loop runs 48 heads x 48 layers x rows per token.
  3. Stop taking the whole box. The forward needs a core for the array's submit thread and the serve needs one for
    HTTP, so 32 OpenMP threads on 32 cores measured 25 % slower than 16. omp_heads_threads() caps the region at
    3/4 of the cores; a lower OMP_NUM_THREADS still wins, so the cap only stops the default from oversubscribing.
    (A higher OMP_NUM_THREADS is bounded by the clause but still sizes libgomp's pool: 32 measured 18.9 against the
    capped default's 21.3, so leave it unset or <= cores*3/4.)

OpenMP is already wired for onebit_npu_forward on main (CMakeLists.txt:833-837), so no build change.

Measured

strixhalo, one npu-hold window per row, same window for each pair, prompt-only prefill = TTFT to the first streamed
chunk, fresh serve per arm warmed with a ~300-token prefill (a 200-char stub leaves the first big request 3-4x slow —
see the note at the end). Harness: ~/wt/prefill-bench.py + ~/wt/prefill-arm.sh.

arm 149-token prompt 704-token prompt decode @149
unparallelised serve (t2s2-20261102) 5.69-6.10 tok/s 5.50 3.17
commit 1 only (32 threads) 15.35 11.89 2.67
commit 1 only, 16 threads 16.61 13.81 3.26
commit 1 + 2, 16 threads 21.01 (+26 %) 16.53 (+20 %) 3.20
commit 1 + 2, default (cap 24) 21.46 / 21.26 (two windows) 17.05 3.19

The prompt path is 6.0 → 21.0 tok/s (3.5x), decode flat. Cross-window absolutes on this box drift ±15 %, so every
multiplier above comes from a within-window pair; the default reading was confirmed in two separate windows.

What is still on the host, and two measured negatives

The array is ~14 % of the wall even now: a pb16i container walks a prompt in 16-row chunks (max_batch_rows()), so
a 1k-token prompt streams the 6.11 GB t2s2 weight set 64 times ≈ 391 GB ≈ 10-12 s at 33-40 GB/s = 86-104 tok/s of
array time
, against 17 measured here.

  • mla_attn OMP over heads (the next item in the perf list): +1.8 % / +1.9 %, i.e. nothing. And it turns out
    mla_ is 0 for this container — mla_attn is never called for Bonsai-2 (the 16 full-attention layers run
    attention()), so both arms were null controls and that +1.8 % was noise. Retracting an earlier claim: a
    first version of that patch appeared to be 2x slower and I blamed per-head std::vector allocations; with no code
    path running, that number was window contamination, not the code. The mla patch is dropped either way.
  • The lesson that survives on mechanism alone: do not allocate inside a parallel region.

One measurement hazard, for anyone reproducing this: the first big request on a fresh serve pays the weight-image
fill (~3-4x slower) even after /health answers, so an arm that runs first reads 6.2 tok/s where the same binary reads
13.2 on its second request. Warm with a real ~300-token prefill, or the arm order becomes the experiment.

Part of the prefill work in TBONSAI-PREFILL.md items 1-3. No merges from me.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

#944 ready for review at dccb02d — fresh branch off origin/main 4b5ef50, one commit, one file (+5/−1). OpenMP is already linked for onebit_npu_forward on main, so no build change. Measured in one npu-hold window with both arms back to back: prefill 5.69→14.43 / 5.62→13.81 / 5.44→11.59 tok/s at 145/289/865 prompt tokens, greedy text byte-identical (a55c0083d904cd03, 82b312f0a3880f27), amdxdna 0. No merges from me.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

#944 updated — now two commits, head 7ba2ef4. Same-window pairs: SIMD/loop-exchange +26 % / +20 % (16.61→21.01 at 149, 13.81→16.53 at 704), thread cap +25 % (16.70 at 32t vs 20.83 at 16t), default path confirmed twice at 21.3-21.5 tok/s. Greedy text byte-identical in every arm (b634703a1a8ae098), decode flat (3.19-3.26 tok/s). Two negative results documented in the body so nobody repeats them: mla_attn OMP is +1.8 % (dropped), and a per-head std::vector for its scores is 2x slower. No merges from me.

@bong-water-water-bong bong-water-water-bong changed the title npu: parallelise the GDN head loop -- perf puts it at 76.5% of host cycles npu: the GDN head loop goes parallel, contiguous and off the whole box (prefill 6.0 -> 21.0 tok/s) Nov 4, 2026
@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit b008a94)

Here are some key observations to aid the review process:

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

Thread Safety of `omp_heads_threads`

The omp_heads_threads() function uses omp_get_num_procs() and omp_get_max_threads() which may not be thread-safe in all OpenMP implementations. If these functions are called from multiple threads simultaneously, it could lead to inconsistent thread count decisions, potentially causing oversubscription or underutilization of CPU cores.

static inline int omp_heads_threads() {
#if defined(_OPENMP)
    const int cap = (3 * omp_get_num_procs()) / 4;
    const int want = omp_get_max_threads();
    return want < cap ? (want > 0 ? want : 1) : (cap > 0 ? cap : 1);
#else
    return 1;
#endif
}
Potential Memory Allocation in Parallel Loop

The scratch vector is allocated inside the parallel loop (#pragma omp parallel for). While this avoids the mistake of per-head allocation, it introduces a potential performance issue as allocations happen per-thread in each iteration of the loop. This could lead to increased memory allocation overhead and cache pressure.

std::vector<float> scratch((size_t)2 * VHD);
float* kvm = scratch.data();
float* delta = kvm + VHD;

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 3d2172c

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

#944 ready for review at 3d2172c — two commits on origin/main 4b5ef50. CI on this head: build SUCCESS (100% tests passed, 0 tests failed out of 76), all four Analyze legs + CodeQL + pr_agent SUCCESS, hw_gate SKIPPED as designed, 0 review threads. mergeStateStatus: BEHIND only because main moved; the diff is one file (npu/forward/src/q4nx_forward.cpp) and main is unprotected.

Numbers are within-window pairs (this box drifts ±15 % across windows): loop-exchange+SIMD +26 % / +20 % at 149/704-token prompts, thread cap +25 % (16.70 at 32t vs 20.83 at 16t), default path 21.3-21.5 tok/s confirmed in two windows, against the unparallelised serve at ~6.0 tok/s. Greedy text byte-identical in every arm. Decode flat.

One correction since the first push, so it is on the record: I had claimed mla_attn OMP was worth +1.8 % and that an earlier per-head-std::vector version was 2x slower. mla_ is 0 for this container, so mla_attn is never called for Bonsai-2 — both were null controls and the 2x was window contamination. The PR body and the commit message say so now.

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 69d0a5e

@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 69d0a5e (post-rebase head; tprs-ready added).

What I verified myself, and what I could not. The reboot wiped /tmp/ab*.jsonl and the per-arm logs (your own state file says so at 01:3x), and your prefill-1k-sweep ticket was in flight, so I did not re-run the device — the 3.5× rests on your within-window pairs, not on a number I re-derived. Everything else I did:

  • The rebase is textual only. git diff 3d2172c 69d0a5e -- npu/forward/src/q4nx_forward.cpp is empty, so the code CI built is the code you measured. Head = refs/pull/944/head = refs/heads/npu/gdn-head-omp.
  • It builds at this head with -DONEBIT_NPU=ON + the private runtime (gcc-16): 41/41, 1bit links, 4.67 MB; 0 warnings from q4nx_forward.cpp (all 16 in the build are the pre-existing nlohmann is_trivial). Flags are -O3 -DNDEBUG -std=c++26 -fopenmp, and the object carries GOMP_parallel, omp_get_num_procs, omp_get_max_threads — so the pragma is live (not one of those silently-ignored ones) and omp_heads_threads() is really called.
  • The cap arithmetic on this box: omp_get_num_procs() = 32 → cap = 24; OMP_NUM_THREADS=16 wins downward, 32 is clamped to 24. Matches what you measured.
  • The container's own dims, from ~/models/npu/bonsai2-27b-NPU/config.json: linear_num_value_heads 48, linear_key_head_dim / linear_value_head_dim 128/128. So one head's state update is 3 passes × 128×128 = 49,152 MACs, × 48 heads × 48 GDN layers = 113.2 M MACs/token — your "113 M" is right as a count of MACs (it is 226 MFLOP; see nit 4).
  • The array ceiling arithmetic re-derives: 6.11 GB × (1024/16 = 64 chunks) = 391 GB; 391/40 = 9.8 s and 391/33 = 11.8 s → 87–104 tok/s. That half is self-consistent.
  • Read for races, not just style. Inside the region every write is per-head (rec_state_[l] rows at hh*KHD*VHD, CORE at m*VD + hh*VHD); everything else touched is a const read (kl/ql/vv, z, gdn_small_[l].{ssm_a,dt,norm}, sem_.eps); the for (m) loop, verify_open_ capture and the [GB] dumps are all outside; nothing packs weights lazily in there. Each head's arithmetic is a per-element chain with no cross-head or cross-element reduction, so thread count cannot reorder a sum.

One measured finding — the comment's "same sequence of operations" is a property of this build's flags, not of the rewrite. I extracted both versions of the rule verbatim (gather/vd-outer vs exchanged+omp simd) into a probe, fed identical inputs, and compared the outputs bitwise:

g++-16 -O3            -fopenmp   state 0/16384 differ, CORE 0/128, ss identical   <- shipped flags
g++-16 -O3 -march=native -fopenmp state 9303/16384 differ (worst 7.2e-07), CORE 98/128, ss differs
g++-16 -O3 -march=native -ffp-contract=off  -> bit-identical again

So with FMA available the contiguous form contracts differently from the stride-VHD gather, and the state moves in the last bits. That does not contradict your gate (greedy text identical is an end-to-end observation and it held), but the sentence "the result is the same sequence of operations -- verified by the greedy text being byte-identical" now reads as if bit-identity followed from the rewrite. It follows from -O3 without -march=native. One clause ("orders identical per element; the vectorised form can contract differently from the gather, so the greedy hash is the gate") makes that comment true under any future flag.

Nits, none gating:

  1. The FMA wording above.
  2. "ONE allocation" is still one allocation per head inside the parallel region — 48 heads × 48 layers × rows per token, ~2.3 k allocations/token, which is the shape of the mla mistake you wrote down. A std::vector<std::vector<float>> scratch(gdn_nt) sized before the region (or alloca/a thread-local) removes it entirely; worth measuring rather than assuming, since the allocator is per-thread-arena and cheap.
  3. The region sits inside for (int m = 0; m < M; m++), so a 16-row chunk opens 16×48 regions per layer-batch. At your 21 tok/s that is ~2 % of a token; hoisting the parallel region over (m, hh) would remove it, if you ever want the last few per cent.
  4. "113 M scalar FLOPs" → MACs (226 MFLOP).

CI at this head: build, Analyze ×5, CodeQL, pr_agent SUCCESS, hw_gate skipped.

@bong-water-water-bong bong-water-water-bong added the tprs-ready TPRS: review verdict READY posted by the standing reviewer; merge gate satisfied label Nov 4, 2026
bcloud and others added 2 commits November 4, 2026 01:59
…ycles

perf puts Q4nxNpuForward::gdn_layer_batch at 76.51% of CPU cycles during a 27B
prefill (next: 3.69% I8Ctx::launch_async_with_bo_rows, 2.86% npu_gemm_rows,
2.53% hadamard_rotate).  48 of the 64 layers are GDN linear attention and the
delta-rule recurrence runs host-only -- plan.json and the NPU designs cover only
the projections (qkv, attn_gate/Z, ssm_out, gate_up, down), so there is no ELF
to blame.  Per head the state update is `sh *= eg` over KHD*VHD plus two 128x128
MAC passes: NVH=48 heads x 48 layers ~ 113 M scalar FLOPs per token, which is
the ~105 ms/token the phase profile could not attribute.

The heads are independent -- disjoint rec_state_ rows, disjoint CORE rows -- so
the loop parallelises as-is.  kvm was shared scratch reused per head, so it
moves inside the loop and becomes per-head.

Measured on strixhalo, same prompts, one NPU ticket, prompt-only prefill:
  37 tok  5.8 -> 8.9 tok/s     decode 1.71 -> 2.67 tok/s
  109 tok 6.1 -> 12.4 tok/s
  217 tok 4.7 -> 12.8 tok/s
Live on :18097 after deploy: 12.7/13.9/13.9 prefill, 3.05 decode.
An 80-token greedy generation is byte-identical to the unpatched binary.

Note for the record: parallelising mla_attn first made the serve *slower*
(3.4-4.5 vs 5.5-6.0 tok/s) -- that loop is cold, and fork/join on a cold loop is
pure cost.  Measure before parallelising.
…op stops taking the whole box

Two changes to the loop the previous commit parallelised.  Both are gated on the same thing as always: a
32-token greedy completion hashes identically before and after, at every prompt.

1. The three delta-rule passes were stride-VHD gathers -- `s += sh[kd * VHD + vd] * kh[kd]` inside a loop
   over vd, so the inner loop jumped a whole row per element.  Exchanging the loops (kd outer, vd inner)
   makes the inner pass walk `sh` and `vh` contiguously, which is what lets the compiler vectorise it, and
   each pass gets `#pragma omp simd`.  `kvm` and the delta now share ONE allocation per head: allocating in
   a parallel region contends on the allocator between the threads the region just created, and this loop
   runs 48 heads x 48 layers x rows per token.
   (Correction for the record: an earlier attempt to *measure* that hazard in mla_attn showed a 2x loss, but
   mla_ is 0 for this container -- `mla_attn` is never called for Bonsai-2 -- so that patch was a null
   control and the 2x was window contamination, not the allocations.  The rule stands on the mechanism, not
   on that number.)

2. The loop took every core.  The forward needs one for the array's submit thread and the serve needs one
   for HTTP, so on this 32-core box 32 OpenMP threads measured 25 % slower than 16 and 24 was level with 16
   (same window, same binary: 16.70 tok/s at 32 threads vs 20.83 at 16, 149-token prompt).  `omp_heads_threads()`
   caps the region at three quarters of the cores; a lower OMP_NUM_THREADS still wins, so the cap only stops
   the default from oversubscribing.  (A *higher* OMP_NUM_THREADS is bounded by the clause but still sizes
   libgomp's pool: 32 measured 18.9 against the capped default's 21.3, so leave it unset or <= cores*3/4.)

Measured on strixhalo, prompt-only prefill (TTFT to the first streamed chunk), same window for each pair:

    GDN loop parallel only (previous commit), 16 threads   16.61 / 13.81 tok/s   (149 / 704 tokens)
    + this commit, 16 threads                              21.01 / 16.53         (+26 % / +20 %)
    + this commit, default (cap = 24)                      21.46 / 17.05
    decode, 16 tokens at a 149-token prompt                3.26 -> 3.19 tok/s    (flat)

Against the unparallelised serve the prompt path is 6.0 -> 21.0 tok/s, i.e. 3.5x, and every greedy text is
byte-identical throughout.
@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 3248885

@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 32488856b. The branch's own diff is byte-identical to the one I reviewed at 69d0a5e34 (git diff origin/main...<head> hashes equal at both heads), so this head only carries base moves.

What that verification covered: built 41/41 with gcc-16 (0 warnings from q4nx_forward.cpp), the OpenMP pragma live (GOMP_parallel/omp_get_num_procs in the object), the head count confirmed from the container (48 × 128/128 = 113.2 M MACs/token), and every write in the parallel region audited as per-head.

The finding I posted then still stands and is worth restating for whoever reads the merge list: the "same sequence of operations" claim holds at -O3 (bit-identical) but not with -march=native, where the exchanged form contracts to FMA (9303/16384 state elements differ, worst 7.2e-07; -ffp-contract=off restores identity). No shipped build uses -march=native, so it is a note, not a blocker.

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit e07ae75

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 83338b2

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 8921903

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 63d0fd1

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 3a5928d

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit c6df811

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit b008a94

@bong-water-water-bong
bong-water-water-bong merged commit eda7542 into main Nov 4, 2026
9 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the npu/gdn-head-omp branch November 4, 2026 09:33
bong-water-water-bong pushed a commit that referenced this pull request Nov 4, 2026
…944 across the target split

Main moved under this branch four times after the 02:22 merge, and three of those commits
touch exactly the code P4 moved into npu/target, so the merge is a port, not a merge:

* #910 (gemv head) creates the lm head's context from a `full_i8_LMHEAD_*` ELF, tightens
  run_lm_head_gemv's tile-stream check (dtype by name, length must BE the padded or the real
  vocabulary width, zero-filled tail) and refuses the int8 tiled head when the family is gemv.
  Kept verbatim, with the context reached through the target (`xd_->make_head_ctx()`,
  `xd_->head_ctx()`, `xd_->head_ctx_ref()`, `xd_->ctx(i)`/`xd_->ctx16(i)`) instead of the
  members P4 moved.  The two functions that stayed in the model (`run_lm_head_gemv`,
  `run_lm_head`) now use the target's head context (`hctx`) where they used `ctx_head_`.
* #871 (fill a weight image straight into the BO) changed the two pb16i cache-miss sites from
  `make_weight_bo(*dev_)` to `make_weight_bo(*dev_, /*zero=*/false)`; those sites live in
  npu/target/xdna/xdna_target.cpp now, so the two-line delta is applied there.
* #944 (GDN head loop parallel) is outside the split and merged clean.

Resolution: 4 conflict hunks in npu/forward/src/q4nx_forward.cpp — the two npu_gemm bodies keep
P4's delegation to xd_->gemv(), the other two take main's text with the target accessors.  The
auto-merged init_impl block needed the same treatment by hand (it referenced the moved
`ctx_head_`), which is the reason this was resolved by reading, not by `git checkout`ing a side.

Verified: `onebit_npu_forward_syntax` compiles in the CI config (ONEBIT_NPU=OFF, the #912
target) and `onebit_npu_forward` compiles + links in ONEBIT_NPU=ON, which is the only place
npu/target/xdna/xdna_target.cpp is built.  tools/copyright.py --check rc 0.
bong-water-water-bong pushed a commit that referenced this pull request Nov 4, 2026
…d and strided (85 -> 5.3 ms per accepted row)

gdn_apply_rows() is the per-row half of a verify batch: after a partial accept, commit_verify_rows() restores the
snapshot and re-applies the recurrence for the accepted rows only.  It was the one place left in the pre-#944 loop
shape -- one thread, and the rank-1 update walking the state row with stride VHD, so every touch is a different cache
line, over 48 GDN layers x 48 heads x 128x128 state (144 MB) per row.

That is why engine#972's opening measurement read as an M-row batch costing 141 ms/row: the tool's window includes
commit_verify(), and the replay was 74-153 ms of it while step_batch's own host work is ~41 ms/row at M=16.

The loops are now exchanged exactly as #944 exchanged them in gdn_layer_batch (kd outer, vd inner, contiguous on the
state row; each output element still accumulates over kd in increasing order) and the heads run in one parallel region
per replay with the per-row preparation in an omp single, because it writes the shared conv ring.

Measured on bonsai2-27b-pb16i, sealed M=16 pb16i ELFs, one npu-hold claim per A/B, arm A/C = before and arm B = after
in the same window: replay 63-153 ms/row before, 5.2-13.5 after (16x); in the live loop 4030 ms -> 720 ms over 20
commits.  The verify-batch curve at load<8 moves 589/720/1149/2721 -> 436/505/627/1336 ms at M=1/2/5/16, and M=1 lands
on before-minus-measured-replay to the tenth of a millisecond.  Acceptance and text are untouched (44/80, chain 3.20
t/pass, per-depth 90/65/35/30, TEXT IDENTICAL, 0 stream mismatches), and NPU_REPLAY_CHECK=1 asserts the replay lands on
exactly the state the batch left (max |diff| 0.000e+00).

closes #972
bong-water-water-bong pushed a commit that referenced this pull request Nov 4, 2026
…d and strided (85 -> 5.3 ms per accepted row)

gdn_apply_rows() is the per-row half of a verify batch: after a partial accept, commit_verify_rows() restores the
snapshot and re-applies the recurrence for the accepted rows only.  It was the one place left in the pre-#944 loop
shape -- one thread, and the rank-1 update walking the state row with stride VHD, so every touch is a different cache
line, over 48 GDN layers x 48 heads x 128x128 state (144 MB) per row.

That is why engine#972's opening measurement read as an M-row batch costing 141 ms/row: the tool's window includes
commit_verify(), and the replay was 74-153 ms of it while step_batch's own host work is ~41 ms/row at M=16.

The loops are now exchanged exactly as #944 exchanged them in gdn_layer_batch (kd outer, vd inner, contiguous on the
state row; each output element still accumulates over kd in increasing order) and the heads run in one parallel region
per replay with the per-row preparation in an omp single, because it writes the shared conv ring.

Measured on bonsai2-27b-pb16i, sealed M=16 pb16i ELFs, one npu-hold claim per A/B, arm A/C = before and arm B = after
in the same window: replay 63-153 ms/row before, 5.2-13.5 after (16x); in the live loop 4030 ms -> 720 ms over 20
commits.  The verify-batch curve at load<8 moves 589/720/1149/2721 -> 436/505/627/1336 ms at M=1/2/5/16, and M=1 lands
on before-minus-measured-replay to the tenth of a millisecond.  Acceptance and text are untouched (44/80, chain 3.20
t/pass, per-depth 90/65/35/30, TEXT IDENTICAL, 0 stream mismatches), and NPU_REPLAY_CHECK=1 asserts the replay lands on
exactly the state the batch left (max |diff| 0.000e+00).

closes #972
bong-water-water-bong added a commit that referenced this pull request Nov 4, 2026
…d and strided (85 -> 5.3 ms per accepted row) (#1022)

gdn_apply_rows() is the per-row half of a verify batch: after a partial accept, commit_verify_rows() restores the
snapshot and re-applies the recurrence for the accepted rows only.  It was the one place left in the pre-#944 loop
shape -- one thread, and the rank-1 update walking the state row with stride VHD, so every touch is a different cache
line, over 48 GDN layers x 48 heads x 128x128 state (144 MB) per row.

That is why engine#972's opening measurement read as an M-row batch costing 141 ms/row: the tool's window includes
commit_verify(), and the replay was 74-153 ms of it while step_batch's own host work is ~41 ms/row at M=16.

The loops are now exchanged exactly as #944 exchanged them in gdn_layer_batch (kd outer, vd inner, contiguous on the
state row; each output element still accumulates over kd in increasing order) and the heads run in one parallel region
per replay with the per-row preparation in an omp single, because it writes the shared conv ring.

Measured on bonsai2-27b-pb16i, sealed M=16 pb16i ELFs, one npu-hold claim per A/B, arm A/C = before and arm B = after
in the same window: replay 63-153 ms/row before, 5.2-13.5 after (16x); in the live loop 4030 ms -> 720 ms over 20
commits.  The verify-batch curve at load<8 moves 589/720/1149/2721 -> 436/505/627/1336 ms at M=1/2/5/16, and M=1 lands
on before-minus-measured-replay to the tenth of a millisecond.  Acceptance and text are untouched (44/80, chain 3.20
t/pass, per-depth 90/65/35/30, TEXT IDENTICAL, 0 stream mismatches), and NPU_REPLAY_CHECK=1 asserts the replay lands on
exactly the state the batch left (max |diff| 0.000e+00).

closes #972

Co-authored-by: pi-mtploop <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Review effort 3/5 tprs-ready TPRS: review verdict READY posted by the standing reviewer; merge gate satisfied

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant