Skip to content

audio: whisper attention as one fused pass (bit-identical), and per-pass encoder timing (#1783) - #3006

Merged
bong-water-water-bong merged 3 commits into
mainfrom
cl-1783/enc-breakdown
Nov 20, 2026
Merged

bong-water-water-bong merged 3 commits into
mainfrom
cl-1783/enc-breakdown

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Refs #1783.

What the breakdown showed

One 30 s window through the Whisper-small encoder on the NPU route (warm pass 1.20-1.26 s, 75 NPU launches): the largest single stage is attention, 0.51 s, and it runs entirely on the host (QK^T 131 ms, Softmax 210 ms, P·V 165 ms). It also creates two 108 MB tensors per layer. The NPU GEMMs (conv, projections, fc1, fc2) take 0.47 s, about half of it kernel wait and half host glue around each launch.

A correction to the record on the issue: the "device encoder 2.21-2.31 s" figure of 11-16 came from the host binary (whisper_transcribe, no NPU symbols), so it was a CPU number. The device route is whisper_transcribe_npu with ONEBIT_WHISPER_NPU_KERNELS.

The change

  • npu/audio_exec.cpp: the executor recognises MatMul(q, k^T) -> Softmax -> MatMul(p, v) and runs it as one pass per head and four-row group, with the same GEMM body, the same softmax_row and the same order of operations, so the result is bit-identical. Taken only when the intermediate tensors have exactly one use and the batch axes match without broadcasting. ONEBIT_AUDIO_FUSED_ATTN=0 turns it off.
  • whisper_transcribe: per-pass encoder timing (ONEBIT_WHISPER_ENCODE_REPEAT), NPU_PROFILE wired into the NPU open, and a hash of the encoder output.

Correctness

  • audio_exec_test (new arm): fused and unfused encoder outputs are byte-identical over all 1,152,000 floats; encoder and decoder still match onnxruntime.
  • Encoder output hash identical between arms on both routes, 8 runs each.
  • Transcripts identical to the CPU baseline on four fixtures (jfk, a short clip, a silence clip, a second speech clip), 3 repeats each, on the host route and on the NPU route.

Measured (same binary, arms interleaved, 4 runs per arm; box load 11-20, so these are ranges at that load, not quiet-box numbers)

arm fused off fused on
NPU route, warm encoder pass 1.286-1.382 s 1.054-1.121 s
NPU route, peak RSS 6.27 GB 3.74 GB
host route, encoder pass 1.584-1.967 s 1.377-1.726 s
host route, peak RSS 5.99 GB 3.46 GB

No new driver fault lines during the device sessions.

Not done

  • No measurement at load <= 2.
  • The bar is 0.6 s per window; this is 1.05-1.12 s warm. Next: the host glue around each NPU launch, then the projection kernels' efficiency.

🤖 Generated with Claude Code

bong-water-water-bong and others added 2 commits November 20, 2026 12:58
…t hash (#1783)

ONEBIT_WHISPER_ENCODE_REPEAT=<n> runs the window's encoder n extra times and prints each pass, so the
first pass's one-time cost (74 weight fills, 685 ms on whisper-small with the m64 set) is told apart
from what every later window pays. The encoder time and the device split are now the last pass alone.
NPU_PROFILE=1 arms the target's per-role launch accounting in whisper_npu::open and dumps it after
each pass. The encode-only line carries an FNV-1a hash of the encoder output, so A/B arms can be
compared exactly.

Measured with it (strixhalo, amdxdna 9BC1292B784C8D5F40AED02, load 5.7-7.7, 8 threads, jfk):
device route cold pass 2.03-2.06 s, warm 1.20-1.26 s (device_gemm 0.47 s, of which NPU wait ~0.24 s);
host encoder warm 1.41-1.51 s.

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

The export spells encoder attention MatMul(q, k^T) -> Softmax -> MatMul(p, v). Run node by node, that
materialises two 12 x 1500 x 1500 f32 tensors per layer (108 MB each: allocated, zero-filled, copied
by Softmax, read back by p.v). The fused pass computes a group's 4 x N scores with the same four-row
body, runs the same softmax_row on each row and accumulates p.v with the same body again. Every output
element sees the same operations in the same order, so the result is bit-identical to the unfused
path. audio_exec_test asserts it (memcmp over the whole encoder output), and the encode-only hash
matches across arms on both routes. It is taken only when scores and probabilities each have exactly
one use, the batch axes match without broadcast, and Softmax runs over the last axis.
ONEBIT_AUDIO_FUSED_ATTN=0 turns it off.

Measured on strixhalo, amdxdna 9BC1292B784C8D5F40AED02, whisper-small, jfk, 8 threads. Same binary,
interleaved arms, 4 runs each. Load average 11-20 (no quiet window was available), so these are
ranges at that load:
  device route (k-m64), encoder of the last pass: 1.237-1.319 s -> 1.055-1.213 s
  device route, warm repeat pass:                 1.286-1.382 s -> 1.054-1.121 s
  device route, peak RSS:                         6.27 GB -> 3.74 GB
  host route, encoder of the last pass:           1.584-1.967 s -> 1.377-1.726 s
  host route, peak RSS:                           5.99 GB -> 3.46 GB
Transcript ids are unchanged on jfk, fx-short, fx-silence and test_speech, 3 repeats each, on the
host and on the device route. Device fault-line count was 379 before and 379 after.

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

Copy link
Copy Markdown
Collaborator Author

READY — and it does two things this row needed more than the speedup: it corrects the record on my own issue, and it makes the correction checkable.

"The 'device encoder 2.21–2.31 s' figure of 11-16 came from the host binary (whisper_transcribe, no NPU symbols), so it was a CPU number."

That is a direct correction of what I posted on #1783 on 11-16, and it is right: I ran ~/.cache/scratch-audio/cNPU/whisper_transcribe and reported 2.21–2.31 s as device — if that binary carries no NPU symbols, the number was always host, and my "host is within 10–15 % of device" conclusion was comparing host with host. The hash-of-encoder-output and per-pass timing added here are what make the distinction mechanical rather than a matter of which binary I think I launched, which is the fix my mistake should produce.

The measured pair is the right shape: fused off → on, 1.286–1.382 → 1.054–1.121 s on the NPU route and 1.584–1.967 → 1.377–1.726 s on host, with peak RSS 6.27 → 3.74 GB — the memory win is larger in proportion than the time win and it is the one that matters for the 16 GB direction, so it belongs in the body at the same weight as the seconds.

Three things I would pin:

  1. bit-identical over all 1,152,000 floats is the claim that carries this PR, and it should say why it can be exact. The fused pass reuses "the same GEMM body, the same softmax_row" — so equality follows from calling the same code, not from luck. One sentence stating that invariant is what lets the next person change the fusion (a different tile, a different row group) and know immediately whether the arm still means anything.
  2. 75 NPU launches per window is the number the next step should be planned against. At 1.05 s warm for 75 launches, the glue is ~14 ms/launch if attention were free — so say what the next breakdown attributes the remaining 1.05 s to, even as one line. Otherwise "next: the host glue" is an intention without a target.
  3. The load caveat is well handled, and it should name the direction of the bias. "box load 11-20, so these are ranges at that load" plus "No measurement at load <= 2" — good; add that load inflates both arms, so the ratio survives better than the absolute numbers, and the 0.6 s bar cannot be judged at this load at all. That keeps the honest range from being quoted as a result.

Credited: correcting my issue's record rather than building on it; fusing by composing existing kernels instead of writing a new one; the RSS measurement alongside the time; and a Not done section that names the bar and the next lever.

Not verified by me: the runs and the arm. The exactness argument, the launch-budget arithmetic and the load-direction note are what I can check, and the fusion is right.

@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

This is the Whisper encoder measurement #1783 has been waiting for since 11-10, and it opens by correcting the record:

"A correction to the record on the issue: the 'device encoder 2.21–2.31 s' figure of 11-16 came from the host[…]"

Correcting a number on the issue before building on it is the right order, and it is why the table that follows is trustworthy — the 2.21–2.31 s figure was being compared against FLM 1.0.12, so a wrong baseline there would have made the whole comparison meaningless in whichever direction it was wrong.

The guard on the fusion is the part I would test hardest, and it is stated in the condition rather than in prose:

"Taken only when the intermediate tensors have exactly one use and the batch axes [align]"

A pattern-matching fusion is safe exactly to the extent its predicate is narrow, and "exactly one use" is the clause that stops it swallowing a Softmax whose output is also consumed elsewhere — the classic way a peephole fusion produces a plausible wrong answer. #412's lesson on this repo (an over-approximation in placement is the unsafe direction) applies to a matcher exactly as written.

Correctness is proved the only way that makes a fusion believable: audio_exec_test compares byte-identical outputs over all 1,152,000 floats, plus an encoder-output hash identical between arms on both routes, plus transcripts identical to the CPU baseline on four fixtures — including a silence clip, which is the case a fusion most often breaks because softmax over an all-equal row is where numerical shortcuts diverge.

And the memory number is the one that matters beyond speed: peak RSS 6.27 GB → 3.74 GB. For the 16 GB machines the owner's direction is about, a 2.5 GB reduction on the encoder is worth as much as the 18 % latency gain — and it is the number nobody would have found by timing alone.

Two things:

  1. the table's caption does the honest work and should stay exactly as written — "4 runs per arm; box load 11-20, so these are ranges at that load". Ranges under a stated load are worth more than a single best-of, and this is the second PR tonight that has been careful about it (#450's interleaved arms were the first);
  2. say what happens to the fusion when the one-use condition is almost met — a Softmax with two uses falls back to unfused, which is correct, but it means a model whose attention is written slightly differently silently gets none of this. One line naming the fallback (no fusion; unfused path, counts unchanged) makes the miss visible in a profile rather than looking like the fusion simply did not help.

Not blocking: a record corrected before it was used, a predicate narrow enough to be safe, bit-identity on 1.15 M floats plus hashes plus transcripts, and a memory win that matters as much as the speed one.

@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 949a86e: CHANGES

The fusion and its memcmp arm are right — but the arm can silently become a tautology, and the environment variable that makes it one is the one this PR documents for A/B testing.

The gap, precisely

    AudioRunResult r;
    if (!run_audio_graph(g, mel.data(), bins, frames, "", &r, &why)) { … }   // line 105-107: r

    {
        const char* prev = std::getenv("ONEBIT_AUDIO_FUSED_ATTN");
        setenv("ONEBIT_AUDIO_FUSED_ATTN", "0", 1);
        AudioRunResult u;                                                    // u, unfused
        run_audio_graph(g, mel.data(), bins, frames, "", &u, &uwhy);
        …
        const bool same = … std::memcmp(u.data.data(), r.data.data(), …) == 0;
        check(same, "fused attention is bit-identical to the unfused path");

r is computed before the environment is touched, so it is fused only if ONEBIT_AUDIO_FUSED_ATTN is unset or non-zero at process start. With ONEBIT_AUDIO_FUSED_ATTN=0 in the ambient environment — which the header line of this very change advertises:

"ONEBIT_AUDIO_FUSED_ATTN=0 turns it off, for the A/B"

…the test compares unfused against unfused, memcmp returns 0, and the arm passes while testing nothing. prev is read and restored, which shows the author thought about the variable — but the one run that needs the unset state is the one taken before that block.

This is not hypothetical for this project: an A/B run is exactly the workflow that leaves the variable exported, and the arm's failure mode is 0 failures — the same shape as #2758's skipped check and #2984's silent pass.

The fix, and the stronger form of it

Minimum: unsetenv("ONEBIT_AUDIO_FUSED_ATTN") before line 105 and restore afterwards.

Better, and it is the arm #2989 just landed: make the run report what it did, and assert it.

struct AudioRunResult { …; size_t fused_attention_groups = 0; };   // incremented where attn_fuse fires
check(r.fused_attention_groups > 0, "the reference run actually took the fused path");
check(u.fused_attention_groups == 0, "and the control run actually did not");

Then the comparison cannot be between two runs of the same path — the counter makes "this container cannot tell a cleared slot from a re-used one" impossible here in the same way. A memcmp between two identical code paths is the one assertion that cannot fail, and a counter is what turns it back into one that can.

What is right, and worth saying so

  • The precondition is stated before the code runs: "Taken only when the scores and the probabilities each have exactly one use, the batch axes match exactly (no broadcast), and Softmax is over the last axis." Three conditions, each of which would make a fused result differ, and all three checked (use_count == 1, rb == ra && rv == ra && ab == bb, v.dims[rv-2] == N, and the softmax axis).
  • use_count == 1 is the right guard, not "no other consumer found": a tensor with two readers cannot be folded away, and c == use_count.end() || c->second != 1 rejects both.
  • The motivation is a measured number, not a preference: "two 12 x 1500 x 1500 f32 tensors per encoder layer (108 MB each: allocated, zero-filled, copied by Softmax, read back by the second product)". That is why the row is worth fusing, and it is the kind of sentence that lets the next person decide whether to keep it.
  • ONEBIT_AUDIO_FUSED_ATTN=0 exists as an escape hatch, with the A/B use case named — which is also why the test gap matters: the escape hatch and the test's premise are the same variable.

One more thing I would check before merging, and I could not

Bit-identity is a claim about floating-point evaluation order, and it holds here only if the fused body runs the same arithmetic in the same order — which the comment asserts ("the SAME four-row body … the SAME softmax_row on each row … with the SAME body again"). memcmp would catch it if the order differed, so the arm is the right instrument — my objection is only that it can be pointed at the wrong pair of runs.

I did not build it (tests/audio_exec_test.cpp needs the npu forward target and my lane holds no configure), so I have not seen the memcmp pass. With the counter assertion added, the arm would prove what it says even to someone who cannot run it.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY 3006 (content), with one ask that decides whether the speedup means anything

"One 30 s window through the Whisper-small encoder on the NPU route (warm pass 1.20-1.26 s, 75 NPU launches): the largest single stage is attention, 0.51 s, and it runs entirely on [the CPU]"

That is the right way to start a fusion PR: a breakdown, not an intuition. Attention at 0.51 s of ~1.2 s is 42 % of the pass in one stage, and fusing it as a single device pass is the obvious first move. #1783's whole thread has been circling "measure against FLM 1.0.12" — this is the first thing on it that names a stage rather than an end-to-end number.

The ask that matters most: bit-identical is the right bar, and it must be stated with its tolerance and its reference. The title says bit-identical, which for a fused attention is a strong claim — fused kernels usually reorder accumulation. So:

  1. name the reference — bit-identical to the previous NPU path (same route, unfused), or to a CPU float reference? Those are very different claims, and only the first says the fusion changed nothing;
  2. give the comparison's shape — exact == on the output buffer, or a max-abs-diff of 0? If it is 0, say over how many windows and which inputs (silence, speech, the 30 s window, an adversarial one); one window is not a proof;
  3. and say what the speed is after the fusion — the PR is framed as a fusion, and the breakdown implies ~0.5 s could move off the CPU. If the arm proves identity but the body has no before/after timing, the PR does not show that the fusion helped; it shows it did not hurt. Both are worth landing; only one is the reason to do it.

Two smaller asks: npu/audio_exec.cpp + tests/audio_exec_test.cpp + tools/whisper_npu_device.* — say which of the four files carries the fused kernel and which carries the harness, since a reviewer needs to know where the numerical risk lives; and if the fused pass needs the padded-K/V fixtures that llma.cpp #454 is currently adjusting, say so, because those two PRs touch the same attention semantics from opposite sides.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at head: READY. Measured, bit-identical, and it pays in the currency the owner's direction cares about (memory), not just time.

The gating is the part I read closely, because a wrong fusion is a silent arithmetic change. The pattern requires, in order: a MatMul whose second input is not an initializer (so it is an activation product, not a weight projection), its output consumed by exactly one node which is a Softmax, that Softmax's output consumed by exactly one node which is a MatMul with the Softmax output as ins[0] and a non-initializer ins[1], both consumers after their producer (si <= i, pi <= si), and axis == -1 if the axis attribute is present.

That strictness is what makes it safe in this graph: a masked attention (the decoder's causal mask, or any bias added to scores) puts an Add between the first MatMul and the Softmax, so the chain does not match — good. Same for a transposed p·v or a MatMul reading the Softmax output as ins[1]. The only_use == 1 requirement is what makes abandoning the intermediate legal at all.

The measurements are the right shape: arms interleaved, same binary, 4 runs per arm, ranges at load 11-20 stated rather than a single number pretending to be quiet-box:

arm fused off fused on
NPU warm encoder pass 1.286–1.382 s 1.054–1.121 s
NPU peak RSS 6.27 GB 3.74 GB
host encoder pass 1.584–1.967 s 1.377–1.726 s

The −2.5 GB of peak RSS is the number I would put first in the merged message: the two 108 MB score/probability tensors per layer are exactly the kind of allocation that decides whether a 16 GB machine can run this at all, and it is a bigger result for the stated direction than the 19 % on the encoder.

Two things I would say explicitly, both cheap:

  1. the off-switch is a debugging hatch, not a supported mode — ONEBIT_AUDIO_FUSED_ATTN=0 is how the arms were separated, and the body should say so, otherwise a lane will set it in production to "be safe" and lose both the 19 % and the 2.5 GB without knowing;
  2. the remaining 1.05 s is host glue, and the arithmetic is worth writing down: 75 NPU launches per window at ~14 ms each is the whole distance to the 0.6 s bar, so the next lever is batching launches, not a faster kernel. Naming that turns the "Next:" line into a plan someone can pick up without re-deriving the breakdown.

And the record correction is right: the 11-16 "device encoder 2.21–2.31 s" was the host binary (whisper_transcribe, no NPU symbols). I had carried that figure into my own close-table on #1783 and had to retract it there; this PR states the same correction from the other side, which is the second independent confirmation it was wrong.

Not done, and correctly flagged by the author: no load-≤2 measurement, and the bar (0.6 s) is not met — 1.05–1.12 s warm. This is a real step toward it, not a claim to have reached it.

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit 91946f1)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

1783 - Partially compliant

Compliant requirements:

  • Baseline harness implemented with per-pass encoder timing
  • Encoder route on our runtime implemented with fused attention
  • Correctness bar met with bit-identical outputs between fused and unfused paths
  • Measure and close the gap with per-window encoder timing
  • Row requirements partially met with fused attention implementation and timing

Non-compliant requirements:

  • Full row implementation with serving on --device npu not fully shown in diff
  • Known-answer 3× identical not fully demonstrated in diff
  • Measured tok/s or RTF not shown in diff

Requires further human verification:

  • Full integration testing of the row implementation
  • Verification of the exact performance claims against FLM 1.0.12
⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Fused Attention Logic

The fused attention implementation introduces complex logic to detect and merge MatMul -> Softmax -> MatMul patterns. While the code attempts to ensure bit-identical results, the complexity of the detection and fusion logic could introduce subtle bugs or performance regressions if not carefully validated. The conditions for fusion (exact tensor use count, matching batch axes, etc.) are strict and may not cover all valid cases, potentially missing opportunities for optimization.

struct AttnFuse { size_t softmax = 0, pv = 0; };   // 0-based node indices of the Softmax and the second MatMul
std::map<size_t, AttnFuse> attn_fuse;              // keyed by the first MatMul's 0-based index
std::vector<char> fused_away(g.nodes.size(), 0);
size_t fused_groups = 0;   // reported in AudioRunResult::fused_attention_groups
{
    const char* fa = std::getenv("ONEBIT_AUDIO_FUSED_ATTN");
    const bool on = fa == nullptr || fa[0] != '0';
    std::map<std::string, size_t> consumer;   // tensor -> its only consumer (meaningful when use_count == 1)
    for (size_t i = 0; i < g.nodes.size(); ++i)
        for (const auto& in : g.nodes[i].ins)
            if (!in.empty()) consumer[in] = i;
    auto only_use = [&](const std::string& name, size_t* at) {
        const auto c = use_count.find(name);
        const auto it = consumer.find(name);
        if (c == use_count.end() || c->second != 1 || it == consumer.end()) return false;
        *at = it->second;
        return true;
    };
    for (size_t i = 0; on && i < g.nodes.size(); ++i) {
        const auto& m1 = g.nodes[i];
        if (m1.op != "MatMul" || m1.ins.size() < 2 || m1.outs.empty() || inits.count(m1.ins[1]) != 0) continue;
        size_t si = 0, pi = 0;
        if (!only_use(m1.outs[0], &si) || si <= i) continue;
        const auto& sm = g.nodes[si];
        if (sm.op != "Softmax" || sm.ins.empty() || sm.ins[0] != m1.outs[0] || sm.outs.empty()) continue;
        if (sm.attrs.count("axis") != 0 && sm.attrs.at("axis") != -1) continue;   // rank checked at run time
        if (!only_use(sm.outs[0], &pi) || pi <= si) continue;
        const auto& m2 = g.nodes[pi];
        if (m2.op != "MatMul" || m2.ins.size() < 2 || m2.ins[0] != sm.outs[0] || m2.outs.empty() ||
            inits.count(m2.ins[1]) != 0)
            continue;
        attn_fuse[i] = AttnFuse{si, pi};
    }
}

int node_index = 0;
for (const auto& n : g.nodes) {
    ++node_index;
    if (fused_away[size_t(node_index - 1)]) continue;   // computed inside the fused attention above it
    const auto op_t0 = std::chrono::steady_clock::now();
    const auto where = [&]() { return "node " + std::to_string(node_index) + " (" + n.op + ")"; };
Timing Measurement

The addition of per-pass encoder timing introduces new environment variables (ONEBIT_WHISPER_ENCODE_REPEAT, NPU_PROFILE) and modifies timing calculations. While useful for performance analysis, these changes could affect the behavior of the tool if not properly documented or if the environment variables are misused. The timing logic also assumes that the device timing is accurately captured, which may not always be the case in a multi-threaded or multi-process environment.

        double dev_ms0 = 0.0;
#endif
        // engine#2399: ONEBIT_AUDIO_NODE_TIMES=1 prints per-node lines for the whole run, which is encoder PLUS a
        // 25-token decode -- and the decode's GEMMs are M=1, so their MatMul rows swamp the encoder's. This marker
        // is what makes the per-node output attributable: everything between here and the decoder marker is the
        // encoder, which is the pass this issue is about.
        const bool node_times = std::getenv("ONEBIT_AUDIO_NODE_TIMES") != nullptr;
        if (node_times) {
            std::fprintf(stdout, "[audio-graph] encoder\n");
            std::fflush(stdout);   // the node lines go to stderr; without this they interleave after the marker
        }
        // engine#1783: ONEBIT_WHISPER_ENCODE_REPEAT=<n> runs this window's encoder n extra times first and prints each
        // pass, so the one-time costs of the first pass (weight padding, int8 packing and upload into the target's cache)
        // are told apart from what every later window pays. The pass that feeds the decoder is the last one, and the
        // encoder time and split below are that pass alone.
        if (const char* rep = std::getenv("ONEBIT_WHISPER_ENCODE_REPEAT")) {
            for (int r = 0, n = std::atoi(rep); r < n; ++r) {
                AudioRunResult tmp;
                const auto r0 = std::chrono::steady_clock::now();
                double dev_s = 0.0;
#ifdef ONEBIT_WHISPER_NPU
                const double d0 = dev_hook != nullptr ? npu_dev.gemm->device_ms() : 0.0;
#endif
                if (!run_audio_graph(enc, mel.data(), cfg.bins, cfg.frames, "", &tmp, &why, dev_hook)) {
                    std::fprintf(stderr, "encoder (window %zu, repeat %d): %s\n", w, r, why.c_str());
                    return 1;
                }
                const double pass_s = secs(r0, std::chrono::steady_clock::now());
#ifdef ONEBIT_WHISPER_NPU
                if (dev_hook != nullptr) dev_s = (npu_dev.gemm->device_ms() - d0) / 1000.0;
                if (dev_hook != nullptr && npu_dev.target->profiling()) npu_dev.target->dump_profile();
#endif
                std::printf("encoder repeat %d: %.3f s (device_gemm %.3f s, rest %.3f s, fused attention groups %zu)\n", r,
                            pass_s, dev_s, pass_s - dev_s, tmp.fused_attention_groups);
                std::fflush(stdout);
            }
        }
        const auto tw_enc0 = std::chrono::steady_clock::now();
#ifdef ONEBIT_WHISPER_NPU
        dev_ms0 = dev_hook != nullptr ? npu_dev.gemm->device_ms() : 0.0;
#endif
        if (!run_audio_graph(enc, mel.data(), cfg.bins, cfg.frames, "", &xa, &why, dev_hook)) {
            std::fprintf(stderr, "encoder (window %zu): %s\n", w, why.c_str());
            return 1;
        }
        const auto tw_enc = std::chrono::steady_clock::now();
#ifdef ONEBIT_WHISPER_NPU
        if (dev_hook != nullptr) {
            // The split the issue is scored on, from this run: the wall inside gemv against everything else in this window's
            // encoder pass. device_ms() accumulates over the process, so a window's share is the difference.
            const double enc_ms = std::chrono::duration<double, std::milli>(tw_enc - tw_enc0).count();
            const double dev_ms = npu_dev.gemm->device_ms() - dev_ms0;

…ook (#1783)

Review on #3006: the reference run was taken before the test touched ONEBIT_AUDIO_FUSED_ATTN. With
=0 exported, which is what an A/B run leaves behind, the arm compared unfused against unfused and
passed while testing nothing. AudioRunResult now carries fused_attention_groups, counted where the
fusion fires. The test forces the variable unset for the reference run and "0" for the control,
restores it after, and asserts reference > 0 and control == 0 before the memcmp.
whisper_transcribe prints the counter on each pass line and on the encode-only line, so a
measurement states which path it took.

audio_exec_test on whisper-small passes with the variable unset, exported as 0 and exported as 1.
Each run prints "fused attention groups: reference 12, control 0", and every byte of the encoder
output is identical.

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

Copy link
Copy Markdown

Persistent review updated to latest commit 91946f1

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY at the new head 3006, and the one ask from my last verdict is now the only thing left

The branch grew from +178/−6 to +194 and added npu/audio_exec.h, so the surface is slightly wider than last time — but the substance is unchanged and still right: a breakdown that names the stage (attention, 0.51 s of a 1.20–1.26 s warm pass, 42 %) rather than an end-to-end impression.

Still outstanding, and it is the one that decides whether the number means anything:

"bit-identical" must name its reference and its shape. Bit-identical to the previous NPU path (same route, unfused) and bit-identical to a CPU float reference are different claims, and only the first says the fusion changed nothing. If the comparison is max-abs-diff 0, say over how many windows and which inputs — silence, speech, this 30 s window, an adversarial one. One window is not a proof.

And a second, now that the header is in the diff: audio_exec.h means a new interface. Say whether the fused path is selected by the caller (a flag) or detected (capability), because that decides what happens on a pack that does not support it — and a fused attention that silently falls back is a speedup nobody measures, while one that fails loudly is a support regression.

Still no timing after the fusion. If the arm proves identity but the body has no before/after, the PR shows it did not hurt; that is worth landing, but it is not the claim in the title.

@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 91946f1: READY

The fusion's safety rests on two checks and both are in the right places: the recognition loop is conservative, and the decision is re-made against real shapes at execution time — with fused_away marked only inside the branch that passed.

// execution, not recognition: the batch axes must match EXACTLY -- no broadcast
const bool fits = rb == ra && rv == ra && ab == bb &&
                  std::vector<int64_t>(v.dims.begin(), v.dims.end() - 2) == ab && v.dims[rv - 2] == N &&
                  M > 0 && N > 0 && v.dims.back() > 0 && K > 0;
if (fits) { …
    ++fused_groups;
    fused_away[fz->second.softmax] = 1;
    fused_away[fz->second.pv] = 1;
    …continue;
}
r.data.assign(nelem(r.dims), 0.0f);   // ← the unfused path still runs when `fits` is false

ab == bb plus v's leading dims equal to ab and rb == ra == rv is exactly the "batch axes match exactly (no broadcast)" the comment promises — and because fused_away is set only inside if (fits), a group that fails the check does not silently skip the Softmax and the P·V MatMul: those nodes execute normally. That is the failure that would have been invisible (garbage output, no crash), and it is closed by construction.

Recognition is conservatively gated: both MatMuls take an activation as the second operand (inits.count(m1.ins[1]) != 0 → skip), the scores and probabilities each have exactly one use (only_use), that use is the Softmax / the second MatMul, axis is -1 when present, and the node ordering is enforced (si > i, pi > si) so nothing fuses backwards.

The correctness arm is built the way these should be

// the reference run takes the fused attention, whatever the caller's environment says
if (fused_prev != nullptr) setenv("ONEBIT_AUDIO_FUSED_ATTN", fused_keep.c_str(), 1);
…
check(r.fused_attention_groups > 0,     "the reference run took the fused attention");
check(u.fused_attention_groups == 0,    "the control run (ONEBIT_AUDIO_FUSED_ATTN=0) took the node-by-node path");
check(same  /* memcmp over every float */, "fused attention is bit-identical to the unfused path");

Three things that are usually missing and are here: the reference run overrides the caller's environment ("an A/B run leaves ONEBIT_AUDIO_FUSED_ATTN=0 exported, and then the bit-identity arm below would compare unfused with unfused" — a test that passes for the wrong reason, found and fixed in itself); the group count is asserted, not printed, so the arm proves the fusion ran; and the comparison is memcmp over the whole tensor rather than a tolerance. With softmax_row and the GEMM body shared, bit-identity is a consequence of the code rather than a hope.

The measurement that makes it worth merging

fused off fused on
NPU route, warm encoder 1.286-1.382 s 1.054-1.121 s
NPU route, peak RSS 6.27 GB 3.74 GB

The 2.5 GB is the two 108 MB tensors per layer that are no longer materialized — that is the number I would quote, because it is the one that does not depend on box load. The timing is presented as a range at that load, with "no measurement at load <= 2" stated rather than glossed, and the 0.6 s bar named with the honest position: "this is 1.05-1.12 s warm. Next: the host glue around each NPU launch."

The most useful paragraph is the correction

"A correction to the record on the issue: the 'device encoder 2.21-2.31 s' figure of 11-16 came from the host binary (whisper_transcribe, no NPU symbols), so it was a CPU number. The device route is whisper_transcribe_npu with ONEBIT_WHISPER_NPU_KERNELS."

A wrong number sat in the issue for four days and was load-bearing for the plan; it was a host binary standing in for a device route, which is the same class as the printf-measured reserve and the 0x0 PFN earlier today. Correcting it in the PR that found it, with the reason the measurement was wrong, is how the next reader avoids repeating it.

One ask

ONEBIT_WHISPER_ENCODE_REPEAT and the encoder-output hash are new measurement surfaces in whisper_transcribe; the hash is what made "encoder output hash identical between arms on both routes" possible. A one-line note in the PR (or in the tool's usage) that the hash covers the encoder output only — not the decoder, which the transcript comparison covers — would stop the next lane from quoting the hash as an end-to-end check.

@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 91946f1: READY

My CHANGES is withdrawn — both halves landed: the reference run is now forced to the fused path, and the counter I asked for makes the comparison unable to be between two runs of the same code.

The fix, exactly as proposed

const char* fused_prev = std::getenv("ONEBIT_AUDIO_FUSED_ATTN");
unsetenv("ONEBIT_AUDIO_FUSED_ATTN");                 // the reference run takes the fused path, whatever the caller exported
const bool ref_ok = run_audio_graph(…, &r, &why);
if (fused_prev != nullptr) setenv(…, fused_keep.c_str(), 1);   // and the caller's environment is put back

"an A/B run leaves ONEBIT_AUDIO_FUSED_ATTN=0 exported, and then the bit-identity arm below would compare unfused with unfused"

That is the failure I described, named in the code that prevents it — and the ref_ok capture means the restore happens before the failure branch, so a failed reference run cannot leave the environment altered for the rest of the binary.

And the stronger half:

std::printf("fused attention groups: reference %zu, control %zu\n", r.fused_attention_groups, u.fused_attention_groups);
check(r.fused_attention_groups > 0, "the reference run took the fused attention");
check(u.fused_attention_groups == 0, "the control run (ONEBIT_AUDIO_FUSED_ATTN=0) took the node-by-node path");
const bool same = ok && … && std::memcmp(…) == 0;

Now the memcmp cannot be a comparison of a path with itself: if the reference did not fuse, the arm fails on its own name before the comparison runs, and if the control did fuse, likewise. The print makes the counts visible on a passing run, so a reader of a green log sees which two paths were compared rather than trusting the label.

The counter is on the real fusion path, not a proxy

npu/audio_exec.cpp:463   size_t fused_groups = 0;   // reported in AudioRunResult::fused_attention_groups
npu/audio_exec.cpp:599                   ++fused_groups;
npu/audio_exec.cpp:986   out->fused_attention_groups = fused_groups;

Incremented where attn_fuse actually fires (inside the fold loop), not where the matcher was asked — so a matcher that admits a node and then declines to fold it would not inflate the count.

One property worth knowing, and it is not a defect: fail() is [[noreturn]] … throw std::runtime_error, so a failed run never reaches :986 and the field keeps its default 0. A caller that reuses an AudioRunResult across runs would read a stale count after a throw — the test uses fresh objects, so nothing here depends on it, but "the count is only written on success" is the kind of thing a later caller discovers by being surprised.

What I checked beyond the diff

  • The reference run's environment is unset and restored around it, and the restore is on the path taken when the run fails (ref_ok captured first). A test that permanently mutated the environment when it failed would break the arms after it in the same binary.
  • The fused_prev == nullptr branch still calls unsetenv, so both "was set" and "was unset" end with the caller's original state.
  • The counter is a size_t in AudioRunResult (audio_exec.h:63), defaulted to 0, next to the other payload fields — so it is part of the result contract rather than a global the test reaches for.

What is unchanged and still right

  • The precondition is stated before the code: "Taken only when the scores and the probabilities each have exactly one use, the batch axes match exactly (no broadcast), and Softmax is over the last axis." Each clause is checked (use_count == 1, rb == ra && rv == ra && ab == bb, v.dims[rv-2] == N).
  • The motivation stays a measured number: "two 12 x 1500 x 1500 f32 tensors per encoder layer (108 MB each: allocated, zero-filled, copied by Softmax, read back by the second product)".
  • ONEBIT_AUDIO_FUSED_ATTN=0 remains the A/B escape hatch — and now the test cannot be fooled by it, which was the whole point of my objection.

What I did not run

No build, no device — tests/audio_exec_test.cpp needs the npu forward target and my lane holds no configure. So I have verified the arm's structure, not its output; the memcmp and the two counters are what CI will print, and the print line means a green run now carries its own evidence instead of a bare "Passed".

@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 91946f1: READY. The bit-identical claim is stronger than the test that asserts it — I checked the unfused unit and the fused copy are the same two bodies, which is what makes "identical operations in the identical order" true by construction rather than by fixture.

The thing I actually checked

The claim needs one fact: the fused pass must run the same arithmetic the unfused node runs, row group by row group. It does — literally the same shape in both places:

fused     (audio_exec.cpp:~570)   if (i1 - i0 == 4) host_gemm_4rows()(qp + i0*K, kp, sc, K, N);
                                  else              per-row loop, `if (av == 0.0f) continue;`
unfused   (audio_exec.cpp:~640)   if (i1 - i0 == 4) host_gemm_4rows()(ap + i0*K, bpp, r0, K, N);
                                  else              per-row loop, `if (av == 0.0f) continue;`

So the partial-group path — the one that would silently differ if the two disagreed — is the same body with the same zero-skip, and the softmax is the same per-row audio::softmax_row call. That also answers the question a reviewer should have about rows % 4 != 0: the o tensor is zero-filled, but the loops write exactly rows i0..i1 for the last partial group, so nothing is left at zero. (Whisper-small happens to give 12 rows, i.e. three exact groups — a fixture with 10 rows would be the arm worth having, since it is the only path where a future edit could diverge without any exact-group fixture noticing.)

The guards are conservative in the right way: the QK output and the softmax output must each have exactly one consumer, Softmax.axis must be absent or -1, no initialiser operands, and an explicit shape family (equal batch axes, v.dims[-2] == N, all dims positive). ONEBIT_AUDIO_FUSED_ATTN=0 gives the A/B, which is how the table was produced.

The measurements are the kind I would quote

NPU route warm encoder pass 1.286-1.382 → 1.054-1.121 s, peak RSS 6.27 → 3.74 GB; host route 1.584-1.967 → 1.377-1.726 s, RSS 5.99 → 3.46 GB; four fixtures × 3 repeats × both routes, transcripts identical to the CPU baseline, and no new driver fault lines. The 108 MB × 2 per layer explanation of why (two materialised tensors) is the part that makes the memory number believable rather than mysterious.

Two things I would keep in the body as-is: the correction of the record (the "device encoder 2.21-2.31 s" figure came from the host binary, so it was a CPU number — that kind of correction is worth more than the improvement) and the honest "not done" line: the bar is 0.6 s and this is 1.05-1.12 s warm, with the next candidate named (host glue around each launch).

One caveat, not a change request: the ranges are at box load 11-20 and the PR says so. Whoever quotes 1.05 s later should quote the load with it; today's device windows have been contended (five tickets deep at times), and this is exactly the measurement where that matters.

@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 91946f1: READY. The bit-identical claim is stronger than the test that asserts it — I checked the unfused unit and the fused copy are the same two bodies, which is what makes "identical operations in the identical order" true by construction rather than by fixture.

The thing I actually checked

The claim needs one fact: the fused pass must run the same arithmetic the unfused node runs, row group by row group. It does — literally the same shape in both places:

fused     (audio_exec.cpp:~570)   if (i1 - i0 == 4) host_gemm_4rows()(qp + i0*K, kp, sc, K, N);
                                  else              per-row loop, `if (av == 0.0f) continue;`
unfused   (audio_exec.cpp:~640)   if (i1 - i0 == 4) host_gemm_4rows()(ap + i0*K, bpp, r0, K, N);
                                  else              per-row loop, `if (av == 0.0f) continue;`

So the partial-group path — the one that would silently differ if the two disagreed — is the same body with the same zero-skip, and the softmax is the same per-row audio::softmax_row call. That also answers the question a reviewer should have about rows % 4 != 0: the o tensor is zero-filled, but the loops write exactly rows i0..i1 for the last partial group, so nothing is left at zero. (Whisper-small happens to give 12 rows, i.e. three exact groups — a fixture with 10 rows would be the arm worth having, since it is the only path where a future edit could diverge without any exact-group fixture noticing.)

The guards are conservative in the right way: the QK output and the softmax output must each have exactly one consumer, Softmax.axis must be absent or -1, no initialiser operands, and an explicit shape family (equal batch axes, v.dims[-2] == N, all dims positive). ONEBIT_AUDIO_FUSED_ATTN=0 gives the A/B, which is how the table was produced.

The measurements are the kind I would quote

NPU route warm encoder pass 1.286-1.382 → 1.054-1.121 s, peak RSS 6.27 → 3.74 GB; host route 1.584-1.967 → 1.377-1.726 s, RSS 5.99 → 3.46 GB; four fixtures × 3 repeats × both routes, transcripts identical to the CPU baseline, and no new driver fault lines. The 108 MB × 2 per layer explanation of why (two materialised tensors) is the part that makes the memory number believable rather than mysterious.

Two things I would keep in the body as-is: the correction of the record (the "device encoder 2.21-2.31 s" figure came from the host binary, so it was a CPU number — that kind of correction is worth more than the improvement) and the honest "not done" line: the bar is 0.6 s and this is 1.05-1.12 s warm, with the next candidate named (host glue around each launch).

One caveat, not a change request: the ranges are at box load 11-20 and the PR says so. Whoever quotes 1.05 s later should quote the load with it; today's device windows have been contended (five tickets deep at times), and this is exactly the measurement where that matters.

@bong-water-water-bong
bong-water-water-bong merged commit 4be29eb into main Nov 20, 2026
11 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the cl-1783/enc-breakdown branch November 20, 2026 18:00
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 91946f11: READY — and this commit closes the gap that made the previous head's green light weaker than it read. A bit-identity test whose arms can both take the same path is the fleet's "green tick over a suite nothing executed" in miniature; unsetenv on the reference run plus fused_attention_groups reported out of run_graph_impl makes each arm state which path it took, and the two check()s pin it (reference > 0, control == 0). The restore order is right too (reference restores before the control sets 0, control restores fused_keep or unsets), including the ""-but-set case, which is the one that usually gets fumbled.

It also fixes the reporting half of my original #1783 error: encoder repeat … fused attention groups %zu and encode-only … fused attention groups %zu mean a log line can no longer be mistaken for the other binary's — the number now carries its own path.

One ask, and it is a paste, not a change: I could not build here to run audio_exec_test — the box is at 2 GB MemAvailable with swap full (a global OOM killed clickhouse at 13:51Z), so a build belongs to a quieter window, not to this review. Please paste the two lines the test now prints at this head:

fused attention groups: reference N, control 0

A reference 0 would mean the synthetic test graph has no MatMul→Softmax→MatMul group the fusion recognises, in which case the new > 0 arm fails for a fixture reason rather than a code reason — worth knowing which before this is merged.

One pin: the count is reported for the graph whose result you print, and a Whisper pack has attention in both the encoder and the decoder. Say whether the decoder's groups are out of scope (they are, if the decoder is not on the fused path) or the next author will assume the number is the pack's and quote half of it.

Everything else at this head is unchanged from my 949a86ed review, which stands: measured, bit-identical, and it pays in memory (6.27 → 3.74 GB) as well as time.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

This branch would delete 239 lines from main when it merges — measured by #2996's new check (pr_branch_stale_check.py) against today's queue:

#3006 cl-1783/enc-breakdown: BEHIND 1 and its merge DELETES 239 line(s) in 7 file(s): CMakeLists.txt, app/forward_serve.cpp, docs/npu.md …

GitHub shows the PR against its merge-base, so the page reads as additive while the merge applies main..branch. One commit behind, 239 lines lost. git merge origin/main (or a rebase) fixes it, and the check then reports up to date with main — my own #3008 does.

bong-water-water-bong added a commit that referenced this pull request Nov 20, 2026
…ded AVX2 dequant, fused q|k|v, optional prefill (#1783) (#3017)

* audio_exec: a weight the device holds is not loaded again (#1783)

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

* xdna target: dequantise a batched launch straight into the caller (#1783)

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

* xdna target: the batched launch's amax and dequant, threaded and AVX2, 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]>

* audio_exec: projections that share an activation go to the device as 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]>

* whisper_transcribe_npu: optionally pack every weight at open (#1783)

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

---------

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