Skip to content

npu forward: attention sums its scores 8-wide when the CPU has AVX2+FMA and splits heads across cores, so a long prefill is not 398 s of scalar math - #1243

Merged
bong-water-water-bong merged 3 commits into
mainfrom
1bit/host-attn-simd
Nov 6, 2026
Merged

bong-water-water-bong merged 3 commits into
mainfrom
1bit/host-attn-simd

Conversation

@bong-water-water-bong

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

Copy link
Copy Markdown
Collaborator

Root cause

The per-op NPU forward's attention is host math (npu/forward/src/q4nx_forward.cpp), and its score
loop was a single-accumulator float reduction:

float d = 0.0f;
for (int i = 0; i < HD; i++) d += qh[i] * kt[i];

Without -ffast-math gcc may not reassociate that, so it stays one FMA latency chain, and the head
loop was serial. That is the whole reason a long prefill of the Phi-3.5-mini OGA pack (32 layers,
32 heads, head_dim 96) took 208-398 s while the same prompt's GEMMs cost 2.1 s on the array: the
quadratic term was scalar host math, and none of it was the device. It is the term the gate (c) rows
in #671 named (27.0 / 17.5 / 5.1 tok/s at ctx 128 / 512 / 2048).

Change (one file, no behaviour change intended)

  • dot_f32(): AVX2+FMA 8-wide, with a portable four-accumulator fallback, dispatched through
    have_avx2_fma() the same way npu/forward/include/hadamard.h already dispatches its SIMD path.
    This file is built for the baseline x86-64 ISA, so plain C++ only ever got 4-lane SSE2.
  • saxpy_f32() for the value accumulation — the other half of the attention flops.
  • the head loop is an OpenMP parallel region over heads, which are independent by construction (each
    writes its own ctx rows and reads its own q against a read-only KV cache), with a per-thread
    score buffer; short contexts stay serial ((long)T*HD >= 8192).

Measured

Device-free first, where the mechanism is visible: NPU_INFER_HOST_GEMM=1, the forward's own
[bl] attn timer, GFLOP/s from the exact MAC count (32 layers x 32 heads x head_dim 96 x 2 tensors),
two binaries interleaved on the same box load, ctx 512:

arm attn ms attn GFLOP/s
before 6375.3 8.10
after 1682.9 30.69

Then on the array (b8 container + b8 kernels, --prefix-slots 0, the same protocol as gate (c), the
reply's own timings.prompt_ms), interleaved within one npu-hold ticket, amdxdna ERROR 0 -> 0:

ctx before after speedup
512 24.8 s (20.6 tok/s) 21.1 s (24.2 tok/s) 1.18x
2048 208.1 s (9.8 tok/s) 52.7 s (38.8 tok/s) 3.94x

(medians of 3 for 512 on a quiet box: loadavg 1.5-4.2, gpu_busy 0. A repeat ticket under a GPU
job — gpu_busy 89-100, loadavg 8-14 — gave the same shape: 512 49.7 -> 28.6 s, 2048
341.3 -> 108.8 s, i.e. 1.5x and 3.1x, with the "after" arm running at the higher load.)

The 512 row gains least because at that size the wall is the per-token dispatch (this route
prefills one token at a time: 128 launches per token), not attention — which is the separate,
already-recorded lever (fused-lane artifacts, not host math).

Numerics

The three forms sum in different orders, so scores differ by float rounding: --dump-logits on the
same prompt gives an identical argmax (2793) and max|dlogit| = 1.0e-4 on a 28.5 max logit
(relative 3.6e-6). Greedy 8-token output on three prompts is identical to a same-commit
baseline binary (ids and text), so nothing about the model's answers moved.

tools/copyright.py --check clean (both new files carry the full Apache notice); no build-flag change, no
new dependency, no -march=native — the portable path still exists and CI's non-AVX2 machines take it.
ctest attn_math passes (and fails on a deliberately broken portable body: control above).

Where the kernels live, and the test

Follow-up commit a21f1c2 moves both kernels into npu/forward/include/attn_math.h — where this tree
already keeps its SIMD-or-portable primitives (hadamard.h, quant_i8.h), each with a device-free test —
and adds tests/attn_math_test.cpp (ctest attn_math). The test checks both bodies against a
double-precision direct sum over the head dims the forward serves (64/96/128/256/512, 896, 3072) and the
widths where a vector body's tail runs (1..17, 24, 31), and prints which body dot()/saxpy() picked so a
CI log answers the coverage question.

That test exists because otherwise the portable body is dead code on any AVX2 build host, which is what
pr_agent flagged: production would never take it. Control, run and reverted: drop dot_scalar's tail loop
and the test fails on exactly the widths with a remainder (n=1,2,3,5,7,...). The move is behaviour-neutral
by construction and re-measured — greedy output identical to the pre-move binary on the same three prompts.

…MA and splits heads across cores, so a long prefill is not 398 s of scalar math

The per-op forward's attention is host math, and its score loop was a single-accumulator
float reduction.  Without -ffast-math gcc may not reassociate that, so it stays one FMA
latency chain: measured device-free (NPU_INFER_HOST_GEMM=1, the forward's own [bl] attn
timer, GFLOP/s from the exact MAC count) it ran at 8.1 GFLOP/s on the Phi-3.5-mini pack
(32 layers, 32 heads, head_dim 96), which is what a 2048-token prefill spends its 398 s
on while the same prompt's GEMMs cost 2.1 s on the array -- the quadratic term was the
whole prefill, and none of it was the device.

Three parts, each following an idiom already in this tree:
  * dot_f32(): AVX2+FMA 8-wide with a portable four-accumulator fallback, dispatched
    through have_avx2_fma() exactly as npu/forward/include/hadamard.h does it (this
    file is built for the baseline x86-64 ISA, so plain C++ gets 4-lane SSE2);
  * saxpy_f32() for the value accumulation, the other half of the attention flops;
  * the head loop is an OpenMP parallel region over heads -- independent by construction,
    each writes its own ctx rows against a read-only KV cache -- with a per-thread score
    buffer, and short contexts stay serial.

Measured, interleaved on the same box load (ctx 512): attn 6375.3 -> 1682.9 ms,
8.10 -> 30.69 GFLOP/s.  Numerics move by float rounding order only: --dump-logits on the
same prompt gives an identical argmax (2793) and max|dlogit| 1.0e-4 on a 28.5 max logit
(relative 3.6e-6).
@github-actions

github-actions Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit 0fd4b8b)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

