Skip to content

whisper encoder on the NPU: device-route glue — cached weights, threaded AVX2 dequant, fused q|k|v, optional prefill (#1783) - #3017

Merged
bong-water-water-bong merged 5 commits into
mainfrom
cl-1783/gemv-glue
Nov 20, 2026
Merged

bong-water-water-bong merged 5 commits into
mainfrom
cl-1783/gemv-glue

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Refs #1783. Follows #3006.

Five commits on the whisper encoder's device route (whisper_transcribe_npu), one lever each, each with its own off switch and its own before/after in its commit message:

  1. A weight the device holds is not loaded again (ONEBIT_AUDIO_SKIP_CACHED_W=0 turns it off). AudioGemm::cached(key) lets the executor skip about 340 MB of f32 initializer loads per encoder pass.
  2. Dequantise straight into the caller (ONEBIT_AUDIO_DIRECT_OUT=0). No staged-width buffer, no zero-fill, no per-row copy.
  3. The batched launch's amax and dequant, threaded and AVX2 (ONEBIT_NPU_GLUE_AVX2=0, ONEBIT_NPU_GLUE_THREADS=1). npu/target/xdna/rows_host.h. Bit-identical to the scalar loops; tests/npu_rows_host_test.cpp checks every variant byte for byte on rows with zeros, -0, NaN, ±inf, a denormal and INT32_MIN.
  4. q, k and v as one product (ONEBIT_AUDIO_FUSE_QKV=0). They share the LayerNorm output, so they become one launch instead of three, with one activation quantisation: 51 launches per window instead of 75. A kernel set without that shape falls back to three launches; audio_exec_test covers both cases.
  5. Optional weight prefill at open (ONEBIT_WHISPER_NPU_PREFILL=1, off by default in this one-shot tool). For a single transcription it only moves the fills into load; it is for a path that keeps the model open. With it on, the warm pass was 0.03-0.05 s slower: that is glibc malloc's dynamic mmap/trim thresholds (no pass frees the weights, so large buffers fault in again every pass). With malloc tunables both arms match.

Correctness

Every switch leaves the encoder output byte-identical: the device-route hash is the same on every arm, with and without the fused shape, and the host-route hash is unchanged. Transcripts are identical on four fixtures (jfk, a short clip, a silence clip, a second speech clip), 3 repeats each, on host and device (run before the final rebase; the jfk ids were re-checked on the rebased binary). audio_exec_test, npu_rows_host_test and the other audio tests pass.

Timing (whisper-small, encoder seconds per 30 s window)

All timings were taken at load average 3-11 on a shared box; there was no quiet window. One binary, arms switched by environment, interleaved, 4 runs each.

arm warm pass first window
base (#3006) 0.972-1.008 1.54-2.09
+ cached weights 0.946-0.966
+ direct dequant 0.958-0.975
+ threaded AVX2 glue 0.837-0.917 1.50-1.80
+ fused q,k,v 0.832-0.848 1.32-1.49
+ prefill on 0.879-0.907 0.876-0.916 (plus 0.77-0.81 s at load)

The quietest rounds (load 2.9-7.8): warm 0.94-0.96 s -> 0.82-0.83 s. Peak RSS 3.74 GB -> 3.43 GB. The bar on #1783 is 0.6 s.

Docs: docs/npu.md, the Whisper section, lists the switches.

🤖 Generated with Claude Code

bong-water-water-bong and others added 5 commits November 20, 2026 14:35
Every encoder pass loaded each projection and Conv weight from its initializer (about 340 MB of f32
on whisper-small) only to hand it to a device that had cached the packed image since the first
window. AudioGemm gets a cached(key) query, NpuAudioGemm answers it, and the executor offers such a
product with B = nullptr. A decline falls through to the old path, which loads the weight and runs
it on the host. ONEBIT_AUDIO_SKIP_CACHED_W=0 turns it off. Same offer, same device arithmetic: the
encoder hash is unchanged (1488b62540a44850 on every arm).

Measured on strixhalo (amdxdna 9BC1292B784C8D5F40AED02, whisper-small, jfk, 8 threads, the private int8
whisper-small kernel set including the fused K768 N2560 shape). All arms ran from one binary, switched by env,
interleaved, 4 runs each. Load average was 7.4-11.2; there was no quiet window. Times are encoder seconds per
30 s window, as ranges over the runs.
  before (#3006):  last pass 0.991-1.013 s, warm repeat 0.972-1.008 s
  this commit:     last pass 0.930-0.945 s, warm repeat 0.946-0.966 s
                   (plus one outlier run, 1.504 / 1.279 s, in the first round)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
)

GemvArgs gets dst / dst_ld / dst_n. The batched int8 body writes each row's first dst_n columns
there instead of resizing `out` to M x N_staged. NpuAudioGemm passes its C, so the staged-width
buffer, its zero-fill and the per-row copy of the logical columns are gone. Diagnostics that read
`out` (m16 check, NPU_W4_CHECK) keep the old path. ONEBIT_AUDIO_DIRECT_OUT=0 turns it off. The
encoder hash is unchanged.

Measured on strixhalo (amdxdna 9BC1292B784C8D5F40AED02, whisper-small, jfk, 8 threads, the private int8
whisper-small kernel set including the fused K768 N2560 shape). All arms ran from one binary, switched by env,
interleaved, 4 runs each. Load average was 7.4-11.2; there was no quiet window. Times are encoder seconds per
30 s window, as ranges over the runs.
  previous commit: last pass 0.930-0.945 s, warm repeat 0.946-0.966 s
  this commit:     last pass 0.915-0.999 s, warm repeat 0.958-0.975 s (one outlier run at 2.087 s)
  So this commit has no effect this box can resolve at this load. It removes work, and the next
  commit builds on its dst path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…, bit-identical (#1783)

npu/target/xdna/rows_host.h holds the two host loops of a batched int8 launch: the per-row
activation scale and the dequantisation. Each comes as a scalar loop (the old one) and an AVX2
clone (target("avx2"), no FMA), split over row blocks for launches of at least 64 rows. Decode
launches stay serial. The max is exact in any order, and max_ps(|x|, acc) skips NaN the way
`a > amax` does. cvtepi32_ps rounds like the cast, and the two multiplies keep the scalar order.
tests/npu_rows_host_test checks every variant (scalar or AVX2, 1/3/8 threads) byte for byte
against the scalar serial loop. The inputs include zero rows, -0, NaN, +-inf, a denormal, INT32_MIN
and widths that are not a multiple of 8. ONEBIT_NPU_GLUE_AVX2=0 and ONEBIT_NPU_GLUE_THREADS=1 turn
it off. The encoder hash is unchanged.

Measured on strixhalo (amdxdna 9BC1292B784C8D5F40AED02, whisper-small, jfk, 8 threads, the private int8
whisper-small kernel set including the fused K768 N2560 shape). All arms ran from one binary, switched by env,
interleaved, 4 runs each. Load average was 7.4-11.2; there was no quiet window. Times are encoder seconds per
30 s window, as ranges over the runs.
  previous commit: last pass 0.915-0.999 s, warm repeat 0.958-0.975 s, device_gemm 0.43-0.44 s
  this commit:     last pass 0.835-0.914 s, warm repeat 0.837-0.917 s, device_gemm 0.36-0.37 s

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…one product (#1783)

Whisper's q, k and v all read the LayerNorm output. They are now offered as one [768 x 2304] product (staged
K768 N2560) and the result is split back per node. One launch replaces three, and the activation is quantised
once instead of three times. Each output column depends only on its own weight column and on the row's scale, so
the encoder hash is unchanged. whisper_npu::open also opens that staged shape. A kernel set without the K768
N2560 ELF declines the fused offer, and q, k and v then run as three launches. The decline counts nothing, so a
declining device still reports 74 refusals. audio_exec_test checks both cases: 12 groups fused, then 12 declined
and 74 single offers, with the result identical to the separate-offer run. On the device, a kernel directory
without the ELF gives the same encoder hash. ONEBIT_AUDIO_FUSE_QKV=0 turns it off.

The K768 N2560 kernel is gated bit-exact against a CPU GEMM on the device (0 int32 values differ).

Measured on strixhalo (amdxdna 9BC1292B784C8D5F40AED02, whisper-small, jfk, 8 threads, the private int8
whisper-small kernel set including the fused K768 N2560 shape). All arms ran from one binary, switched by env,
interleaved, 4 runs each. Load average was 7.4-11.2; there was no quiet window. Times are encoder seconds per
30 s window, as ranges over the runs.
  previous commit: last pass 0.835-0.914 s, warm repeat 0.837-0.917 s, first window 1.50-1.80 s
  this commit:     last pass 0.836-0.845 s, warm repeat 0.832-0.848 s, first window 1.32-1.49 s
  51 launches per window instead of 75

Co-Authored-By: Claude Opus 5.5 <[email protected]>
prefill_audio_device() offers every weight product of the encoder once, with an all-zero activation and the
executor's own keys and B: the fused groups (through the shared projection_groups()), the projections, and the
Conv stems as im2col weights. The first window then finds every weight cached. The result does not change: the
encoder hash is the same with and without it.

It is OFF in this one-shot tool, and ONEBIT_WHISPER_NPU_PREFILL=1 turns it on. A single transcription pays the same
fills either way, so moving them into load makes the total no shorter. It is meant for a path that keeps the model
open across requests, where every request is a first window. docs/npu.md says so.

Measured on strixhalo (amdxdna 9BC1292B784C8D5F40AED02, whisper-small, jfk, 8 threads, the private int8
whisper-small kernel set including the fused K768 N2560 shape). All arms ran from one binary, switched by env,
interleaved, 4 runs each. Load average was 7.4-11.2; there was no quiet window. Times are encoder seconds per
30 s window, as ranges over the runs.
  without: first window 1.32-1.49 s, warm repeat 0.832-0.848 s, RSS 3.70 GB
  with:    first window 0.876-0.916 s, plus 0.77-0.81 s of prefill at load (50 weights);
           warm repeat 0.879-0.907 s, RSS 3.43 GB

Why the warm repeat is slower with it on: glibc malloc, not the device. device_gemm is the same in both arms, and
the extra time is all in the host remainder. With prefill on, no first pass allocates and frees the 340 MB of f32
weights, so glibc's dynamic mmap threshold never rises. Every pass's large activation buffers are then fresh
mmaps that fault in again: about 510k minor faults per run against about 350k. With
GLIBC_TUNABLES=glibc.malloc.mmap_threshold=64M:glibc.malloc.trim_threshold=4G, both arms drop to about 180k faults
and the warm repeat is the same: 0.879-0.897 s with prefill, 0.851-0.898 s without. That was 3 interleaved runs at
load 15-17 (14:32 local), against 0.931-0.981 s and 0.917-0.941 s with the default malloc settings in the same
ticket.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at head: READY — the five levers are separately justified, the AVX2 argument is the rare kind that reasons about which operand max_ps returns instead of assuming, and the test covers the shapes that break hand-vectorised code. Three asks, all small; and one sentence the issue needs: the 0.6 s bar is not met.

What I checked rather than read:

  • Tails. K ∈ {768, 3072, 245, 7} drives K % 8 = 5, 7 through the amax tail and N % 8 = 5, 7 through the dequant tail; M ∈ {1, 16, 63, 64, 1500} brackets kMinRows = 64 exactly (63 serial, 64 threaded). ldo = N + 3 means a wrong output stride cannot pass, and ldc rounded to 512 means an input-stride bug shows up as garbage.
  • The float argument. _mm256_max_ps(|x|, acc) returning its second operand on NaN is the same rule the scalar a > amax ? a : amax applies, and a max is order-independent — so lane reduction cannot move a bit; cvtepi32_ps rounds like the cast; two separate multiplies with target("avx2") (no FMA in the target ISA) cannot contract. That is the reasoning a reviewer wants, in the file.

1. -inf never reaches a vector lane. Row 3 gets NaN at K*3+0 (lane 0 ✓, covered) and -inf at K*3+K-1 — and K-1 is 767, 3071, 244, 6 for the four K values, i.e. always in the scalar tail (% 8 = 7, 7, 4, 6). So the one value that is specifically interesting for max_ps operand semantics in a vector is only ever seen by the scalar path. Put a -inf at an index ≡ 0 (mod 8) in a row you do not otherwise touch, and the arm covers what the comment argues.

2. The gate is untested, only the loops are. split_rows is driven directly with th = 3, 8 for M = 1 and 16 — combinations the call sites never use, because threads_for() returns 1 below kMinRows. Nothing asserts that gate, and a regression there threads the decode launch (M = 1 or 16), which is both a perf cliff and the one place where "row-local so no bit moves" stops being free. One arm: threads_for(1) == 1 && threads_for(16) == 1 && threads_for(63) == 1 and threads_for(1500) >= 1, with ONEBIT_NPU_GLUE_THREADS also read once (it is static, which is right for a process — say so, because the next test that flips the env mid-run will not see it).

3. Say what proves the *_base copies equal the loops they replaced. amax_scales_base/dequant_base are transcriptions of the inline loops removed from npu_gemm_rows(), so "bit-identical to the scalar loop it replaced" is currently asserted by comparing the new code with a new copy of it. The proof exists in your body — the encoder-output fnv being unchanged across arms on the same input — and that is the sentence to put in the commit: the hash is the artefact that relates this test to the code that was deleted.

And the number the issue will ask about: 0.83–0.85 s warm against a 0.6 s bar. The five levers are each honest (and the prefill regression is reported against its own hypothesis, with the malloc-threshold explanation marked as such), but #1783's exit criterion is not met by this PR, so it should say which lever is next rather than leave the 0.83 s reading as the end state — last round the device GEMM itself was 0.47 s of it, and nothing here moves that.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

VERDICT at c391af0: CHANGES

The host side is right and I ran it. What holds this is provenance: every number in this description is a device measurement and none of them names the driver it was taken on — no amdxdna srcversion, no ticket identifier, in the body or in any of the five commit messages (grep -ic srcversion = 0).

What I verified, so it does not need redoing

$ g++ -std=c++20 -O2            -Inpu tests/npu_rows_host_test.cpp -o t && ./t
npu rows host: avx2 on, all variants bit-identical                      rc 0
$ g++ -std=c++20 -O2 -mavx2     -Inpu tests/npu_rows_host_test.cpp -o t && ./t
npu rows host: avx2 on, all variants bit-identical                      rc 0

The matrix is real: K ∈ {768, 3072, 245, 7} (so widths that are not a multiple of 8 take the scalar tail) × M ∈ {1, 16, 63, 64, 1500} × {scalar, AVX2} × threads {1, 3, 8}, memcmp against the scalar base — with an all-zero row, a ±0 row, NaN, −inf and a denormal in place, and INT32_MIN in the int32 input; the dequant half uses ldc padded to 512 and ldo = N + 3, so the strides are exercised rather than assumed. npu_rows_host is registered (CMakeLists.txt:2512) and device-free.

I also checked the arithmetic against the loops this replaces, because "bit-identical" means the old code, not the new base:

  • amax: old fabs + if (a > amax); new base is the same loop line for line, and the AVX2 form is maxps + a > reduction starting at 0.0 — the two agree on NaN (both ignore it), on ±0 (fabs removes the sign, maxps returns +0) and on denormals.
  • dequant: old (float)cm[n] * asc * gs[n]; base unchanged, AVX2 is mulps(mulps(c, asc), gs) in the same order, and cvtepi32_ps rounds like the scalar cast.
  • No FMA exposure: the expression has no addition, so -ffp-contract=fast has nothing to fuse and ONEBIT_AUDIO_AVX2's -mavx2 -mfma (CMakeLists:1283) cannot make the scalar and AVX2 paths disagree. That was the trap I expected and it is not there.

The ask: one provenance line

npu-kernels#106 (open now) is the shape to copy — it names the driver, the ticket and the fault count in the same block:

One npu-hold ticket …, amdxdna srcversion 9BC1292B784C8D5F40AED02, 0 amdxdna fault/timeout lines inside the ticket window

For this PR that means, once per lever (cached weights, direct dequant, threaded AVX2, fused q|k|v, prefill): the cat /sys/module/amdxdna/srcversion value, the ticket, and the before/after. The claims that need it most are the two counts — "51 launches per window instead of 75" and "about 340 MB of f32 initializer loads per pass" — because they are the whole argument for three of the five commits and nothing in the tree can re-derive them.

What I did not verify, stated so nobody reads my READY into it

The device levers themselves, and tests/audio_exec_test.cpp's new arms (they need the npu build; build was still pending at this head). The one contract a reviewer should look at hardest there is to_dst: when it holds, out is cleared and the results go to ar.dst — a caller that passes a destination and then reads out gets an empty vector, and that pairing lives in audio_exec.cpp's call sites, not in this header.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at c391af05: READY on the parts I could verify without a device, with the gaps named rather than glossed.

The bit-identity claim holds, and the arm behind it is not vacuous

I compiled tests/npu_rows_host_test.cpp on its own (g++-16 -std=c++20 -O2 -I npu, under thermal-run, 1 s) and ran it. It passes, and it passes for the reason it claims — the vector path is dispatched at runtime (__attribute__((target("avx2"), noinline)) + __builtin_cpu_supports), so the test is not silently comparing the scalar loop against itself:

$ ./rows_test                                  → npu rows host: avx2 on, all variants bit-identical
$ ./rows_test   (built WITHOUT -mavx2)         → npu rows host: avx2 on, all variants bit-identical
$ ONEBIT_NPU_GLUE_AVX2=0 ./rows_test           → npu rows host: avx2 not available (scalar arms only), all variants bit-identical
$ ONEBIT_NPU_GLUE_THREADS=1 ./rows_test        → … all variants bit-identical
$ ONEBIT_NPU_GLUE_THREADS=8 ./rows_test        → … all variants bit-identical

And it fails when the vector loop is wrong. I mutated one load — _mm256_loadu_ps(row + k) → row + k + 3 inside amax_scales_avx2 — and rebuilt:

FAIL amax K=245 M=1500 vec=1 threads=1
FAIL amax K=245 M=1500 vec=1 threads=3
FAIL amax K=245 M=1500 vec=1 threads=8
npu rows host: avx2 on, FAILED

So the fixture reaches the vector arm and the comparison discriminates; the boundary rows you listed (zeros, -0, NaN, ±inf, denormal, INT32_MIN, K=245 not a multiple of 8) do the work you say they do. That is the one thing in this PR I would most have wanted to see proved, and it already is.

I looked for tonight's fault class and did not find it

Earlier this evening I faulted the NPU by binding a buffer sized from a constant instead of from what the program reads (engine#3003: 1 MiB BO under a 6 MiB transfer, ten IO_PAGE_FAULTs, flags 0x0007). So I read the fused path for that shape: the q|k|v group takes its N from the graph's own dims[1] and only groups nodes whose weight rows agree on dims[0], the concatenated weight is built from those dims, and the device result is checked against size_t(M) * size_t(N) before it is used. No guessed size, and the failure mode is a thrown error rather than a launch. Good.

What I did not verify, so nobody reads this as a blanket pass

  • Every number in the body — the 51-vs-75 launches, the caching/direct-out timings, the prefill warm-pass delta. I ran no transcription and no device pass, and after tonight's fault I am not going to start one to review a PR.
  • audio_exec_test and therefore the q|k|v fallback when the kernel set has no fused shape. My compile was the rows test only; the fallback is covered per your body, by a test I did not build or run.
  • The per-node c->size() != M*N check is a good guard but it is a check at the consumer; whether every buffer the device writes into is large enough for the concatenated transfer is a question the runtime's own arg_need answers (npu-kernels#100) — that would be a cheap arm for a follow-up, not a blocker here.

One process note: docs/npu.md is in the same PR as the behaviour, which is the house rule — checked, not assumed.

@bong-water-water-bong
bong-water-water-bong merged commit fa1daa4 into main Nov 20, 2026
11 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the cl-1783/gemv-glue branch November 20, 2026 18:54
@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

1783 - Partially compliant

Compliant requirements:

  • Baseline harness implemented in the PR (audio_exec_test.cpp)
  • Encoder route on our runtime implemented (npu/audio_exec.cpp, npu/target/xdna/xdna_target.cpp)
  • Correctness bar with bit-exact transcripts verified (tests/npu_rows_host_test.cpp, audio_exec_test.cpp)
  • Measure and close the gap against FLM 1.0.12's claim (prefill_audio_device, fused q|k|v, cached weights, AVX2 threading)
  • Row with DONE points implemented (prefill_audio_device, fused q|k|v, cached weights, AVX2 threading)

Non-compliant requirements:

  • The PR does not include a full row in the AMD-RAI-BOARD.md (this is a follow-up PR)

Requires further human verification:

  • Verification of the actual performance improvement against FLM 1.0.12's claim (0.6 s per 30 s window)
  • Verification of the bit-exactness of the results against the CPU baseline on ≥3 fixtures plus edge case
⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Potential Performance Regression

The introduction of projection_groups and projection_group_key functions in audio_exec.cpp may introduce a performance regression if the logic for detecting and grouping projections is not optimized. The code iterates through all nodes to find MatMul operations and then groups them by activation, which could be inefficient for large graphs. If not properly optimized, this could slow down the graph execution.

// engine#1783: MatMuls whose B is a rank-2 initializer and that read the same activation with the same K (whisper's q, k, v),
// keyed by the first one's 0-based index. The executor offers each group to the device as one product, and the device
// prefill walks the same groups, so both build the same key. Empty when ONEBIT_AUDIO_FUSE_QKV=0.
std::map<size_t, std::vector<size_t>> projection_groups(const OnnxGraphInfo& g,
                                                        const std::map<std::string, const OnnxInit*>& inits) {
    std::map<size_t, std::vector<size_t>> out;
    const char* fq = std::getenv("ONEBIT_AUDIO_FUSE_QKV");
    if (fq != nullptr && fq[0] == '0') return out;
    std::map<std::string, std::vector<size_t>> by_a;
    for (size_t i = 0; i < g.nodes.size(); ++i) {
        const auto& m = g.nodes[i];
        if (m.op != "MatMul" || m.ins.size() < 2 || m.outs.empty() || inits.count(m.ins[1]) == 0) continue;
        if (inits.at(m.ins[1])->dims.size() != 2) continue;
        by_a[m.ins[0]].push_back(i);
    }
    for (auto& kv : by_a) {
        if (kv.second.size() < 2) continue;
        const int64_t k0 = inits.at(g.nodes[kv.second[0]].ins[1])->dims[0];
        bool same_k = true;
        for (size_t i : kv.second) same_k = same_k && inits.at(g.nodes[i].ins[1])->dims[0] == k0;
        if (same_k) out[kv.second[0]] = kv.second;
    }
    return out;
}

std::string projection_group_key(const OnnxGraphInfo& g, const std::vector<size_t>& members) {
    std::string key = "fused";
    for (size_t i : members) key += "|" + g.nodes[i].ins[1];
    return key;
}
AVX2 Usage Conditional

The code in xdna_target.cpp uses conditional compilation for AVX2 support, which is good for portability. However, if the AVX2 support is not properly detected or enabled, the performance benefits of the AVX2-optimized functions may not be realized, potentially leading to suboptimal performance on systems that support AVX2.

    // engine#1783: the same per-row scale, rows split over threads and |a| maxed 8 wide (rows_host.h says why the
    // result is the same float); a decode launch (M < 64) stays serial.
    namespace rh = npu::target::xdna::rows_host;
    rh::amax_scales(A, M, K, ascales.data(), rh::use_avx2(), rh::threads_for(M));
}
Direct Output Flag Logic

The logic for handling the ONEBIT_AUDIO_DIRECT_OUT flag in NpuAudioGemm::gemm may introduce a performance regression if the flag is set to 0, causing unnecessary buffer allocations and copies. This could impact performance, especially in high-throughput scenarios.

static const bool direct = [] {
    const char* e = std::getenv("ONEBIT_AUDIO_DIRECT_OUT");
    return e == nullptr || e[0] != '0';
}();
if (direct) C->resize(size_t(M) * size_t(N));
else C->assign(size_t(M) * size_t(N), 0.0f);

bong-water-water-bong added a commit that referenced this pull request Nov 20, 2026
…ant, fixed malloc thresholds (#1783) (#3026)

* whisper_transcribe: fixed malloc thresholds, so a warm encoder pass stops re-faulting its buffers (#1783)

glibc raises its mmap threshold only after a large block is freed. An encoder pass allocates and frees multi-MB
activation buffers (the largest, fc1's 1500 x 3072 f32, is 18 MiB), so with the dynamic threshold every pass mmapped
and faulted them in again. The tool now sets M_MMAP_THRESHOLD to 32 MiB (glibc's 64-bit ceiling) and
M_TRIM_THRESHOLD to INT_MAX at start-up. ONEBIT_WHISPER_MALLOPT=0 keeps glibc's defaults. Only the tool's process
is affected; nothing in the library calls mallopt.

Measured on strixhalo, npu-hold ticket 01795202457190959979.cl-1783-opus-e2e (2026-11-20 15:21 local), amdxdna
srcversion 9BC1292B784C8D5F40AED02, 1-minute load 7.1-17.6, one binary with the arms switched by env, 6 interleaved
rounds, whisper-small, jfk.wav, encode-only, 8 threads, the m1536 per-role kernel family:
  warm pass (2nd of 2)  ONEBIT_WHISPER_MALLOPT=0  0.814-1.006 s (median 0.873)
                        default                   0.791-0.931 s (median 0.839), faster in 5 of 6 paired rounds
  minor faults per run  343k-703k -> 169k-360k
The encoder output hash (encode-only "output fnv") is 1488b62540a44850 on the device route in every run of both arms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* audio_exec: a projection's bias, GELU and residual run inside the device dequant (bit-identical) (#1783)

The whisper encoder spells a projection's tail as separate nodes after its MatMul: Add(bias), then either the five-node
erf GELU (Div, Erf, Add, Mul, Mul) or Add(residual). Each node allocates and walks a 1500 x 768 (fc1: 1500 x 3072)
tensor. The executor now hands the tail to the device hook with the product (AudioGemm::gemm_ep, npu/audio_epilogue.h),
and the xdna target applies it per row block right after the dequant, on the same thread, so the product is written
once in its final form.

Bit-identity: every folded step is the same single IEEE operation on the same two operands as the node it replaces
(x + y, x * y, x / y and std::erf, in the graph's order). Float + and * are commutative, so operand order inside a
step changes nothing. GELU and residual are exclusive, so no multiply feeds an add inside one expression, and an -mfma
build cannot contract the tail into an FMA.

The fold is taken only when nothing outside the chain can see an intermediate. The MatMul's B is a rank-2
initializer and the MatMul is outside a q|k|v group. Its output has exactly one use (graph outputs count as uses),
an Add with a 1-D initializer as wide as the product. The biased value is then used either exactly twice, by a GELU
whose constants are scalar initializers and whose intermediates are each used once, or once, by an Add whose other
operand is a computed tensor of the product's exact shape. Anything else runs node by node. A residual that is not
ready, or a device that declines, falls back to the plain product. The residual pointer is advanced per M-chunk. A
target that cannot fold (epilogue_done stays 0) gets the tail applied by NpuAudioGemm on the rows it wrote.
ONEBIT_AUDIO_FOLD_EPILOGUE=0 turns the fold off; AudioRunResult::folded_epilogues counts the folds.

Tests: audio_exec_test runs the whisper-small encoder through a fake device folded and unfolded: 36 tails folded (o,
fc1, fc2 x 12), 0 with the switch off, and the encoder output is memcmp-identical. npu_rows_host_test checks
dequant+tail against dequant then tail for the scalar and AVX2 arms at 1, 3 and 8 threads, for both kinds.

Measured in the same session as the parent commit (ticket 01795202457190959979.cl-1783-opus-e2e, srcversion
9BC1292B784C8D5F40AED02, load 7.1-17.6, same binary, 6 interleaved rounds):
  warm pass   fold off 0.791-0.931 s (median 0.839)  ->  fold on 0.728-0.837 s (median 0.787), faster in 6 of 6 rounds
  RSS         3.71 GB -> 2.17 GB;   minor faults 169k-360k -> 117k-124k
Device "output fnv" 1488b62540a44850 in every run. Host route 4aabfa4a61b5fd49 (it has no device hook, so it never
folds). Transcripts in ticket 01795201092423076936.cl-1783-opus (15:01): jfk, fx-short, fx-silence and test_speech,
3 runs each, all equal to the CPU-baseline token ids.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* npu_rows_host_test: -inf in a vector lane, decode widths stay serial; rows_host.h says what ties the base loops to the old ones (#3017 review)

The three asks from the #3017 review:
* -inf now also sits at index 8 (0 mod 8) of a row, so _mm256_max_ps sees it in a vector lane. Before, it was only
  at K-1, which is always in the scalar tail for K = 768, 3072, 245 and 7.
* threads_for(1), threads_for(16) and threads_for(63) must be 1: a decode launch and anything under kMinRows keep
  the serial loop.
* rows_host.h now says that the device encoder hash ties the *_base loops to the inline loops they replaced: the
  device route printed the same encode-only "output fnv" before and after the move. The dequant comment now gives
  the right reason no FMA can form: no add follows a multiply, so there is nothing to contract.

npu_rows_host_test passes with the defaults, with ONEBIT_NPU_GLUE_AVX2=0 and with ONEBIT_NPU_GLUE_THREADS=3.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs/npu.md: the fold and malloc switches, and why prefill made the warm pass slower (#1783)

The device-route list gains ONEBIT_AUDIO_FOLD_EPILOGUE and ONEBIT_WHISPER_MALLOPT. The ONEBIT_WHISPER_NPU_PREFILL
note no longer calls the 0.03-0.05 s warm-pass slowdown unexplained. With prefill on, no pass frees a large block,
so glibc's dynamic mmap threshold stays low and every pass re-faults its buffers: about 510k minor faults per run
against 350k. With fixed thresholds both arms measured the same. That was measured in the cl-1783 lane on
2026-11-20, with GLIBC_TUNABLES mmap_threshold/trim_threshold, at load 15-17.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: bong-water-water-bong <[email protected]>
Co-authored-by: Claude Opus 5.5 <[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