671 - Partially compliant

Compliant requirements:

  • Import Ryzen AI OGA NPU model packs on Linux through the engine
  • Parse quantized weights into Q4NX container with layout-version field
  • Self-check dequantises sampled tensors against reference values bit for bit
  • Generate per-shape full ELFs for the pack model's geometry from generator
  • Ensure bit-exactness against CPU reference
  • Gate on first pack (Qwen2.5-0.5B-Instruct npu_4K) with greedy output identical to vendor stack
  • Measure decode tok/s at ctx 128/512/2048 and prefill at 128/2048 side by side with vendor stack
  • Support a second pack from public collection

Non-compliant requirements:

  • No vendor wheel or shared object required, no vendor-compiled NPU program executed

Requires further human verification:

  • Verification of performance claims (27.0 / 17.5 / 5.1 tok/s at ctx 128 / 512 / 2048)
  • Confirmation that the engine's own runtime and kernels are used for execution
⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Potential Performance Regression

The introduction of AVX2+FMA optimizations for attention scoring may introduce a performance regression on CPUs that do not support AVX2/FMA, as the fallback implementation uses a portable four-accumulator loop. This could impact performance on older x86-64 systems.

    const int nt = omp_heads_threads();
#pragma omp parallel num_threads(nt) if (nt > 1 && NH > 1 && (long)T * HD >= 8192)
OpenMP Parallelization Logic

The OpenMP parallelization logic for attention heads includes a condition that only enables parallelization for contexts with a large enough product of T and HD. This condition may not be optimal for all scenarios and could lead to suboptimal performance on smaller contexts.

#pragma omp parallel num_threads(nt) if (nt > 1 && NH > 1 && (long)T * HD >= 8192)

@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 0a86bfdf.

The change is real in the compiled object, not just in the source. Built this head through CMake (ONEBIT_NPU=ON,
Release, thermal-run, 1bit 4.94 MB) and inspected the exact TU:

CMakeCache:  OpenMP_CXX_FLAGS=-fopenmp   OpenMP_CXX_LIB_NAMES=gomp;pthread      (found, so the pragmas are not silently dropped)
q4nx_forward.cpp.o:  17 vfmadd instructions, 3 GOMP references                 (AVX2+FMA path compiled in; the parallel region is a runtime call)
warnings in this TU: exactly one, the pre-existing -Wformat-truncation at :1833 (present before this PR)

That OpenMP was actually found is the check I would have failed this on otherwise: a #pragma omp parallel on a target
built without -fopenmp compiles to serial code and the headline number becomes a mystery.

The parallel region is structurally right: score is a per-thread std::vector<float> allocated inside the region,
#pragma omp for schedule(static) over heads, each head writing only its own ctx rows and reading the read-only KV cache,
and the if (nt > 1 && NH > 1 && (long)T*HD >= 8192) genuinely leaves short contexts serial rather than relying on the
team being cheap.

The "rounding, not value" claim holds, measured on your own code: lifted dot_avx2/dot_f32 verbatim and ran 200,000
unit-ish q·k pairs at HD=96 against a double-precision exact sum —

AVX2/FMA vs double-exact   : worst ABS 3.99e-07   (worst rel 1.75e-02, but that sample's true value is ~0, so relative error is meaningless there)
AVX2     vs portable 4-acc : worst ABS 7.63e-06

So the reassociation moves the last bits of a ~10-magnitude dot by ~1e-7, which is what "different order, same value"
should look like, and it is consistent with your --dump-logits gate reading max|dlogit| ~1e-4 on a 28.5 logit after 32
layers of compounding.

One arithmetic nit. The GFLOP/s columns are MAC/s, not FLOP/s. With T=512, HD=96, 32 heads, 32 layers the exact
MAC count is 100,663,296 per token, which gives 8.08 G MAC/s for the before arm (you report 8.10) and 30.63 for the after
(30.69) — so the figures are internally consistent, and the 3.79x ratio is unaffected. But the conventional count is two
flops per FMA, i.e. 16.2 -> 61.3 GFLOP/s, so anyone comparing these against another tool's GFLOP/s will find a factor of
two. Worth a "(MAC/s)" in the column head; renaming the rows would also make the 2.1 s of npu GEMMs look less anomalous next
to them.

Not re-measured, and neither would mean anything tonight: the host-GEMM timing row (6375.3 -> 1682.9 ms) and the device
rows. The NPU lock is held by another lane's serve and the box has been loaded all night, so both would be numbers about
the box rather than the kernel. The ratio I can see from the code — 8-wide FMA over a scalar latency chain, plus 32
independent heads across cores — makes 3.8x entirely plausible; what I verified is that the mechanism is really there and
that it does not change the answer.

… the portable body never had

The two kernels ARE the fix, so they belong where this tree already keeps its
SIMD-or-portable primitives (npu/forward/include/hadamard.h, quant_i8.h), and
each of those comes with a device-free test.  Moving them makes the portable body
reachable from a test at all: on an AVX2 build host the engine only ever runs
dot_avx2 in production, so without this the four-accumulator path would be dead
code until someone ran the engine on an older machine.

tests/attn_math_test.cpp checks both bodies against a double-precision direct sum
over the head dims the forward serves (64/96/128/256/512, 896, 3072) plus the
widths where a vector body's tail runs (1..17, 24, 31), and it names which body
dot()/saxpy() picked so a CI log answers the coverage question.  The bound is the
arithmetic worst case scaled by the operand magnitudes -- a result-relative bound
is wrong under cancellation, which is how the first version of the test failed a
correct FMA.

Control, run and reverted: drop dot_scalar's tail loop and the test fails on
exactly the widths that have a remainder (n=1,2,3,5,7,...), so it bites.
Behaviour-neutral by construction, and re-measured: greedy output identical to the
pre-move binary on the same three prompts.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Answering the two focus areas from the reviewer guide, both of which the follow-up commit changes:

"Potential performance regression for CPUs that do not support AVX2/FMA." No — the portable path is the
old code plus three more accumulators, so it is strictly faster than what it replaces: the previous loop
was float d = 0.0f; for (i) d += a[i]*b[i];, one FMA latency chain that gcc may not reassociate. Anything
without AVX2 therefore still gets a speedup, just a smaller one (the same 8.1 GFLOP/s baseline measured on
this box before the change would come out of a 4-lane SSE2 build). Nothing is removed for those hosts, and
nothing is selected at build time — have_avx2_fma() is a runtime check.

It is also no longer untested code: tests/attn_math_test.cpp (ctest attn_math) calls dot_scalar and
saxpy_scalar explicitly, so the portable body runs on an AVX2 CI host, which it otherwise never would. The
test names which body dot()/saxpy() picked, so a CI log answers "was the SIMD path covered". Control:
dropping dot_scalar's tail loop makes the test fail on exactly the widths with a remainder.

"The OpenMP if (… T*HD >= 8192) may not be optimal for smaller contexts." That is deliberate, and it is
the shape this file already uses for its GDN head loops: below that threshold the per-layer team costs more
than the work it splits (measured: at ctx 128 the gain came entirely from the four-accumulator dot — 5.6 →
12.9 GFLOP/s — while the head split added nothing), and above it the split is where the 2048-token row's 3.94x
comes from. If someone measures a better crossover on another geometry, the constant is one number in one
line and I would take that patch; I would not move it on a hunch, since the last time this lane trusted a
scaling argument instead of a row it was wrong by two orders of magnitude.

@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 a21f1c2e — my READY at 0a86bfdf carries, and the new test closes the gap I had to work around by hand.

What I had to do last time, this header now does properly. In my previous review the portable body was unreachable
from outside q4nx_forward.cpp (it sits behind the ISA #if), so I transcribed their four-accumulator loop by hand to
compare it against the AVX2 path. The split into dot_scalar/saxpy_scalar + dot/saxpy dispatchers makes it callable,
and tests/attn_math_test.cpp calls both bodies explicitly (:70-74 dot_scalar and dot, :83-84
saxpy_scalar/saxpy) — so the body production never takes on an AVX2 host is the one under test.

The move is a move, checked by normalising both versions and diffing: the SIMD bodies are the same code, the only
differences are the dot_scalar/saxpy_scalar extraction and the static inline x_f32 -> q4nx_attn::x naming the two
call sites in q4nx_forward.cpp:4750,4764 now use.

Built and run (Release, ONEBIT_NPU=ON, thermal-run):

$ ninja -C build attn_math_test          -> rc 0
$ ./build/attn_math_test
dispatch: AVX2+FMA available (dot/saxpy take the SIMD body)
ok: 19 widths, dot and saxpy agree with a double-precision direct sum        rc 0

Widths are the forward's real head dims (64/96/128/256/512…) plus every awkward tail (1,2,3,5,7,8,9,15,16,17,24,31), and
the bound is 4 * eps * sum|a_i b_i| — the arithmetic worst case, which is tight enough to catch an order error and loose
enough not to fail on a legitimate one. That is the right instrument, and better than my hand-rolled probe.

It bites: I broke one accumulator in the portable body ((s0+s1)+(s2-s3)) and rebuilt the test alone —

FAIL: dot_scalar != direct sum (n=5 got=1.74325597 want=1.90228764)
FAIL: dot_scalar != direct sum (n=7 got=0.132466882 want=-0.133967088)      rc 1

restored, green again.

One CI indirection worth stating, because I checked it rather than trusting "CI green on 0a86bfd" — that head
predates the test. attn_math_test is not in ci.yml's Build target list, whose own comment says every target a
ctest test invokes must be listed there. It works anyway: the new add_dependencies(npu_forward_loader_test … attn_math_test) makes it an order-only dependency of a target that is listed, and I proved it by deleting the binary and
building only npu_forward_loader_test — it came back (29,848 B). So ctest will run it. The cost of the indirection is
that the relationship is invisible from the CI file: if npu_forward_loader_test ever leaves that list, this test silently
stops being built and ctest reports "Not Run". One name in the CI list, as the comment asks, would make it explicit.

Last nit, from the move itself: saxpy_scalar no longer carries the #pragma omp simd the old saxpy_f32 fallback had. On
an AVX2 host that path is never taken, so it costs nothing that matters here — but on a host without AVX2/FMA the value
accumulation is now a plain loop where it used to be a vector hint. If it was dropped so the body under test is exactly
the body that runs, that is a good reason; one clause in the comment would say so.

@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit a21f1c2

@bong-water-water-bong
bong-water-water-bong merged commit 54e4e70 into main Nov 6, 2026
8 of 9 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the 1bit/host-attn-simd branch November 6, 2026 11:12
@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 0fd4b8b

bong-water-water-bong added a commit that referenced this pull request Nov 6, 2026
…ixes #803)

Same content as the 13-commit stack on npu/plan-p4-target, re-applied onto
origin/main 7153bed as ONE commit: the branch had accumulated fifteen "merge
origin/main" commits, one per re-gate, and the repo squashes on merge anyway.

  npu(p4): extract the XDNA launch layer behind NpuTarget (engine#799 P4 / #803)
  docs(npu-p4): the Apache-2.0 notice tools/copyright.py requires
  npu(p4): consume P1's plan loader in NpuTarget::open instead of duplicating the derivation
  npu(p4): the LM head falls back through ctx_for(), so a set with no M=16 twins still runs
  npu(p4): the pb16i role split is the target's state, so setup asks it instead of assigning
  npu(p4): the kernel family is the forward's to name, so open() takes it
  npu(p4): the rotation is one implementation, so the target calls hadamard.h too
  npu(p4): the head's ternary flag is head_pb16i_, not a self-reference
  npu(p4): the rebase put a_k in the wkey/sc slots, so pass all three as main does
  docs(npu-p4): name the gemv family's boundary in A1, now that #885 is in the rebase
  npu(p4): the m16 debug comparison takes its difference at int64 width
  npu(p4): the target headers take npu-relative includes, so CI's syntax target compiles them
  chore: re-trigger CI

Rebased rather than merged this time, because the merge caravan is what has
been voiding the gate: each "merge origin/main" moved the head, so fourteen
pairings were spent keeping a table honest against a tree that kept moving.
The split's own files are byte-identical to the reviewed ones (blob check in
the PR): npu/target/target.h, npu/target/xdna/*, npu/forward/include/q4nx_lh.h,
docs/npu-p4-target-split.md. The three that differ are the three main changed:
CMakeLists.txt (main's test registrations), and q4nx_forward.{h,cpp}, which
now carry main's newer forward work (#1243's AVX2/FMA attention, #1266's MoE
container) *on top of* the split -- verified by grepping the moved-in symbols
in the rebased file, not by trusting the clean merge.

Nothing in here changes numerics: the device and launch layer moved, the 38
launch sites became role-based calls, and the model math stayed where it was.
bong-water-water-bong added a commit that referenced this pull request Nov 6, 2026
…ixes #803)

Same content as the 13-commit stack on npu/plan-p4-target, re-applied onto
origin/main 7153bed as ONE commit: the branch had accumulated fifteen "merge
origin/main" commits, one per re-gate, and the repo squashes on merge anyway.

  npu(p4): extract the XDNA launch layer behind NpuTarget (engine#799 P4 / #803)
  docs(npu-p4): the Apache-2.0 notice tools/copyright.py requires
  npu(p4): consume P1's plan loader in NpuTarget::open instead of duplicating the derivation
  npu(p4): the LM head falls back through ctx_for(), so a set with no M=16 twins still runs
  npu(p4): the pb16i role split is the target's state, so setup asks it instead of assigning
  npu(p4): the kernel family is the forward's to name, so open() takes it
  npu(p4): the rotation is one implementation, so the target calls hadamard.h too
  npu(p4): the head's ternary flag is head_pb16i_, not a self-reference
  npu(p4): the rebase put a_k in the wkey/sc slots, so pass all three as main does
  docs(npu-p4): name the gemv family's boundary in A1, now that #885 is in the rebase
  npu(p4): the m16 debug comparison takes its difference at int64 width
  npu(p4): the target headers take npu-relative includes, so CI's syntax target compiles them
  chore: re-trigger CI

Rebased rather than merged this time, because the merge caravan is what has
been voiding the gate: each "merge origin/main" moved the head, so fourteen
pairings were spent keeping a table honest against a tree that kept moving.
The split's own files are byte-identical to the reviewed ones (blob check in
the PR): npu/target/target.h, npu/target/xdna/*, npu/forward/include/q4nx_lh.h,
docs/npu-p4-target-split.md. The three that differ are the three main changed:
CMakeLists.txt (main's test registrations), and q4nx_forward.{h,cpp}, which
now carry main's newer forward work (#1243's AVX2/FMA attention, #1266's MoE
container) *on top of* the split -- verified by grepping the moved-in symbols
in the rebased file, not by trusting the clean merge.

Nothing in here changes numerics: the device and launch layer moved, the 38
launch sites became role-based calls, and the model math stayed where it was.

One row of the gate was a citation rather than a check, and is now a check: §4 item 4 asks for
`--npu-target xdna` as the default with an unknown name refused by name, and A1 had no such
option at all -- the name appeared only in a comment in npu/target/target.h and in the design
doc, so the earlier "PASS: from the A1 design row" was a claim about the document. The flag now
exists: `forward-serve --npu-target <name>` (defaulting to XdnaTarget::kName), `serve` carries
it through to that child, and an unknown name is refused **before the device is opened**, which
is what makes the row measurable without a ticket.
bong-water-water-bong added a commit that referenced this pull request Nov 6, 2026
…ixes #803)

Same content as the 13-commit stack on npu/plan-p4-target, re-applied onto
origin/main 7153bed as ONE commit: the branch had accumulated fifteen "merge
origin/main" commits, one per re-gate, and the repo squashes on merge anyway.

  npu(p4): extract the XDNA launch layer behind NpuTarget (engine#799 P4 / #803)
  docs(npu-p4): the Apache-2.0 notice tools/copyright.py requires
  npu(p4): consume P1's plan loader in NpuTarget::open instead of duplicating the derivation
  npu(p4): the LM head falls back through ctx_for(), so a set with no M=16 twins still runs
  npu(p4): the pb16i role split is the target's state, so setup asks it instead of assigning
  npu(p4): the kernel family is the forward's to name, so open() takes it
  npu(p4): the rotation is one implementation, so the target calls hadamard.h too
  npu(p4): the head's ternary flag is head_pb16i_, not a self-reference
  npu(p4): the rebase put a_k in the wkey/sc slots, so pass all three as main does
  docs(npu-p4): name the gemv family's boundary in A1, now that #885 is in the rebase
  npu(p4): the m16 debug comparison takes its difference at int64 width
  npu(p4): the target headers take npu-relative includes, so CI's syntax target compiles them
  chore: re-trigger CI

Rebased rather than merged this time, because the merge caravan is what has
been voiding the gate: each "merge origin/main" moved the head, so fourteen
pairings were spent keeping a table honest against a tree that kept moving.
The split's own files are byte-identical to the reviewed ones (blob check in
the PR): npu/target/target.h, npu/target/xdna/*, npu/forward/include/q4nx_lh.h,
docs/npu-p4-target-split.md. The three that differ are the three main changed:
CMakeLists.txt (main's test registrations), and q4nx_forward.{h,cpp}, which
now carry main's newer forward work (#1243's AVX2/FMA attention, #1266's MoE
container) *on top of* the split -- verified by grepping the moved-in symbols
in the rebased file, not by trusting the clean merge.

Nothing in here changes numerics: the device and launch layer moved, the 38
launch sites became role-based calls, and the model math stayed where it was.

One row of the gate was a citation rather than a check, and is now a check: §4 item 4 asks for
`--npu-target xdna` as the default with an unknown name refused by name, and A1 had no such
option at all -- the name appeared only in a comment in npu/target/target.h and in the design
doc, so the earlier "PASS: from the A1 design row" was a claim about the document. The flag now
exists: `forward-serve --npu-target <name>` (defaulting to XdnaTarget::kName), `serve` carries
it through to that child, and an unknown name is refused **before the device is opened**, which
is what makes the row measurable without a ticket.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

CI note, so the red pr_agent check is not read as a code finding: the job ran, published its review comment, and was then killed — ##[error]Process completed with exit code 137, followed by The runner has received a shutdown signal. It also points OPENAI__API_BASE at the box's local qwen3-coder serve on :8090, so a runner restart takes it down with it. Everything else on this PR is green: build 5m37s, CodeQL, all four Analyze legs, and ctest attn_math locally. #1290's equivalent job has been queued 2h behind the same self-hosted, pr-agent runner.

bong-water-water-bong added a commit that referenced this pull request Nov 6, 2026
…ixes #803)

Same content as the 13-commit stack on npu/plan-p4-target, re-applied onto
origin/main 7153bed as ONE commit: the branch had accumulated fifteen "merge
origin/main" commits, one per re-gate, and the repo squashes on merge anyway.

  npu(p4): extract the XDNA launch layer behind NpuTarget (engine#799 P4 / #803)
  docs(npu-p4): the Apache-2.0 notice tools/copyright.py requires
  npu(p4): consume P1's plan loader in NpuTarget::open instead of duplicating the derivation
  npu(p4): the LM head falls back through ctx_for(), so a set with no M=16 twins still runs
  npu(p4): the pb16i role split is the target's state, so setup asks it instead of assigning
  npu(p4): the kernel family is the forward's to name, so open() takes it
  npu(p4): the rotation is one implementation, so the target calls hadamard.h too
  npu(p4): the head's ternary flag is head_pb16i_, not a self-reference
  npu(p4): the rebase put a_k in the wkey/sc slots, so pass all three as main does
  docs(npu-p4): name the gemv family's boundary in A1, now that #885 is in the rebase
  npu(p4): the m16 debug comparison takes its difference at int64 width
  npu(p4): the target headers take npu-relative includes, so CI's syntax target compiles them
  chore: re-trigger CI

Rebased rather than merged this time, because the merge caravan is what has
been voiding the gate: each "merge origin/main" moved the head, so fourteen
pairings were spent keeping a table honest against a tree that kept moving.
The split's own files are byte-identical to the reviewed ones (blob check in
the PR): npu/target/target.h, npu/target/xdna/*, npu/forward/include/q4nx_lh.h,
docs/npu-p4-target-split.md. The three that differ are the three main changed:
CMakeLists.txt (main's test registrations), and q4nx_forward.{h,cpp}, which
now carry main's newer forward work (#1243's AVX2/FMA attention, #1266's MoE
container) *on top of* the split -- verified by grepping the moved-in symbols
in the rebased file, not by trusting the clean merge.

Nothing in here changes numerics: the device and launch layer moved, the 38
launch sites became role-based calls, and the model math stayed where it was.

One row of the gate was a citation rather than a check, and is now a check: §4 item 4 asks for
`--npu-target xdna` as the default with an unknown name refused by name, and A1 had no such
option at all -- the name appeared only in a comment in npu/target/target.h and in the design
doc, so the earlier "PASS: from the A1 design row" was a claim about the document. The flag now
exists: `forward-serve --npu-target <name>` (defaulting to XdnaTarget::kName), `serve` carries
it through to that child, and an unknown name is refused **before the device is opened**, which
is what makes the row measurable without a ticket.
bong-water-water-bong added a commit that referenced this pull request Nov 6, 2026
…ixes #803)

Same content as the 13-commit stack on npu/plan-p4-target, re-applied onto
origin/main 7153bed as ONE commit: the branch had accumulated fifteen "merge
origin/main" commits, one per re-gate, and the repo squashes on merge anyway.

  npu(p4): extract the XDNA launch layer behind NpuTarget (engine#799 P4 / #803)
  docs(npu-p4): the Apache-2.0 notice tools/copyright.py requires
  npu(p4): consume P1's plan loader in NpuTarget::open instead of duplicating the derivation
  npu(p4): the LM head falls back through ctx_for(), so a set with no M=16 twins still runs
  npu(p4): the pb16i role split is the target's state, so setup asks it instead of assigning
  npu(p4): the kernel family is the forward's to name, so open() takes it
  npu(p4): the rotation is one implementation, so the target calls hadamard.h too
  npu(p4): the head's ternary flag is head_pb16i_, not a self-reference
  npu(p4): the rebase put a_k in the wkey/sc slots, so pass all three as main does
  docs(npu-p4): name the gemv family's boundary in A1, now that #885 is in the rebase
  npu(p4): the m16 debug comparison takes its difference at int64 width
  npu(p4): the target headers take npu-relative includes, so CI's syntax target compiles them
  chore: re-trigger CI

Rebased rather than merged this time, because the merge caravan is what has
been voiding the gate: each "merge origin/main" moved the head, so fourteen
pairings were spent keeping a table honest against a tree that kept moving.
The split's own files are byte-identical to the reviewed ones (blob check in
the PR): npu/target/target.h, npu/target/xdna/*, npu/forward/include/q4nx_lh.h,
docs/npu-p4-target-split.md. The three that differ are the three main changed:
CMakeLists.txt (main's test registrations), and q4nx_forward.{h,cpp}, which
now carry main's newer forward work (#1243's AVX2/FMA attention, #1266's MoE
container) *on top of* the split -- verified by grepping the moved-in symbols
in the rebased file, not by trusting the clean merge.

Nothing in here changes numerics: the device and launch layer moved, the 38
launch sites became role-based calls, and the model math stayed where it was.

One row of the gate was a citation rather than a check, and is now a check: §4 item 4 asks for
`--npu-target xdna` as the default with an unknown name refused by name, and A1 had no such
option at all -- the name appeared only in a comment in npu/target/target.h and in the design
doc, so the earlier "PASS: from the A1 design row" was a claim about the document. The flag now
exists: `forward-serve --npu-target <name>` (defaulting to XdnaTarget::kName), `serve` carries
it through to that child, and an unknown name is refused **before the device is opened**, which
is what makes the row measurable without a ticket.
bong-water-water-bong added a commit that referenced this pull request Nov 7, 2026
…808)

* npu: extract the XDNA launch layer behind NpuTarget (engine#799 P4, fixes #803)

Same content as the 13-commit stack on npu/plan-p4-target, re-applied onto
origin/main 7153bed as ONE commit: the branch had accumulated fifteen "merge
origin/main" commits, one per re-gate, and the repo squashes on merge anyway.

  npu(p4): extract the XDNA launch layer behind NpuTarget (engine#799 P4 / #803)
  docs(npu-p4): the Apache-2.0 notice tools/copyright.py requires
  npu(p4): consume P1's plan loader in NpuTarget::open instead of duplicating the derivation
  npu(p4): the LM head falls back through ctx_for(), so a set with no M=16 twins still runs
  npu(p4): the pb16i role split is the target's state, so setup asks it instead of assigning
  npu(p4): the kernel family is the forward's to name, so open() takes it
  npu(p4): the rotation is one implementation, so the target calls hadamard.h too
  npu(p4): the head's ternary flag is head_pb16i_, not a self-reference
  npu(p4): the rebase put a_k in the wkey/sc slots, so pass all three as main does
  docs(npu-p4): name the gemv family's boundary in A1, now that #885 is in the rebase
  npu(p4): the m16 debug comparison takes its difference at int64 width
  npu(p4): the target headers take npu-relative includes, so CI's syntax target compiles them
  chore: re-trigger CI

Rebased rather than merged this time, because the merge caravan is what has
been voiding the gate: each "merge origin/main" moved the head, so fourteen
pairings were spent keeping a table honest against a tree that kept moving.
The split's own files are byte-identical to the reviewed ones (blob check in
the PR): npu/target/target.h, npu/target/xdna/*, npu/forward/include/q4nx_lh.h,
docs/npu-p4-target-split.md. The three that differ are the three main changed:
CMakeLists.txt (main's test registrations), and q4nx_forward.{h,cpp}, which
now carry main's newer forward work (#1243's AVX2/FMA attention, #1266's MoE
container) *on top of* the split -- verified by grepping the moved-in symbols
in the rebased file, not by trusting the clean merge.

Nothing in here changes numerics: the device and launch layer moved, the 38
launch sites became role-based calls, and the model math stayed where it was.

One row of the gate was a citation rather than a check, and is now a check: §4 item 4 asks for
`--npu-target xdna` as the default with an unknown name refused by name, and A1 had no such
option at all -- the name appeared only in a comment in npu/target/target.h and in the design
doc, so the earlier "PASS: from the A1 design row" was a claim about the document. The flag now
exists: `forward-serve --npu-target <name>` (defaulting to XdnaTarget::kName), `serve` carries
it through to that child, and an unknown name is refused **before the device is opened**, which
is what makes the row measurable without a ticket.

* npu(p4): the host fallback pads its activations too, so a padded design cannot be read past its buffer

Review of #808 found the regression this move introduced: main pads A from the design's real_k
up to K before branching, and the split moved that pad into XdnaTarget while leaving the host
branch of npu_gemm()/npu_gemm_rows() on the raw A. At a padded design (0 < real_k < K, e.g.
hidden 896 stored at K=1024) the host matvec then read A[real_k..K) past the caller's buffer,
and the rows form read at stride K from a buffer laid out at stride real_k -- every row after
the first was the wrong row as well as an overrun. It fires under NPU_INFER_HOST_GEMM=1/init_host,
which is #796 rung 1's reference path.

The pad and the multiply are one decision, so they now live in one function:
q4nx_host_gemm_f32_padded() (q4nx_pack.{h,c}) zero-fills the tail into scratch and runs the loop
at stride K; both host branches are one call to it, so no caller can take the read without the pad.
a_k <= 0 (the MLA designs) and a_k >= K keep their old path exactly.

tests/host_gemm_pad_test.c (ctest host_gemm_pad) pins it with a NaN guard tail after the activation
buffer, so an implementation that reads past the buffer fails even when its numbers look plausible.
Checked by breaking the code rather than by watching it pass: with the pad disabled it reports
'worst |d| 60' and 'got 0 want 1' on the guard for the 896-of-1024 case, and passes once restored.

Also: the design doc now records that the engine#666 canary retry is conditional on !ctx.gemv
because readback() only verifies for a non-gemv context -- not a dropped safety, and worth
saying so where a reader will look.

* ci: bind host_gemm_pad_test to a target CI already builds, so ctest runs it

ci.yml names its build targets explicitly and needs the `workflow` scope to extend, which this lane's
token does not have. Without the binding the new row reports 'Not Run' and the job fails after 106 tests
have passed -- which is exactly what happened on f605dbe. Same mechanism as hadamard_rotate_test and
attn_math_test on the line above.

---------

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