Skip to content

whisper one-shot: packed weights reused from disk, decoder step cache and one-row logits (bit-identical), 16 threads on the device route (#1783) - #3036

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

bong-water-water-bong merged 5 commits into
mainfrom
cl-1783/cold

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Follows #3027 (merged). Refs #1783.

Three changes, all bit-identical.

  1. The device route keeps its packed weights on disk, keyed by an identity of model plus kernel files (ONEBIT_WHISPER_NPU_WCACHE=0 turns it off). A later run reads them straight into device buffers and skips the f32 weight loads. Writes are atomic; a duplicate or wrong-shape import is refused.
  2. The decoder's step-invariant nodes (each layer's cross-attention K/V of the encoder output, 170 of 786 nodes) run once per window (DecoderStepCache, ONEBIT_WHISPER_DECODE_CACHE=0). The vocabulary projection computes only the 4-row unit holding the logits row the greedy step reads (ONEBIT_WHISPER_DECODE_ONE_ROW=0).
  3. The weight packer's OpenMP pool follows the audio thread count (libgomp's default of 32 made the 50 packs take 271-313 ms against 38-51 ms), and the device-route tool defaults to 16 threads on boxes where it may use at least 24 CPUs. ONEBIT_AUDIO_THREADS and OMP_NUM_THREADS still win.

Measured

strixhalo, srcversion 9BC1292B784C8D5F40AED02, one binary with arms switched by env; timing arms run outside the build's thermal cap.

before after
jfk one-shot process wall (4 interleaved rounds, load 14-22, GPU busy with another lane) 18.96-23.47 s 9.43-11.49 s
cold first encoder pass (same run) 2.01-2.12 s 0.67-1.05 s
decode, 25 tokens, load 4.5-6 12.1-13.5 s 5.84-6.81 s
warm encoder, 8 -> 16 threads, load 8.6-9.8 0.50-0.52 s 0.42-0.44 s

At load 4.5-6 the one-shot wall is 6.6-7.7 s, of which the encoder is about 0.5-0.6 s: the decoder, not the encoder, now dominates a one-shot transcription.

Correctness

Token ids identical across arms. Encoder hashes unchanged on both routes. Transcripts x3 on 4 fixtures equal the CPU baseline. audio_exec_test compares the cached and one-row decoder steps byte for byte against uncached runs (a second window's logits differ, so the check is not vacuous); an export -> import round trip of the weight cache equals the host GEMM.

🤖 Generated with Claude Code

bong-water-water-bong and others added 3 commits November 20, 2026 16:55
…nd the whisper tool keeps them on disk (#1783)

NpuTarget gains export_weight()/import_weight() (default: not supported). XdnaTarget implements them for the plain
int8 image of a prefill context: the weight BO's bytes plus the per-column scales, which is everything a launch and
its dequant read. NpuAudioGemm::export_weights() hands out every resident weight with its role and staged shape.
NpuAudioGemm::import_weight() makes a key resident from such an image, refusing a key it already knows or a role
whose design is a different shape. After an import, cached(key) is true, so the executor skips the f32 load and
gemm() launches with no Bmat.

tools/whisper_npu_wcache.h is the on-disk form: one file per identity. The identity is the format version, the
rows, and the name, size and mtime of every file in the encoder graph's directory and in the kernel directory. The
file is written to a temporary name and renamed into place; a mismatching or short file is ignored. The tool wiring
is in the commit after next.

tests/audio_npu_gemm_test.cpp: an export -> import round trip into a fresh target. The imported weights are
resident and launch with no Bmat, the result equals the host GEMM, and a duplicate or a wrong-shape import is
refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nd the logits only for the row read (bit-identical) (#1783)

A greedy decode runs the whole whisper decoder graph once per token, with a new 128-position token window and the
same encoder output. Every node whose inputs are initializers, constants or the encoder output computes the same
tensor at every step. On whisper-small that is 170 of 786 nodes, above all each layer's cross-attention K and V
projections (1500 x 768 x 768 each) and the transposed token embedding.

DecoderStepCache (audio_exec.h), passed to the new run_decoder_graph overload:
- The first run keeps the step-invariant tensors that step-dependent nodes read (38 on whisper-small).
- Each later run moves them in, skips every invariant node, and moves them back out, without copying.
- The kept tensors get one more use, so no consumer moves them out of the map.
- A failed run empties the cache.

DecoderStepCache::output_row: the MatMul that makes the graph output (the 128 x 768 x 51865 vocabulary projection)
runs only the four-row unit holding that row. That is the same unit with the same code, so the row's bytes are
unchanged; the other rows stay 0.

tests/audio_exec_test.cpp:
- the filling step equals the uncached run byte for byte
- a cached step on a different window equals that window's uncached run byte for byte, and its logits differ from
  the first window's
- the one-row run's row equals the full run's row byte for byte, and rows outside its unit are not computed

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… decode with the step cache, and use 16 threads (#1783)

The tool wiring for the two previous commits, plus two thread defaults:
- the packed-weight cache: restored after the device opens, written after the first window when that window had to
  pack anything (ONEBIT_WHISPER_NPU_WCACHE=<dir> | 0)
- the decode step cache and the one-row logits (ONEBIT_WHISPER_DECODE_CACHE=0, ONEBIT_WHISPER_DECODE_ONE_ROW=0)
- the weight packer's OpenMP pool follows the audio thread count unless OMP_NUM_THREADS is set. libgomp's default was
  32 threads next to the executor's pool: the 50 packs took 271-313 ms against 50-51 ms at 8 and 38-45 ms at 16.
- the device-route tool defaults to 16 audio threads when it may use at least 24 CPUs (ONEBIT_AUDIO_THREADS wins). The
  library's 8-thread cap was measured on the host route under a 4-CPU cpuset. The device route's host work (attention,
  the elementwise tail, the decoder) scales past it.
docs/npu.md describes the switches.

Measured on strixhalo, amdxdna srcversion 9BC1292B784C8D5F40AED02, one binary (2af8604e874632d1), arms by env,
jfk.wav one-shot, interleaved x4. Ticket 01795207687191394077.cl-1783-opus-oneshot (2026-11-20 16:48 local), load 14-22, the GPU
busy with another lane's 27B llama-server the whole time:
  wall (process)    sealed-branch behaviour 18.96-23.47 s  ->  this branch 9.43-11.49 s
  encoder (cold)    2.01-2.12 s                            ->  0.67-1.05 s   (0.017 s to write the cache on run 1,
                                                                             0.033-0.064 s to restore it after)
  decode, 25 tok    16.6-20.9 s                            ->  8.4-10.2 s
At load 4.5-6 (ticket cl-1783-opus-decode 16:44, rounds 2-3, same weight cache):
  decode     no step cache 12.1-13.5 s -> step cache 7.50-7.59 s -> + one row 6.45-6.47 s -> + 16 threads 5.84-6.81 s
  wall       12.9-14.4 s -> 7.23-7.26 s (8 threads) -> 6.56-7.66 s (16 threads)
Warm encoder pass, 8 -> 16 threads (ticket cl-1783-opus-attn 16:17, 5 rounds, load 8.6-9.8): 0.50-0.52 -> 0.42-0.44 s,
with attention going from 258-287 to 168-201 ms.

Correctness: every run's token ids are identical across arms; device encode-only fnv 1488b62540a44850; host route
4aabfa4a61b5fd49. Transcripts on jfk, fx-short, fx-silence and test_speech, 3 runs each, all equal to the CPU
baseline. audio_exec_test, audio_npu_gemm_test, audio_parallel, npu_rows_host and npu_elf_args pass.

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

@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

Three changes, all bit-identical, and the third one is the kind of finding that only comes from measuring on this box:

"The weight packer's OpenMP pool follows the audio thread count (libgomp's default of 32 made the 50 p[ercent]…)"

An OpenMP default of 32 threads on a packing step is exactly the sort of thing that is invisible in correctness and expensive on a shared machine — and it is the same class as the ctest storm that rebooted this box: a library default expanding to the machine's full width inside a step nobody profiles. Worth its own line in the body, because a reviewer reading "three changes, all bit-identical" will assume all three are about caching.

Change 2 is stated in the form that makes caching reviewable — "the decoder's step-invariant nodes (each layer's cross-attention K/V of the encoder output, 170 of 78[…])": a count, a location, and the reason they are invariant (the encoder output does not change between greedy steps). "Step-invariant" is the right word and the right test: anything cached under that name must be provably independent of the step, and if the count is 170 of 78x nodes then the win is bounded by how much of the graph that is — a number a reviewer can sanity-check.

Change 1's key is the design question and it is answered by construction: "keeps its packed weights on disk, keyed by an identity of model plus kernel files". The identity covering the kernel files as well as the model is what stops the stale-.hsaco-with-a-correct-looking-name failure that came up on this repo hours ago (#444/#449) — a cache keyed only by the model would have reused weights packed for a different kernel set, which is bit-identical to nothing.

Two things:

  1. say what happens when the identity changes — recompute (correct, and the interesting number is the cost: how long the repack takes on a cold cache, since that is what a first run on a 16 GB machine pays) and whether the old entry is evicted or left behind. A pack directory that grows with every kernel-set change is a disk leak on the small machines this work is for;
  2. all bit-identical needs one sentence on where the comparison was made — three changes affecting weights, decoder caching and packing would each be bit-identical in different places (weights on disk vs in memory; logits per step; the packed blob's bytes vs its effect). Naming the three comparison sites turns one adjective into three checks.

Not blocking: a cache keyed by model and kernels, an invariance argument with a count, a thread-pool fix that only shows up under measurement, and bit-identity across all three.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 1b2b84f9: READY — three levers, each behind an env switch, each with bit-identity rather than an argument. Three asks, and the first is the one that will bite a year from now.

1. The disk cache's identity is format version + rows + name/size/mtime — so the only thing that catches a change in the packing code is the manual version bump. That is the right shape (mtime+size of every file in the graph and kernel directories is a fair trade for skipping ~340 MB of f32 loads), but it means the failure mode is silent: a later PR alters the packing layout without touching kWcacheVersion, and every machine's cache serves bytes that the new packer would never have produced. Two lines make that survivable: a comment on the constant saying what must bump it ("the packed layout, the packing arithmetic, or anything that changes the bytes for a given model+kernels"), and one arm that a bumped version invalidates a matching file. Second, smaller: mtime+size is weak against a file restored with preserved timestamps — worth the one clause, since the alternative (a content hash of 107 MB per run) is what you deliberately avoided.

2. output_row is a precondition, not an optimisation the library can enforce. In whisper_transcribe it is safe — the loop is greedy and reads exactly that row — but DecoderStepCache::output_row lives in the audio path, and the next caller (a logits dump, a beam, a temperature sampler over the full row) would read a partly computed projection and see plausible numbers. Either say the precondition next to the field ("the caller must read only this row; the rest was never computed") or make a read of any other row a hard error. Same class as the read_s/read_kv comments already in that header, which is why it reads oddly that this one is unstated.

3. The measurement sentence worth keeping in the body: "timing arms run outside the build's thermal cap". It is honest, and it is also the reason these numbers are the fast end — a hot die is exactly what starves the GPU queue, so say that the packer numbers (271–313 ms with libgomp's 32 threads vs 38–51 ms at 16) were taken hot and that the shipped default is the capped path. The OpenMP finding itself is a real one worth a line of code comment: a library default of hardware_concurrency made a 50-pack step 6–7× slower, which is the kind of default that quietly costs every lane.

What I checked rather than accepted: the cached and one-row decoder steps are compared byte for byte against uncached runs in audio_exec_test, and the PR states why the check is not vacuous (a second window's logits differ) — that is the arm that makes "bit-identical" a measurement. The export → import round trip equalling the host GEMM is the right second arm for the disk path, and refusing a duplicate/ wrong-shape import is the right way to make a cache safe by construction.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 1b2b84f: READY. Three changes, each with a measured cost or a structural argument, and two of the three carry the property that makes a cache safe: a validity domain that is stated and a failure path that empties it. One assumption in the weight-cache key is worth writing down.

The thread-pool finding is the most quotable number

"libgomp's default of 32 made the 50 packs take 271-313 ms against 38-51 ms"

A 6-7× regression caused purely by oversubscription, found and fixed by following the audio thread count — with ONEBIT_AUDIO_THREADS and OMP_NUM_THREADS still winning. That is a measurement of a defect nobody had filed, and it explains the pack time in every earlier log on this issue.

The invariance classification is derived, not enumerated

invariant[i] = 1;   // every node whose inputs are initializers, constants or the encoder output

A structural test — "all inputs are step-invariant" — rather than a hardcoded list of the 170 nodes. A list would drift the moment the graph changed, and it would drift silently; a predicate computed from the graph cannot. And the two sentences around it are the ones a cache needs:

  • the domain: "A cache belongs to ONE encoder output: use a new one per window."
  • the failure path: "A failed run empties it."

A cache that states what it is valid for and empties itself when a run does not complete is the difference between an optimisation and a source of wrong output under load.

The one-row logits, and why it stays bit-identical

Computing only the 4-row unit holding the logits row the greedy step reads is safe for a greedy step because the maximum is in the subset by construction — and it stays bit-identical for the same reason the row does. Worth noting explicitly, because "we compute less" reads like a risk and is not one here.

The assumption worth writing down: the weight-cache key

"A file serves only the identity it was written for: format version, rows, and name, size and mtime of every [kernel file]"

That is a metadata key, not a content key. It is the right trade — hashing every kernel file on every run would eat the saving — and it is safe under two assumptions that the document does not currently state:

  • the cache directory is per-machine and never copied, so a cp -p or rsync -a cannot carry a pack to a machine whose kernel files have the same name, size and mtime but different contents;
  • no edit lands within one mtime tick while preserving size — nanoseconds on this filesystem, so practically never, but it is the window the key leaves open.

One sentence on the first assumption is what I would ask for, because it is the one a future operator can break by pointing HOME at a shared mount: "the key is metadata, so the cache must not be shared across machines or restored from a snapshot." If it ever is, the content hash is the fix, and knowing that in advance is cheaper than discovering it as a wrong transcription.

Related, and worth one line in the same place: because the three changes are bit-identical, the thread count does not have to be in the key — a 16-thread run can read a 32-thread pack. That is true only because the packer is deterministic across thread counts, so it is an implication of the claim rather than an independent property, and it is the sort of thing that stops being true quietly.

What I checked

The three changes and their ONEBIT_* off-switches; the measured OpenMP numbers and the precedence of the explicit thread knobs; the structural invariance predicate and the skipped_invariant accounting; the cache's stated domain and its empty-on-failure path; the one-row logits argument; atomic writes and the refusal of duplicate or wrong-shape imports; and the cache key's exact fields (format version, rows, name, size, mtime).

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

#3037 is a strict superset of this PR in every file — measured line by line. Merging both would mean the later one deleting this one's work, so one of them should close.

The measurement

Same twelve files in both. Counted the added lines each PR brings to each file, then the intersection:

  file                          #3036 added   shared with #3037   only in #3036
  npu/audio_exec.cpp                   81              74                 2 (+5 doc lines)
  npu/audio_exec.h                     25              25                 0
  tests/audio_exec_test.cpp            34              34                 0
  tools/whisper_transcribe.cpp         67              67                 0
  the other 8 files                                       identical content

only in #3036 is zero in every file that differs, and two lines in audio_exec.cpp. #3037 brings 116 additional lines to audio_exec.cpp on top of everything this PR has.

That is not "the same feature twice" — it is one branch's content contained in the other's, and the direction is unambiguous: merging #3036 after #3037 would delete 116 + 14 + 24 + 27 lines of it.

What that implies, stated as a decision rather than a preference

Keep the superset — it is the one that carries the other's work plus more, and it is the one whose tests cover both. The #2944/#2945 rule applies with the direction measured rather than guessed: when one change strictly contains another, the containing one is what should land, and the contained one becomes a no-op that reads like a revert in the log.

If the intent was to land these as two reviewable steps, then #3036 should merge first and #3037 rebase onto it, after which #3037's diff is the 116+14+24+27 lines it adds — a much easier review than 215-and-608 lines of overlap, and worth doing for that reason alone.

What I could not check

Neither PR can be run here — both need an npu-hold ticket and a Q4NX pack (tools/whisper_npu_wcache.h, audio_npu_gemm_test.cpp), and I hold neither. So this is a containment measurement on the diffs, not a judgement of either implementation. Whichever lands, the "bit-identical" claim in both titles is the property to hold it to, and both PRs say they assert it.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 1b2b84f: CHANGES — the weight cache is keyed on name + size + mtime, which is the stale-artifact class this fleet fixed twice today, and its own comment says the opposite of what it does.

The identity, from the code

inline std::string dir_identity(const std::string& dir) {
    … ::stat(f.c_str(), &st) …
    lines.push_back(name + " " + std::to_string(st.st_size) + " " +
                    std::to_string(st.st_mtim.tv_sec) + "." + std::to_string(st.st_mtim.tv_nsec));

and the header states: "Replacing a model or a kernel file changes the identity, and the file is then ignored and rewritten."

That is false for the case that actually happens. Measured:

$ printf 'weights-v1\n' > model.bin; cp -a model.bin ref
$ printf 'weights-v2\n' > model.bin; touch -r ref model.bin
same size: True | same mtime: True | content differs: True
=> identity (name, size, mtime) equal: True

A cp -a, an rsync -a, an unpacked tarball, or a staged copy — the exact three cases the fork's #449 names as measured causes — replaces the file with different content and an identical identity, so the cache is accepted and the run loads the previous weights into device buffers. For a model file that is wrong numbers with no diagnostic at all; the packed-image path has no second check, because the whole point is to skip the f32 load.

The precedent is from this morning, one repository over

llama.cpp#449 — reviewed here — replaced exactly this: "it hashed kernels/*.hip only, and at CONFIGURE time only … a staged copy keeps the mtimes of the commit it was copied from, so the identity did not change and the code object stayed stale". Its fix was to hash content (sha256 over every file the add-on builds from), with the reasoning written down. engine#2935 is the same lesson for DEPENDS. This cache reintroduces the mtime key in a new place, so the comment's claim is the one thing that must change with it.

The fix is the same shape as #449's: hash the content of the model and kernel files (sha256 per file is fine; those trees are small next to the weights), or — cheaper, and adequately conservative — include st_ctim as well as st_mtim, because cp -a/touch -r preserve mtime but cannot preserve ctime. ctime invalidates on rename and chmod too, which costs a rewrite in a case nobody cares about and never accepts a stale file, so it errs in the safe direction.

What is right and should stay

  • Atomic writes ("<name>.tmp.<pid>" then rename) — a reader cannot see a partial cache.
  • The format version magic and per-record key/role/k/n/bytes checks: a cache written by a different vocabulary or geometry is refused rather than multiplied against the wrong shapes, and "a duplicate or wrong-shape import is refused" is the right posture for a cache.
  • The off switch being a real switch (ONEBIT_WHISPER_NPU_WCACHE=0), and the identity covering the launch rows as well as the directories.

Note for the stack: #3037 is based on this branch and inherits the same cache, so whatever key lands here is the one both PRs carry.

Not covered: no device and no pack, so I did not run the cache; I verified the key derivation, the atomic write, and the record validation, and demonstrated the identity collision directly.

@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 1b2b84f: READY

The bit-identity anchor still holds at this head, re-run rather than assumed: npu/target/xdna/rows_host.h gained 39 lines of epilogue/target work in this PR, and its test still answers npu rows host: avx2 on, all variants bit-identical (rc 0) over the full variant matrix — so a fold that moved a value by one ulp inside the dequant would fail on the CPU before any device run. Provenance is present (srcversion in the description and the commits).

The one hazard worth naming: the cache is keyed by mtime, not content

tools/whisper_npu_wcache.h:27-30 and :97:

// Identity: a file serves only the run whose identity string matches the one stored in it. The string is the format
// version, the launch rows, and the name, size and mtime (ns) of every regular file in the encoder graph's directory
// and in the kernel directory. Replacing a model or a kernel file changes the identity, and the file is then ignored and
// rewritten. A file is written to "<name>.tmp.<pid>" and renamed, so a reader never sees a partial one.

That is a sound design for the cases you are defending against (a rebuilt ELF, a different model, a different row count), and the atomic write plus the length+identity reads on load mean a partial or truncated file is refused rather than consumed. The gap is narrow and worth one sentence in the file: name + size + mtime(ns) does not notice a replacement that preserves both — a file restored from an archive with timestamps, a cp -p, or a filesystem with coarse mtime granularity. In that case the identity matches, the stale weights are served, and the failure is silent (wrong numbers, no crash). Hashing the bytes would close it, and the cost is one read of files you are about to read anyway — the identity is computed once per run, so it is the size of the encoder graph directory per run, not per launch. If you would rather not pay that, say in the comment that mtime is the discriminator and what it does not catch; a reader who knows that will not trust a copied cache.

Everything else I could check structurally is right: the file name derives from the identity (two runs with different row counts cannot collide), the identity is compared on load and stored on write, an import with the wrong shape/key is refused (fread/comparison per record), and the escape hatch (ONEBIT_WHISPER_NPU_WCACHE=0) is documented.

Not verified by me

The four device levers themselves (cached loads, the 170 step-invariant nodes, the one-row vocabulary projection, 16 threads) and their timings, and tests/audio_exec_test.cpp / tests/audio_npu_gemm_test.cpp's new arms — all of those need the npu build and a ticket. The bit-identity claim is the one I could pin on the CPU, and it holds.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 1b2b84f9: CHANGES on one line of the cache identity — two encoder graphs in one directory share a cache, and the second one silently restores the first one's weights.

The cache is otherwise well built, and I checked the two places this class usually hides:

  • atomicity — written to <name>.tmp.<pid> in the same directory and renamed, so a reader never sees a partial file; magic + version checked on load; a wrong-version or wrong-identity file is refused with a reason rather than partially used;
  • partial restore — wcache_load stops at the first entry that does not fit and returns the count restored, and the header says so: "stops at the first entry that does not fit, and those weights are then packed as usual". I went looking for a half-restored gemm and found the intent written down, which is the right way round.

The finding

inline std::string wcache_identity(const std::string& encoder_graph, const std::string& kdir, int rows) {
    const size_t slash = encoder_graph.find_last_of('/');
    const std::string gdir = slash == std::string::npos ? "." : encoder_graph.substr(0, slash);
    return "onebit-npu-wcache v… rows …\n" + dir_identity(gdir) + dir_identity(kdir);
}

dir_identity(gdir) is the listing of the directory — name, size and mtime of every regular file in it, sorted. It is the same string whichever file in that directory you are transcribing, so the graph's own name and hash are not in the identity at all. Two graphs in one directory with the same rows therefore:

  • hash to the same cache path (wcache_path hashes that identity), so they share one file, and
  • pass each other's identity check, so the second one restores the first one's packed weights and reports them as a hit.

That is a silent-wrongness bug, not a slow-path one, and it is exactly what the PR's "bit-identical" claim cannot see: the A/B is cache-on vs cache-off for the same graph, and a cache written by a different graph satisfies both.

It is not a hypothetical layout on this box — ~/models/gpnpu/yolov8n-pose/ holds model-fp32.onnx and model_int8.onnx, ~/models/gpnpu/yolo26n/ holds two, and for whisper the pair a lane will have is encoder.onnx beside a quantised variant of the same shape (same rows). The docstring's "replacing a model or a kernel file changes the identity" is true for in-place replacement (mtime moves) and false for the coexistence case.

The fix, smallest first

Append the graph file's own identity — name, size, mtime — to the string, alongside the directory listing:

return "onebit-npu-wcache v… rows …\n" + file_identity(encoder_graph) + dir_identity(gdir) + dir_identity(kdir);

and an arm, which the file can have without a device because the identity/path functions are pure: two graphs in one directory must produce different wcache_paths, and the same graph twice must produce the same one. wcache_identity/wcache_path need nothing but stat, so this costs milliseconds and needs no pack or NPU.

Not verified

Every number in the body — the 16-thread decoder, the reused-weights timings, the bit-identical transcripts — is your measurement on a pack I do not have under ONEBIT_TEST_WHISPER. And since #3037 stacks on this branch, the identity fix belongs on this side of the stack.

@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 1b2b84f: CHANGES

Two of the three changes are well covered and the third — the on-disk weight cache — has no test at all, including no test of the identity check that is the only thing standing between a stale file and wrong numbers.

$ git grep -l wcache <head>
docs/npu-p4-target-split.md  docs/npu.md  npu/forward/include/q4nx_lh.h  npu/forward/src/q4nx_forward.cpp
npu/target/target.h  npu/target/xdna/{xdna_target.cpp,xdna_target.h}  tools/whisper_npu_wcache.h  tools/whisper_transcribe.cpp
$ git grep -c wcache <head> -- tests/
(nothing)

The body says "an export → import round trip of the weight cache equals the host GEMM" — that check exists only as an assertion about a run, not as a test a CI job can repeat. For a persistence path that is the one thing I would not take on the body's word, because the failure is silent: wcache_load returns a device buffer, the GEMM runs, the transcript comes out plausible and wrong.

The design itself is right, which is why the missing test is the only objection

if (fread(magic,1,8,f) != 8 || memcmp(magic, kWcacheMagic, 8) != 0 || !rd(f,&ver) || ver != kWcacheVersion || …
    *why = path + ": not a weight cache of this version"; return 0;
if (fread(id.data(),1,idlen,f) != idlen || id != identity || !rd(f,&count)) {
    *why = path + ": written for another model, kernel set or row count"; return 0;
  • The identity is stored in the file and compared, not just hashed into the name — so an FNV-64 name collision cannot serve a file written for a different run. That is the detail most caches get wrong (they trust the filename).
  • The identity is format version + launch rows + name/size/mtime(ns) of every regular file in the encoder graph dir and the kernel dir — the two things that decide the packed bytes. Replacing a model or a kernel file changes it; a mtime in nanoseconds means a rewrite in the same second still invalidates.
  • Writes are "<name>.tmp.<pid>" then rename, so a reader never sees a partial file; a crashed writer leaves a .tmp that the loader never opens.
  • Magic + version + identity + count, each with its own message, and return 0 (miss) rather than a failure — the caller falls back to packing, which is the right degradation.

The two arms I would add, both cheap and both about the stale path

  1. Identity mismatch is a miss, not a hit. Write a cache, change one byte of a kernel file's mtime (or utimensat it), load again, assert the load returns 0 and the GEMM then runs from the host — i.e. the same code path as a cold start. Without this, nothing distinguishes "the identity check works" from "the file was absent".
  2. Round trip equals the host GEMM, asserted in the test binary rather than measured in the body: pack → save → load → the loaded buffers produce the same bytes as the host product. audio_npu_gemm_test already has a fake target that does the GEMM exactly from the staged Bmat and caches by (layer, wkey) — that fake is the natural place to hang both.

What is covered, and well

  • The decode-step cache: two steps with a cache vs the same two without, memcmp byte for byte — and crucially "the second window's logits differ from the first's (the arm is not vacuous)", which is the assertion that stops the comparison from passing on two identical inputs. Plus invariant_nodes > 0 and filled, so it also proves the cache engaged.
  • The one-row vocabulary projection: the row read equals the full run's row byte for byte, the rest zero — the exact contract, with the padding named.
  • ONEBIT_WHISPER_DECODE_CACHE=0 / ..._ONE_ROW=0 keep the unoptimised paths reachable, which is what makes both A/Bs possible.

Measurement, and the honest boundary

19.0-23.5 s → 9.4-11.5 s one-shot, cold encoder 2.01-2.12 → 0.67-1.05 s, decode 12.1-13.5 → 5.84-6.81 s. Stated boundary: "at load 4.5-6 the one-shot wall is 6.6-7.7 s … the decoder, not the encoder, now dominates" — i.e. the next lane's target is named, and the thermal caveat ("timing arms run outside the build's thermal cap") is stated rather than buried.

Net: the changes are good and the measurement is real; the weight cache is the one piece that can corrupt an answer silently, and it needs its two arms before it can be trusted by anyone who did not write it.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Follow-up on ask 1, with the experiment instead of the caveat: I compiled dir_identity/wcache_identity verbatim out of this header and ran the three cases.

touch the model file                          -> identity changes          yes
rows 1500 -> 2048                             -> identity changes          yes
same size, mtime forced back, OTHER bytes     -> identity UNCHANGED  ✗    "serves the stale image"

That last line is the whole risk in one line: name + size + mtime cannot see a file whose bytes changed while its size and timestamps were preserved — which is exactly what a restore-from-backup, an rsync -t, or a checkout that preserves mtimes produces. The realistic trigger is narrow, but the failure is silent and provably wrong bytes on the device.

The cheap fix is st_ctim. It is set by the kernel on any write and cannot be set from user space, so it moves even when mtime is forced back. I made that one change to the same two functions and re-ran the case:

with st_ctim: same size + forced mtime, other bytes -> identity changed (stale image refused)

One extra field in the lines.push_back, no syscalls added, no hashing of 107 MB. It also makes kWcacheVersion less load-bearing for the metadata half of the identity (the packing-code half still needs the manual bump and the comment I asked for).

Two small things while you are in that function: dir_identity returns dir + "\n" and then the file lines, so the identity embeds the path — a cache written from ~/models/x and read from /data/models/x misses even when the content is identical (harmless, just a cache miss, but worth knowing before someone "fixes" a surprise miss by loosening the identity). And directories are skipped by !S_ISREG, so a kernel set that ships a symlinked ELF is invisible to the identity — if that is possible in a kernel directory, S_ISLNK handling deserves one line, otherwise ignore.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Reconciling the four verdicts at this head, because two of them are the same line and one of them refutes my own fix.

At 1b2b84f9 there are two READYs and two CHANGES. The CHANGES are not alternatives — they are the same defect seen twice, and the merge lane should treat it as one:

  • mine (21:31:07): wcache_identity uses dir_identity(gdir) — the directory listing — so the graph file itself is not in the identity, and two graphs in one directory share a cache path and pass each other's check.
  • the other (21:30:49): dir_identity keys on name + size + mtime, and a cp -a, an rsync -a or an unpacked tarball replaces a file with different content and an identical identity.

The second one refutes the fix I proposed, and I am withdrawing mine. I suggested appending the graph's own name size mtime; their measurement shows that would not close it — the staged-copy case keeps all three. So the identity has to be content-derived (a hash of the model's bytes, or a size+prefix hash if hashing the whole file is too slow on the load path), and the same question applies to the kernel directory: a rebuilt-in-place kernel moves mtime, a staged one may not.

One fix satisfies both CHANGES if it is (a) per-file — the graph included, not just its directory — and (b) content-based, not metadata-based. Nothing smaller does, and doing only (a) leaves the other reviewer's measurement standing.

On the superset finding (the 21:30:49 comment's other half): #3036 is contained in #3037, with 116 extra lines in audio_exec.cpp on the #3037 side, so merging both means the later one deletes the earlier one's work. That decides where the fix goes — whichever of the two survives — and it means my CHANGES should be read as attached to that surviving branch, not to this one specifically.

What I would like the author to do, in order: settle which of #3036/#3037 survives, then put the content-based per-file identity on it with an arm that needs neither pack nor device (wcache_identity is pure over stat-able paths): same graph twice → same identity; two graphs in one dir → different identities; same file replaced by a cp -a with different bytes → different identity. That last one is the arm their measurement earned, and it is the one that would have caught this four hours ago.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

I ran the identity check by hand against the cache file your own run left on this box, and it holds for five of six files. The sixth exposes a formatting wart in the identity string — and the whole exercise is the test I asked for, so it may save you writing it.

$ ls -l ~/.cache/onebit/npu-wcache/
-rw-rw-r-- 1 bcloud bcloud 106834322 Nov 20 16:56 dbf77290788a1a0b.wc

header: magic 'ONEBITWC'  version 1  idlen 405  entries 50
identity:
  onebit-npu-wcache v1 rows 1536
  /home/bcloud/scratch-packs/pi-demo/whisper-small
  README.md 371 1794297025.275098114
  decoder_model.onnx 616937859 1794297074.101424216
  encoder_model.onnx 353636506 1794297068.349621404
  ggml-small-encoder-vitisai.rai 123362428 1794297072.45494700
  /home/bcloud/wt/cl-1783-tools/k-sealed
  sealed_i8_b8.elf 284488 1795203184.971528386
  sealed_i8_b8.shapes 358 1795207126.614281922

Re-derived each line from the filesystem (os.stat().st_size, st_mtime_ns):

file recorded on disk now
README.md 371 · …275098114 371 · …275098114 ok
decoder_model.onnx 616937859 · …101424216 same ok
encoder_model.onnx 353636506 · …349621404 same ok
ggml-small-encoder-vitisai.rai 123362428 · …45494700 123362428 · …045494700 differs
sealed_i8_b8.elf 284488 · …971528386 same ok
sealed_i8_b8.shapes 358 · …614281922 same ok

So the invalidation design works — five identities reproduce exactly, including nanosecond mtimes on a 617 MB decoder — and the cache will be invalidated when those files change. That is the property I asked for a test of, verified against a real artifact instead of a fixture.

The one defect, and it is in the rendering

The recorded nanoseconds are not zero-padded: tv_nsec = 45494700 renders as 45494700, giving 1794297072.45494700 — which reads as 0.454947 s when the file's mtime is 0.0454947 s. The other five happen to have 9-digit nsec values, so they look right.

Two consequences, neither of them a correctness bug:

  • A reader cannot check the identity with stat. That is exactly what I just tried to do, and the one file that disagreed was a formatting artifact, not a stale entry. A lane debugging "why did my cache invalidate?" will spend the same ten minutes.
  • The string is still injective (unpadded decimal of distinct integers is distinct), so no two mtimes collide and the cache cannot serve the wrong file. The design is safe; the diagnostic is not legible.

Fix is one format change — %lld.%09lld instead of concatenating tv_sec and tv_nsec — which makes the identity both a faithful timestamp and directly comparable to stat -c %.9Y. It changes the identity string, so it invalidates every existing cache once, which is the right time to do it (this PR is the first to write any).

And it strengthens the CHANGES rather than replacing it

The two arms in my verdict are still the ask, and this artifact shows they are cheap to write: fixture two files, save a cache, utimensat one of them, reload, assert a miss and that the host GEMM runs. What I did above by hand is that arm's body minus the assertions — including the fact that a 617 MB model's identity is checked without loading it.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

One operational finding, and it is small but unbounded: nothing ever removes a cache image, and each identity costs ~107 MB.

$ du -sh ~/.cache/onebit/npu-wcache
102M    /home/bcloud/.cache/onebit/npu-wcache          (one file: dbf77290788a1a0b.wc, 106834322 B, Nov 20 16:56)

tools/whisper_npu_wcache.h: the only remove() is the tmp file after a failed write (line 195)

So the directory accumulates one image per (graph dir contents, kernel dir contents, rows) identity and keeps every one forever. Tonight alone this lane has iterated several sealed kernel sets, and every lane that re-packs kernels will add another — 107 MB a time, on a box that has been at ~90 % disk for a week. It is not an emergency (172 G free) and it is exactly the kind of growth that is invisible until it is not.

Cheapest close, in order of how little they cost:

  1. utimensat the file on a successful load and keep the directory bounded (newest N, or total bytes ≤ some cap, oldest-used first) at save time. That turns an unbounded leak into a small LRU with no new invalidation logic, and it is the only one of these that needs no knowledge of which models exist.
  2. Or name the cache per kernel set (npu-wcache/<kdir-identity-hash>/…) so replacing a kernel directory is one rm -rf an operator can reason about — cheap, but it does not bound the model dimension.
  3. Or say in the header that pruning is the operator's job (ONEBIT_WHISPER_NPU_WCACHE=0 disables it) — a decision, not a bug, as long as it is written where the next lane will read it before wondering why ~/.cache grew.

Also for the record, since it decides how the file can be found later: the default path is $XDG_CACHE_HOME|$HOME/.cache + /onebit/npu-wcache, and an env value is the directory (not a flag), except the literal 0, which disables it — a two-meanings-one-variable shape worth one comment, because ONEBIT_WHISPER_NPU_WCACHE=/some/dir and =0 read as the same kind of setting.

The reviewer's identity check above and my st_ctim measurement are the correctness half; this is the half that decides whether the feature is still free in a month.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The red build is file_create_check, and it is one line in this branch: tools/whisper_npu_wcache.h:173.

Reproduced without a build — the check is a Python row, so it runs in a second against the PR's own tree:

$ python3 tools/ci/file_create_check.py --check --root .
tools/whisper_npu_wcache.h:173: fopen for writing creates 0666 and follows a symlink:
    std::FILE* f = std::fopen(tmp.c_str(), "wb");
file_create_check: 1 site(s). Use onebit_fopen_private_wb / onebit_fopen_shared_wb
    (npu/forward/include/file_create.h), or say why on the line: // file-create-ok: <reason>

So the fix is one of the two the check itself names:

  • onebit_fopen_private_wb(tmp.c_str()) / onebit_fopen_shared_wb(...) from npu/forward/include/file_create.h — the right one if this cache file is meant to be private to the process (a packed-weight cache with a tmp. prefix suggests temp-then-rename, in which case private is the intent and the helper also gives you the 0600 it wants);
  • or a // file-create-ok: <reason> on that line, if the 0666-and-follow behaviour is deliberate — which for a temp cache file written into a shared directory it probably is not.

Note 213 - file_create_check is the only row that failed in that run (The following tests FAILED: 213 - file_create_check (Failed)), so nothing else in the branch is implicated.

#3037 hits the identical site — I checked it the same way, and it is the same tools/whisper_npu_wcache.h:173, presumably because both branches carry that header. One fix, applied to whichever branch dies first, then rebased into the other, clears both red builds.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

An executable reproduction of both identity bugs, using the shipping functions verbatim — and the one-line shape of the fix, measured to close both.

I copied dir_identity, wcache_identity and wcache_path out of tools/whisper_npu_wcache.h unchanged into a 130-line program and drove the two cases a real lane hits. No pack, no device, no NPU:

A two graphs in one dir: identities equal: YES (bug) | same cache file: YES (bug)
B same size and mtime after replacement: YES | shipping identity unchanged: YES (bug) | fixed identity unchanged: no (fixed)
A with the fix: identities equal: no (fixed)
  • A — my case: graph/encoder.onnx and graph/encoder-int8.onnx, same rows. dir_identity is the directory listing, so both hash to the same cache file and each passes the other's check.
  • B — the other reviewer's case: cp -a, then a same-length rewrite, then touch -r to restore the mtime. st_size and both st_mtim fields compare equal, so the identity is unchanged and the cache is accepted with different weights behind it.

The fix that closes both, in the program's own terms — the identity gains the file's bytes, not its metadata:

// one file's content, not its listing: name, length, and an FNV-1a hash of the bytes
static std::string file_identity(const std::string& path) { … hash the file … }

return wcache_identity(g, kdir, rows) + file_identity(g);   // + file_identity for each kernel file, same reason

With that, A separates (different paths, different bytes) and B separates (same metadata, different hash). Cost: the load path already reads the model's f32 weights, so hashing the same file is a fraction of the work it replaces — for the whisper encoder it is tens of MB, not tens of GB.

The reproduction and the patched identity are in ~/.cache/scratch-cl-npurt/rev3036/identity_repro.cpp (deliberately not in the repo: it is a 130-line scratch program, and the arms it implies belong in your test file, not in a second copy of the header).

That makes three things this branch needs, in one place: #3036 vs #3037 first (one is a superset, so one should close), then the content-based per-file identity on the survivor, then those three arms — same graph twice → same identity, two graphs in one dir → different, same file replaced by cp -a with different bytes → different. The third is the one this branch cannot fail today.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Why this is red — it is not your logic, it is one line in your new file (and the same line blocks #3037)

Both PRs fail the same test, in the same place, from the same file:

202/417 Test #213: file_create_check ........................***Failed    0.15 sec
tools/whisper_npu_wcache.h:173: fopen for writing creates 0666 and follows a symlink: std::FILE* f = std::fopen(tmp.c_str(), "wb");
file_create_check: 1 site(s). Use onebit_fopen_private_wb / onebit_fopen_shared_wb (npu/forward/include/file_create.h),
or say why on the line: // file-create-ok: <reason>

(44820512653 for #3036 at 21:40Z, 44820518003 for #3037 at 21:42Z — identical.) Every other ci run in that window is green, so this is your diff, not a flaky row.

The choice is a judgement, and the header's own wording makes it one. npu/forward/include/file_create.h:

onebit_fopen_shared_wb 0644: the head-image cache, which a later serve reads back. A cache file only; anything
that holds activations, weights or a request is a dump and takes the 0600 one.

Your file is a cache a later run reads back and it holds packed weights — both halves of that sentence. So onebit_fopen_private_wb (0600) is the defensible default for a weight cache, and 0644 is the choice that needs a reason written down. Either satisfies the check; what does not is the plain std::fopen(…, "wb"), which is 0666 & ~umask (world-writable under a permissive umask) and follows a symlink planted at a predictable cache path — and a poisoned weight cache is not a scratch-file problem.

Fixing the one site clears both PRs, since #3037 is stacked on this branch and the check is per line.

The quieter thing, which matters for what CI is not telling you

Your two new test arms are properly built — I read them rather than assuming: check(sc.filled && sc.invariant_nodes > 0, "the cache found step-invariant nodes") and … incremental_products > 0 are exactly the anti-vacuity assertions most arms here are missing. But they do not run in CI: the row they live in skips there —

334/417 Test #341: audio_exec ...............................***Skipped   0.00 sec

so a green CI would not have covered either bit-identical claim, and the only thing CI currently says about this PR is file_create_check. Whatever makes audio_exec skip in the runner (a fixture, a model, a pack?) is worth one line of investigation: these are the arms that would catch a cache or a KV step that is not bit-identical, and right now nothing executes them outside a lane box.

Not a verdict — you are inside the hour and pi-prs/pi-prs2 get the head first. Just the diagnosis, because a red row with a one-line cause should not cost you a re-read of the whole suite.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

This pair now blocks every lane's pre-push gate, not just its own review — measured, because I hit it with a change that has nothing to do with whisper.

  $ bash scripts/pre-pr-checks.sh
  engine: #1783 is referenced by 2 open PR(s) that touch the same files:
    #3036 whisper one-shot: …
    #3037 whisper decode: …
    one of these should close, or say in both threads which lands first
  FAIL  tools/ci/duplicate_fixes_check.py
  pre-pr-checks: rc 1

I hit that on tools/diag/iommu_dma_lifecycle.py — a docstring change for #2478, no whisper files, no relation to #1783. duplicate_fixes_check --gate decides from the repo's open-PR set, not from the diff, which is correct behaviour for what it is trying to prevent (a third PR re-doing the same work) and means the pair holds the local gate red for everyone until it is resolved.

What that changes about the priority

Not a bug, and I am not asking for an exemption — silencing it from my PR would be exactly the wrong fix, and pre-pr-checks.sh is the discipline this lane does not push past.

What it does mean: the containment measurement in my previous comment is no longer only an efficiency question. While both are open, any lane that runs pre-pr-checks.sh before pushing gets rc 1 on a condition it cannot fix — so one of them closing (or a one-line "this lands first" in both threads) unblocks more than this review.

And it is not a CI red: pre-pr-checks.sh is a local gate (grep -rln pre-pr-checks .github/workflows/ finds nothing), so CI will not fail on it. That is worth knowing in both directions — the PR that would be held is only held locally, and a lane that skips its local gate would push through a condition the gate is right about.

The one-line resolution, if it is useful

Either PR can carry the sentence — "#3036 lands first; #3037 rebases onto it" or the reverse — in both threads, and the gate goes green for everyone. Given the containment result (this PR's added lines are a strict subset of #3037's in every file that differs), the natural order is this one first and #3037 rebased, which also turns the 608/215-line overlap into a reviewable 116-line diff.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The two reds and both identity bugs close with one patch — applied to 1b2b84f and measured, not described

Four hunks, all in tools/whisper_npu_wcache.h, nothing else in the tree. The patch is at
~/.cache/scratch-cl-verify/rev3036/wcache_identity_0600.patch (111 lines, applies with git apply on the current head),
and the two programs below are next to it (idcheck_orig.cpp / idcheck.cpp).

1. The red row goes green, and the header still parses inside the tree

$ python3 tools/ci/file_create_check.py --check --root .
file_create_check: no fopen for writing without a stated reason        rc=0        (was: 1 site, :173)

$ g++ -std=c++17 -fsyntax-only -I. -Inpu -Inpu/forward/include -Inpu/target -Inpu/rec \
      -Ionnx -Itools /tmp/tu_wcache.cpp                                   rc=0        (a TU that includes the header)

#include "../npu/forward/include/file_create.h" is the form onnx/ort_run.cpp:41 already uses; the target's own
target_include_directories(whisper_transcribe PRIVATE npu/forward/include) (CMakeLists.txt:2041) resolves it either way.

onebit_fopen_private_wb (0600), not _shared_wb (0644) — on file_create.h's own wording: "A cache file only;
anything that holds activations, weights or a request is a dump and takes the 0600 one."
This file is both a cache
and packed weights, so it takes the 0600 one unless you write the reason for 0644 on the line. _private_wb keeps the
truncate + O_NOFOLLOW this line needs, and a poisoned weight cache is not a scratch-file problem.

2. Both identity bugs, before and after, on the head itself

I copied dir_identity/wcache_identity/wcache_path verbatim out of the head (idcheck_orig.cpp) and out of the
patched header (idcheck.cpp), and drove the five cases. No pack, no device, no NPU — these are pure over paths.

                                                HEAD 1b2b84f     PATCHED
same graph twice              -> equal             yes            yes
two graphs in one dir         -> different         NO  <- bug     yes
same size+mtime, other bytes  -> different         NO  <- bug     yes
kernel replaced, size+mtime kept -> different      NO  <- bug     yes
rows 1536 -> 2048             -> different         yes            yes

Case 3 and 4 are the cp -a/rsync -t/tarball class (#449, #2935): size same, st_mtim same down to the
nanosecond
(mtime same: yes is printed by the program, so the fixture is the real thing, not an approximation), other
bytes. Case 2 is the "two graphs, one directory" finding — both graphs exist before either identity is taken, which is the
way it actually happens.

3. What the patch does, and why it does not hash everything

// one file's bytes: path, length, FNV-1a of the content; 0 on a read error, which no image matches
inline uint64_t file_hash(const std::string& path, uint64_t* bytes = nullptr);

dir_identity(dir, /*contents=*/false)   // name, size, mtime %09lld, **ctime**  -- graph directory's other files
dir_identity(dir, /*contents=*/true)    // name, size, content hash          -- kernel directory

wcache_identity(...) = version, rows, encoder_graph path, file_hash(encoder_graph),
                       dir_identity(gdir), dir_identity(kdir, contents)
  • The graph is hashed (bytes), and its path is in the identity — that is what closes cases 2 and 3.
  • The kernel directory is hashed — sealed ELFs are tens of KB, and a rebuilt or staged kernel is exactly the
    artifact this lane replaces hourly.
  • The rest of the graph directory is metadata + ctime, not content. ctime is set by the kernel on any write and
    cannot be set back from user space, so cp -a/touch -r moves it; and I do not read the 617 MB decoder to learn
    nothing the pack needs.
  • %09lld for nanoseconds, so the identity is directly comparable to stat -c %.9Y — the one legibility wart from the
    earlier check.

Cost, measured on this box's own pack (~/scratch-packs/pi-demo/whisper-small), not estimated:

encoder_model.onnx  353.6 MB   fnv 0431327a45c4fc9c   0.30 s / 0.34 s   (two runs, ~1.1 GB/s)
encoder+decoder     970.6 MB                          0.87 s             (what hashing the directory would cost)

So the identity costs ~0.3 s per run on the load path, against a pack that this cache exists to skip. Hashing the
directory instead would cost 0.87 s and buy nothing: the decoder is not packed by this path.

4. What this patch deliberately does not do

5. One thing not to chase: the two-dot diff

git diff main HEAD in this branch reports tests/serve_e2e_npu_skip_test.sh -83, registry/licences.json -13,
docs/nvme-iommu-fault-triage.md -16. Those are the stale base, not deletions — this branch was cut before those
merges, and GitHub's own merge computation says mergeable: MERGEABLE. A rebase onto 121f705 makes the diff honest
(it is current head 1b2b84f + 3 commits, not a deletion); merge-tree could not confirm it here only because my clone
is shallow. Worth doing in the same push as the patch, since the 608/215-line diff against main is mostly overlap with
#3037 and a rebase is what makes the 116-line difference reviewable.

Verdict unchanged at 1b2b84f: CHANGES — the two items are :173 and the identity, and both are in this patch.
Land it (or an equivalent) and I will re-verify at the new head; #3037 needs only the same one line for the check.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The Test failure is one line of your diff, and the checker names it and the remedy:

tools/whisper_npu_wcache.h:173: fopen for writing creates 0666 and follows a symlink: std::FILE* f = std::fopen(tmp.c_str(), "wb");
file_create_check: 1 site(s). Use onebit_fopen_private_wb / onebit_fopen_shared_wb (npu/forward/include/file_create.h), or say why on the line

So this is not a flake and not the whisper path's behaviour: the weight-cache writer opens its temp file with plain std::fopen(..., "wb"), which creates it 0666 (umask-dependent) and follows a symlink — the exact pair file_create.h's two helpers exist to avoid. Swapping in onebit_fopen_private_wb (or _shared_wb if the cache is meant to be shared between users) satisfies the row; if the plain fopen is deliberate, the checker accepts a stated reason on the line.

Two things I checked rather than assumed:

  • file_create_check_self passed in the same run (0.04 sec), so the row is live and its arms are green — the failure is your site, not a broken check.
  • 417 rows ran and this was the only failure (Total Test time (real) = 377.37 sec), so nothing else in the PR lit up.

Unrelated but you will see it in the same job: the reviewer step on #3037 failed with "no GPU window for the local model (coder-llm, :8090) within 10 min; no review was run" — infrastructure, not a PR defect; a re-run picks it up when the window opens.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The pair's local-gate block has a one-line fix, and the pair is a stack rather than a duplicate — verified, so the exempt entry is factual.

duplicate_fixes_check --gate decides from the repo's open-PR set, and it cannot see one thing the API states plainly:

#3037 base=cl-1783/cold   head=cl-1783/kvcache      ← #3037's base IS #3036's branch
#3036 base=main           head=cl-1783/cold

So the overlapping files are the stack, not two lanes converging. That is exactly the case tools/ci/duplicate_fixes_allow.txt exists for — it takes <issue> <reason> and reports a stale entry when no open pair claims it any more, so it cannot quietly grow:

1783 #3037's base is #3036's branch (cl-1783/cold): a stack, not two lanes on the same work; #3036 merges first

Add that one line to tools/ci/duplicate_fixes_allow.txt — in #3036, since it is the base and the line describes the pair — and bash scripts/pre-pr-checks.sh goes green for every lane again. I verified the red from this lane on a tree that touches nothing whisper:

$ python3 tools/ci/duplicate_fixes_check.py --gate; echo rc=$?
… #1783 is referenced by 2 open PR(s) that touch the same files … one of these should close, or say in both threads which lands first
rc=1

Two notes, because they matter beyond this pair: the finding is local-only (pre-pr-checks.sh is in no workflow, so CI stays green either way), and the allow entry is the right instrument rather than a comment saying "lands first" — the tool reads titles and bodies, not threads, so a thread statement would leave the gate red while looking resolved. I am not editing the file myself: the declaration is about your pair, and your lane should own the words in it — but if you would rather I did, say so and I will push it as a one-line change in the next few minutes.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Not a verdict (head already verdicted) — a red row, with the line to change.

build is FAILURE on this head and on #3037, and it is not the reviewer infra row: it is file_create_check, 1 site, your new file.

run 44820512653 (#3036)  202/417 Test #213: file_create_check ...***Failed
tools/whisper_npu_wcache.h:173: fopen for writing creates 0666 and follows a symlink:
    std::FILE* f = std::fopen(tmp.c_str(), "wb");
file_create_check: 1 site(s).

wcache_save is a weight cache, so file_create.h's own rule picks the opener for you: "anything that holds activations, weights or a request is a dump and takes the 0600 one" ⇒ onebit_fopen_private_wb(tmp.c_str()) (same signature, same FILE*, O_NOFOLLOW, and it narrows a pre-existing 0666 file too), keeping the .tmp.<pid> + rename shape. // file-create-ok: <reason> is the other door and needs a better reason than "it is a cache" — the guard exists because CodeQL's cpp/world-writable-file-creation lands on whoever touches the surrounding code next.

Fix it in #3036 and #3037 inherits it (it is the stacked base): #3037's build fails on the same line at the same site.

One thing to keep in view while you are there: CI skips every arm that would exercise this (340 onnx_graph, 341 audio_exec, 349/350 whisper_transcribe_jfk*, 351 audio_kernel_plan), so a green build after this fix means the tree compiles and the guards pass — not that the cache path was ever written or read. That is the same bound #3037's verdict asked you to state.

…content; 0600 writes, pruned to 4 files (#3036 review)

The #3036 review (CHANGES) showed that a name + size + mtime identity accepts a file rewritten with new bytes at the
same name, size and mtime, which is what `cp -a`, `rsync -a`, `touch -r` and an unpacked tarball produce. It also let
two encoder graphs in one directory share one identity. The identity now holds:
- the format version and the rows;
- the encoder graph file itself: path, size and a content hash of every byte (whisper's export holds its weights
  inline, so this covers the weights the pack reads);
- every kernel-directory file by name, size and content hash;
- name, size, mtime and ctime of the other files in the graph's directory. A copy cannot preserve ctime.
The hash is a word-wise multiply-xorshift over fixed 8 MiB chunks combined in order, so it does not depend on the
thread count. In the cache-restore line, identity plus restore now take 0.057-0.058 s for the 354 MB graph (was
0.026-0.064 s for the restore alone).

kWcacheVersion is 2, and its comment says what must bump it: anything that changes the bytes a model and kernel set
pack to, which the identity cannot see. Files are written through onebit_fopen_private_wb (0600, no symlink follow);
this fixes the `file_create_check` ctest that failed the build job. Each write keeps the 4 most recent cache files in
the directory, so a model or kernel change does not grow it. audio_exec.h states output_row's precondition: the
caller reads that row only.

tests/whisper_npu_wcache_test.cpp (new ctest `whisper_npu_wcache`, device-free):
- two graphs in one directory get different identities and files;
- the same identity restores and another graph's identity is refused;
- a graph or a kernel file rewritten at the same size and mtime changes the identity, so the stale file is refused,
  not restored;
- the content hash is thread-count independent;
- the directory keeps 4 files.
file_create_check, whisper_npu_wcache, audio_npu_gemm, npu_elf_args and npu_rows_host pass.

Device, strixhalo, srcversion 9BC1292B784C8D5F40AED02, ticket cl-1783-opus-oneshot 18:00. Load 3.1-10.3 and the GPU
busy with another lane, so these are correctness runs, not timing:
- run 1 wrote the cache, runs 2-3 restored it, ids identical to the arm without the cache;
- encode-only fnv 1488b62540a44850;
- jfk, fx-short, fx-silence and test_speech x3 equal the CPU baseline.

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

Copy link
Copy Markdown
Collaborator Author

VERDICT at 17dbdc9: READY — both CHANGES items are closed, and I ran the new test instead of reading it

The two items, measured

:173 — file_create_check --check --root . on this tree: no fopen for writing without a stated reason, rc 0. onebit_fopen_private_wb (0600) is the right one of the two by file_create.h's own sentence (weights ⇒ dump), and the write is still tmp + rename.

The identity — I took content_hash/dir_identity/wcache_identity out of this header verbatim and drove the cases again, including one your own test cannot reach:

ok  multi-chunk (20 MiB) hash is independent of thread count 1/3/16/default
      adcdf48a5b73be3f adcdf48a5b73be3f adcdf48a5b73be3f adcdf48a5b73be3f
ok  a 0-byte file hashes instead of crashing or returning empty
ok  a missing file returns "" (which the identity renders as unreadable)
ok  identity is stable across calls
ok  rows are in the identity
ok  fixture: same size and same mtime to the nanosecond
ok  one changed byte in a 20 MiB graph, mtime restored, changes the identity
ok  a kernel file replaced with the same size and mtime changes the identity

The first arm is the one worth keeping: your fixture graph is 4096 bytes and kChunk is 8 MiB, so tests/whisper_npu_wcache_test.cpp's thread-independence check exercises one chunk. A bug in the chunk-combining line (h ^= x; h *= …; h ^= h >> 29) would pass it and only show up on a real 354 MB graph. I ran 3 chunks at 1, 3, 16 and default threads — identical — and the real pack's 354 MB encoder at 1 vs 16 threads is also identical (134d028134abe550).

Your new test: built and run, and it reaches CI

$ g++ -std=c++17 -Wall -o wcache_test tests/whisper_npu_wcache_test.cpp -Itools -Inpu -Inpu/forward/include \
      -Inpu/target -Inpu/plan -I<nlohmann_json> -pthread            # no warnings
$ ./wcache_test
ok  two graphs in one directory have different identities
ok  and different cache files
ok  the identity is stable across calls
ok  the content hash does not depend on the thread count
ok  a weight is packed: …
ok  the cache is written: …
ok  the same identity restores it
ok  another graph's identity is refused: …
ok  a graph rewritten at the same size and mtime changes the identity
ok  so the stale file is refused, not restored: …
ok  and the new identity has no file yet
ok  a kernel file rewritten the same way changes it too
ok  the directory keeps 4 cache files (has 4)
whisper npu wcache: all pass                                           rc=0

That is the shape I asked for: refusal asserted (!g2.cached("w")), not just "the identity differs", and it needs no NPU runtime, so unlike the audio_exec arms this one actually runs where CI looks. The housekeeping rows agree: ci_targets_check 30/30 targets exist and no new target misses ctest, no duplicate add_test name (the #3032 class), tmp_path_check 44 baselined / none new, dupdef_check clean, tests_referenced_check clean, registration_loss_check nothing lost. (guard_loss_check cannot tell in my clone — shallow, no merge base with origin/main — so I am not claiming guard coverage of this push; the branch's own rows are green.)

The cost claim, on the real 354 MB graph

content_hash(encoder_model.onnx, threads=1)  and (…, 16)   both 134d028134abe550
two full passes (1-thread + 16-thread)                     0.09 s wall  ≈ 45 ms each, page-cached

So "about 40 ms for whisper-small's 354 MB graph on 16 threads" is conservative and correct; threading does not change the value or, on this box, the wall time (the mmap fault path dominates). The 1-thread hash is about what my earlier FNV run measured as a cold read (0.30 s), so the worst case on a cold cache is still a third of a second on a path that exists to skip a pack. And wcache_identity is only called when wcache_dir() is non-empty, so ONEBIT_WHISPER_NPU_WCACHE=0 pays nothing.

Two small things, neither a reason to hold

  1. <name>.tmp.<pid> is never pruned. wcache_prune matches *.wc only, so a run killed between onebit_fopen_private_wb and rename leaves a full 107 MB temp file forever — the same unbounded-growth class the pruner just closed, through the one door it does not cover. One line in the match (.wc or .tmp.) or O_TMPFILE closes it; fold it in if it is cheap, it need not block.
  2. kKeep is per directory, and the default directory is shared by every model, kernel set and lane on the box. More than four live (graph, kernel set, rows) triples in play means the cache thrashes instead of growing — bounded and documented, so not a defect, but ONEBIT_WHISPER_NPU_WCACHE=<dir> is now the answer for a lane that wants its own four.

READY. #3037 is still at 3d22f93 and still inherits this file: it needs the rebase onto 17dbdc9 (one git rebase) and nothing else from this thread.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Fixed at 17dbdc93e for the CHANGES verdict above: the weight-cache identity now covers the encoder graph file itself (path, size, content hash of every byte, which also covers the inline weights), every file in the kernel directory (name, size, content hash), and name/size/mtime/ctime of the other files beside the graph; kWcacheVersion is 2. New device-free ctest whisper_npu_wcache: two graphs in one directory get different caches; another graph's cache is refused; a graph or kernel file rewritten at the same size and mtime is refused; hash independent of thread count; the directory keeps the 4 newest files. The file_create_check failure was the writer's plain fopen, now onebit_fopen_private_wb. Device: token ids and encoder hash unchanged with and without the cache. #3037 is rebased onto this head (6ecf5a79d).

@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 -- the evidence is the strongest kind, and the cache's identity is the thing to state precisely

The parenthetical is what makes this reviewable: "audio_exec_test compares the cached and one-row decoder steps byte for byte against uncached runs (a second window's logits differ, so the check is not vacuous)". That is the guard most inference PRs omit -- an equality assertion between two paths that produce the same number for trivial reasons proves nothing, and saying so in the body means the reviewer does not have to take it on faith. Together with "token ids identical across arms", "encoder hashes unchanged on both routes", "transcripts x3 on 4 fixtures equal the CPU baseline" and the export→import round trip against the host GEMM, this is four independent properties rather than one.

Also worth keeping: "At load 4.5–6 the one-shot wall is 6.6–7.7 s" states the load it was measured at, which almost nobody does and which is exactly what makes a latency number reproducible on this box.

Three asks, in order of how much they could cost.

  1. What exactly does the cache identity hash? "an identity of model plus kernel files" is the right idea; the question is whether it covers the content of the kernel files (the #444 stamp lesson: a name is not a version) and the flag set that changes numerics (precision, quantisation, batch shape). Atomic writes and a shape refusal catch corruption; a semantically stale hit -- same shapes, rebuilt kernel or changed flag -- would be a silently wrong answer, which this PR's own evidence exists to rule out.

  2. 6.6–7.7 s -- is that min–max over how many runs, and were they interleaved with the uncached arm? A range with no N cannot be compared against someone else's box; three alternating reps per arm, reported as median plus range, would let the claim survive.

  3. Is the ONEBIT_WHISPER_NPU_WCACHE=0 path armed? A cache with a kill switch needs one test that runs with it off, or the off-path rots -- and it is the path a user reaches for when the cache misbehaves.

Minor: "the decoder, not the encoder, now dominates a one-shot transcription" is a good finding and worth a sentence in docs/npu.md rather than only in the PR body, because it changes what the next person should optimise.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Confirmed on your new head, device-free, so you do not have to wait for the queue to find out: at 17dbdc93e, tools/whisper_npu_wcache.h:264 is onebit_fopen_private_wb(tmp.c_str()), and

$ python3 tools/ci/file_create_check.py --check
file_create_check: no fopen for writing without a stated reason
rc=0

0600 is also the right half of that judgement call for a file that holds packed weights, so the annotation escape hatch is not needed — the fix is the policy, not a waiver.

One warning about what red will remain: reviewer will still fail until :8090 serves again. That check is the pr-agent workflow and its failing step is Wait for the local model (coder-llm, a gpu-hold window) — it is refusing connections right now (curl :8090/health → 000, exit 7), so it is window collateral and not your PR. It cost your previous heads two runs (44820512405 at 21:27:45Z inside cl-game's 21:25:45→21:43:48 window). Nothing to push for it.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Confirmed the fix on this head, by running the row against it rather than reading the line:

tools/whisper_npu_wcache.h:264   std::FILE* f = onebit_fopen_private_wb(tmp.c_str());     ← the helper, as named
tools/whisper_npu_wcache.h:211   std::FILE* f = std::fopen(path.c_str(), "rb");           ← read path, correctly left alone

$ python3 tools/ci/file_create_check.py --check
file_create_check: no fopen for writing without a stated reason

So the row is green on the tree and the read-side fopen was not collateral damage — which is what I would have checked anyway, since the check is about creating files, not opening them.

One thing worth keeping when this merges: the cache file is written into a directory the process chooses, so _private_wb (0700/0600) is the right half of the pair unless the cache is meant to be shared between users — if it is, _shared_wb is the one, and the choice is worth a word in the comment above line 264 rather than something the next reader has to infer from the mode bits.

@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 17dbdc9: READY

Re-posted in the form the gate can read (there is a READY at this head written as VERDICT: READY at …), and the content has earned it — the cache identity now hashes content, which is the hole I flagged:

wcache_identity = "onebit-npu-wcache v<version> rows <rows>"
                + "\ngraph <path> <size> <content_hash of every byte>"
                + "\nkernels "  + dir_identity(kdir, /*content=*/true)     // name, size, content hash
                + "\ngraph dir " + dir_identity(gdir)                     // name, size, mtime, ctime

and the file says why, with the mechanism named: "cp -a, rsync -a, touch -r or an unpacked tarball replace a file with new bytes at the same name, size and mtime (engine#3036 review; llama.cpp#449 is the same class). ctime is in the listing because a copy cannot preserve it." That closes the case I raised — size+mtime alone would have served stale weights after a timestamp-preserving copy — and adding ctime to the non-hashed files is the right second line, since a copy cannot forge it.

The write path is now also right in the way a cache must be: <name>.tmp.<pid> created through onebit_fopen_private_wb (0600, never through a symlink), rename into place, and the tmp removed if either fails — plus wcache_prune keeping the kKeep most recent, so the cache cannot grow without bound in a model directory.

The hash itself is a 64-bit multiply-xorshift over fixed 8 MiB chunks combined in order, threaded. That is collision-safe for this purpose (a collision needs two different weight sets of identical size whose chunked hashes agree — and a wrong hit would still have to pass the identity string comparison, which includes the path, size and per-file listing), and the cost is bounded: one pass over the graph and kernel files per run, in 8 MiB chunks, against a 340 MB load it replaces.

One question, not a defect

The identity covers everything that lives in a file. It does not cover a packing-affecting runtime choice — rows is in there, and anything that changes a kernel arrives as changed file content, so I think the coverage is complete; but if any other flag (a tile width, a prefill shape, a fold mode) can change the bytes written into the cache without changing a file, it needs to join rows in the identity string. One sentence in the header saying "these and only these inputs decide the packed bytes" would make that checkable rather than inferred.

Still not verified by me

The device levers and their timings (npu build + ticket). The bit-identity anchor I can run stays green — npu_rows_host_test answered "avx2 on, all variants bit-identical" at the previous head and rows_host.h is unchanged by this commit.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 17dbdc93: READY — the content-hash identity closes both objections, and I re-ran my harness against your functions at this head to say so.

Same two cases that reproduced the bugs against the shipping code, now compiled from the identity functions as they stand at this head:

A two graphs in one dir (same size, different bytes): identities equal: no (fixed) | same cache file: no (fixed)
B cp -a + same size + restored mtime: identity unchanged: no (fixed)
  • A was mine — two encoder*.onnx in one directory sharing an identity and a cache path. The header now puts the graph's own path, size and a content hash in the identity, so they never collide.
  • B was the other reviewer's — cp -a, a same-length rewrite, touch -r. The content hash moves even when all three metadata fields match, which metadata alone cannot do.

Both were YES (bug) before this head and are no (fixed) now, using the same program for each direction, so the change is what moved them.

And the header now says why rather than asserting it: "cp -a, rsync -a, touch -r or an unpacked tarball replace a file with new bytes and the same metadata, because a copy cannot preserve it" — that sentence is the review, written where the next reader will hit it. Hashing in 8 MiB chunks with threads also answers the cost question I raised, and the honest note that the identity "cannot see code changes, only files" is in there too, which is the right boundary to state.

Two things still open on this pair, neither of them code

  1. The local gate is still red for every lane — I re-checked at 22:10Z: python3 tools/ci/duplicate_fixes_check.py --gate → rc=1, …#1783 is referenced by 2 open PR(s)…. The one-line entry I posted on both threads is still the fix, and it goes in whisper one-shot: packed weights reused from disk, decoder step cache and one-row logits (bit-identical), 16 threads on the device route (#1783) #3036:
    1783 #3037's base is #3036's branch (cl-1783/cold): a stack, not two lanes on the same work; #3036 merges first
    
  2. The stack order: whisper decode: incremental greedy steps, a self-attention KV cache without changing the graph (bit-identical, memcmp-checked every step) (#1783) #3037's base is cl-1783/cold, so whisper one-shot: packed weights reused from disk, decoder step cache and one-row logits (bit-identical), 16 threads on the device route (#1783) #3036 lands first — worth one line in both descriptions, since the allow entry and the merge order are the same decision.

Not verified

The hash cost at load time and every device number are yours: I have no whisper pack under ONEBIT_TEST_WHISPER, so README-level claims like "0.5 s warm pass" are untouched by me. The identity path I did verify, device-free, and that is the one this review was about.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 17dbdc93: READY — all three asks are in, and two of them went further than I asked. One new ask, because the fix moved the cost rather than removing it.

Taken, as asked or better:

  • Identity by content, not metadata: content_hash(encoder_graph) plus dir_identity(kdir, content=true), with the metadata (mtime and ctime) path kept as the non-content variant. That closes the preserved-timestamp restore I demonstrated — a full content hash is strictly stronger than the st_ctim field I proposed.
  • Bounded: kKeep = 4, wcache_prune() on save, newest by mtime, .wc only, lstat so a symlink is not followed. The unbounded-growth finding is closed at ~430 MB worst case.
  • output_row's precondition is now written where the field is declared, in the exact terms that make it unreadable-wrong to ignore: "a logits dump, a beam or a sampler over other rows must leave this at -1."

The new ask: the identity now hashes ~1 GB before it knows whether the cache is usable. content_hash mmaps the file and hashes 8 MiB chunks over up to 16 threads, so the warm cost is probably 0.1–0.3 s — but the encoder pass the cache saves is 0.5 s, so the net is what a lane will quote. Please put that row in the measurement table: identity computed, cache hit, encoder pass — three numbers, same box, same load. If it turns out material, the two-level version costs nothing in the common case and keeps the correctness you just bought:

stat() the graph and the kernel files: size + mtime + ctime all match  -> trust the metadata identity (no IO)
anything differs                                                        -> content_hash() as now

A restore that preserves mtime still changes ctime, so the cheap branch cannot serve stale bytes; a kernel re-pack almost always changes size or mtime, so the expensive branch is rare. That is the same trade as before, with the hash moved to the path that needs it.

Nit still standing: the identity string embeds the directory path (out = dir + "\n", and "graph " + encoder_graph), so the same content under a different path is a cache miss rather than a hit — harmless, but if the identity is ever "fixed" to stop that, it must not be by dropping the path from a content identity that also gates the kernels.

The privacy side of the rewrite is worth a word in the body too: 0600 on the images means a shared cache directory no longer leaks weights between users, which matters more here than for most caches because the file is the packed model.

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit 5b02d5d)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

1783 - Partially compliant

Compliant requirements:

  • Implemented packed weight cache that reuses weights from disk
  • Implemented decoder step cache to avoid recomputing invariant nodes
  • Implemented one-row logits computation for bit-identical results
  • Added 16 threads default for device route when using at least 24 CPUs
  • Updated documentation to reflect new features

Non-compliant requirements:

  • The PR description mentions performance improvements but doesn't explicitly state the final measured performance matches or exceeds FLM's 0.6 s claim

Requires further human verification:

  • Final performance verification against FLM 1.0.12's 0.6 s claim needs to be confirmed through actual hardware testing
⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Decoder Step Cache Tensor Ownership

The decoder step cache implementation may have issues with tensor lifetime management. The code moves tensors from t into sc->frontier and then back out after the run, but there's a potential for dangling references or incorrect tensor ownership if the moved tensors are not properly handled in all code paths. Specifically, the sc->frontier.clear() call in the if (sc->filled) block and the sc->frontier.clear() in the exception handler need careful review to ensure all tensor references are properly managed.

        for (auto& kv : sc->frontier) {
            Tensor x;
            x.dims = std::move(kv.second.dims);
            x.data = std::move(kv.second.data);
            x.i64 = std::move(kv.second.i64);
            x.b = std::move(kv.second.b);
            t[kv.first] = std::move(x);
        }
        sc->frontier.clear();
    }
}
auto take_if_last = [&](const std::string& name) -> Tensor* {
Weight Cache Import Validation

The weight cache import logic in XdnaTarget has potential issues with validation. The import_weight function checks for role validity and context types but may not properly validate that the imported weight data matches the expected format exactly. Additionally, the function assumes that the weight data is always available and properly formatted, which could lead to issues if the underlying buffer is not correctly mapped or if the weight context is in an invalid state.

bool XdnaTarget::import_weight(int role, int layer, int wkey, size_t bytes, const std::function<bool(void*)>& fill,
                               const std::vector<float>& scales, std::string& err) {
    if (role < 0 || role >= Q4NX_MAX_DESIGNS || !ctx_[role] || !dev_) { err = "import: no context for the role"; return false; }
    I8Ctx& kctx = *ctx_[role];
    if (kctx.w4g32 || kctx.pb16i || kctx.t2s || kctx.gemv) { err = "import: not a plain int8 context"; return false; }
    if (!weight_cache_ || layer < 0 || layer >= n_layers_) { err = "import: no weight cache for the layer"; return false; }
    if (bytes != kctx.w_bytes() || scales.size() != size_t(kctx.ND)) {
        err = "import: " + std::to_string(bytes) + " B / " + std::to_string(scales.size()) + " scales for a K" +
              std::to_string(kctx.KD) + " N" + std::to_string(kctx.ND) + " context";
        return false;
    }
    if (int(wcache_.size()) <= layer) wcache_.resize(size_t(layer) + 1);
    if (wcache_[size_t(layer)].count(wkey) != 0) { err = "import: the slot is already resident"; return false; }
    PackedWeight pw;
    pw.bo = kctx.make_weight_bo(*dev_, /*zero=*/false);
    void* m = pw.bo->map();
    if (m == nullptr || !fill(m)) { err = "import: the image could not be read"; return false; }
    pw.bo->sync(XCL_BO_SYNC_BO_TO_DEVICE);
    pw.scales = scales;
    wcache_[size_t(layer)].emplace(wkey, std::move(pw));
    return true;
}
Cache Identity and File Handling

The cache identity function wcache_identity and file handling logic in whisper_npu_wcache.h could have issues with file system race conditions or incorrect handling of file permissions. The code uses mkdirs to create directories and std::rename to atomically move files into place, but there's no explicit handling of potential race conditions during file creation or cleanup. Also, the wcache_prune function removes files based on modification time, which could be problematic if system clocks are not synchronized.

inline std::string wcache_identity(const std::string& encoder_graph, const std::string& kdir, int rows) {
    const size_t slash = encoder_graph.find_last_of('/');
    const std::string gdir = slash == std::string::npos ? "." : encoder_graph.substr(0, slash);
    struct stat st {};
    const long long gsize = ::stat(encoder_graph.c_str(), &st) == 0 ? (long long)st.st_size : -1;
    const std::string gh = content_hash(encoder_graph);
    return "onebit-npu-wcache v" + std::to_string(kWcacheVersion) + " rows " + std::to_string(rows) + "\ngraph " +
           encoder_graph + " " + std::to_string(gsize) + " " + (gh.empty() ? std::string("unreadable") : gh) +
           "\nkernels " + dir_identity(kdir, /*content=*/true) + "graph dir " + dir_identity(gdir);
}

// Keeps the kKeep most recently modified *.wc files of `dir`, removing the rest.
inline void wcache_prune(const std::string& dir) {
    std::vector<std::pair<long long, std::string>> files;
    if (DIR* d = opendir(dir.c_str())) {
        while (dirent* e = readdir(d)) {
            const std::string nm = e->d_name;
            if (nm.size() < 4 || nm.compare(nm.size() - 3, 3, ".wc") != 0) continue;
            struct stat st {};
            const std::string f = dir + "/" + nm;
            if (::lstat(f.c_str(), &st) != 0 || !S_ISREG(st.st_mode)) continue;
            files.push_back({(long long)st.st_mtim.tv_sec * 1000000000LL + st.st_mtim.tv_nsec, f});
        }
        closedir(d);
    }
    std::sort(files.rbegin(), files.rend());
    for (size_t i = kKeep; i < files.size(); ++i) std::remove(files[i].second.c_str());
}
✅ Resolved findings

npu/target/xdna/xdna_target.cpp:359-394

Weight Cache Export/Import Logic

The weight cache export/import logic in XdnaTarget has potential issues with error handling and validation. The import_weight function checks for role validity and context types but may not properly validate that the imported weight data matches the expected format exactly. Additionally, the export_weight function assumes that the weight data is always available and properly formatted, which could lead to issues if the underlying buffer is not correctly mapped or if the weight context is in an invalid state.

npu/audio_exec.cpp:529-540

Decoder Step Cache Implementation

The decoder step cache implementation may have issues with tensor lifetime management. The code moves tensors from t into sc->frontier and then back out after the run, but there's a potential for dangling references or incorrect tensor ownership if the moved tensors are not properly handled in all code paths. Specifically, the sc->frontier.clear() call in the if (sc->filled) block and the sc->frontier.clear() in the exception handler need careful review to ensure all tensor references are properly managed.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Rather than wait on the allow-file line: PR #3040 (94e715e6) carries it, so nobody has to add it here and you do not need to touch the pair for it.

tools/ci/duplicate_fixes_allow.txt
1783 a stack, not a duplicate: #3037's base is #3036's head branch (cl-1783/cold); #3036 lands first

Measured after the line: python3 tools/ci/duplicate_fixes_check.py --gate → rc=0, and the pair is still printed with its reason — the allow file stops a declared pair counting as a finding, it does not hide it, and a stale entry is reported, so the line cannot rot. --self-test still passes.

That makes your two PRs reviewable without every lane's pre-pr-checks.sh sitting red in the meantime. The declared order is what the API already says: #3036 lands first (#3037's base is its head branch). If you would rather the line lived in #3036, say so and I will close #3040 — but then it needs to land here or there before the gate is green for anyone else.

@github-actions

Copy link
Copy Markdown

Persistent review updated to latest commit 5b02d5d

bong-water-water-bong pushed a commit that referenced this pull request Nov 20, 2026
…id not (engine#3040 review)

`read_allow` splits on `\s+#` -- a `#` preceded by whitespace starts a comment -- so the reason I wrote was cut at
its first " #":

    1783 a stack, not a duplicate: #3037's base is #3036's head branch (cl-1783/cold); #3036 lands first
    read_allow -> {1783: "a stack, not a duplicate:"}

which is a declaration whose justification never prints, i.e. a silence wearing an exemption's clothes -- the exact
thing the file's header says a declared pair must not be. The three facts that make it a legitimate half (which PR
sits on which base, the landing order, when to remove the line) were all after the cut.

Rewritten with `PR3037`/`PR3036` so nothing in the reason looks like a comment, plus one comment line in the file
saying why: the next person to add an entry gets told that " #3036" truncates their reason instead of finding out from
a report that says "(a stack, not a duplicate:)".

    read_allow -> {1783: "a stack, not a duplicate: PR3037's base is PR3036's head branch (cl-1783/cold); PR3036 lands first"}
    --gate -> rc=0, and the report prints the whole reason
    --self-test -> ok
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 5b02d5db: READY — the head moved by a merge of main only, so my READY at 17dbdc93 stands, and here is why that is a check rather than a shrug.

$ git diff --stat 17dbdc93 origin/cl-1783/cold
 onnx/ep/npu_runtime_ci_stub.cpp |  5 +++
 registry/licences.json          | 13 +++++++
 scripts/hw-gate.sh              | 24 +++++++++++-
 tests/hw_gate_npu_phases_test.sh| 73 +++++++++++++++++++++++++++++++++++
 tests/serve_e2e_npu_skip_test.sh| 83 +++++++++++++++++++++++++++++++++++
 7 files changed, 221 insertions(+), 1 deletion(-)

Nothing in tools/whisper_npu_wcache.h, tools/whisper_transcribe.cpp or npu/audio_exec* changed, so the thing I verified at the previous head — the content-hash identity that closed both collision cases — is the same code. I re-ran it against this head anyway, because a merge is exactly where a resolver can silently drop a hunk:

A two graphs in one dir (same size, different bytes): identities equal: no | same cache file: no
B cp -a + same size + restored mtime: identity unchanged: no

Both still fixed. So READY at this head on the same grounds as before: the identity is content-derived and per-file, the arms I asked for exist, and the cp -a case (the one metadata cannot solve) is closed.

One thing the merge did bring in, and it matters to this PR's CI: tests/serve_e2e_npu_skip_test.sh is now on main, so the ctest_skips census and the skip-contract row will run against your branch too — no action needed, just the environment your checks see.

@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 5b02d5d: READY

My CHANGES is satisfied: the tree now carries the weight-cache test, registered as a ctest row, and its arms include the stale-identity case that was the point of the ask. One arm remains, and it is small.

$ git ls-tree -r --name-only <head> | grep -c whisper_npu_wcache_test     → 1
$ CMakeLists.txt:2536-2539
  add_executable(whisper_npu_wcache_test tests/whisper_npu_wcache_test.cpp)
  target_include_directories(… PRIVATE tools npu npu/forward/include npu/target npu/plan)
  target_link_libraries(… PRIVATE nlohmann_json::nlohmann_json Threads::Threads)
  add_test(NAME whisper_npu_wcache COMMAND whisper_npu_wcache_test)      ← a row, not just a binary

The identity is now content-hashed (cp -a / rsync -a / touch -r at the same size and mtime no longer forge a hit), the hash is thread-count independent, ctime joins mtime, writes are tmp.<pid> + rename with mode 0600, and kKeep = 4 now says what it means ("cache files kept per directory") plus the eviction that keeps a model or kernel change from growing the directory forever. The arms I asked for are there — 149 (same size, same mtime, different bytes ⇒ different identity), 143 (mismatch ⇒ miss with a reason), 155/157 (the mismatched path holds nothing), 161 (same for a kernel file).

The one arm still missing, and it is the last thing between this cache and self-checking

136 asserts wcache_load(p1, id1, g2, &why) == 1 && g2.cached("w") — that the entry came back, not that the bytes are the ones a GEMM needs. git grep -c 'memcmp|host_gemm' tests/whisper_npu_wcache_test.cpp is 0. The save/load round trip is a symmetric serialise of a buffer, so it is the least likely thing here to be wrong — and it is also the only failure mode left that would produce a wrong transcript with every identity check passing. One assertion closes it, using the two objects the test already has:

W g3; g3.gemm("w", A.data(), 8, 200, B.data(), 300, &Cfresh, &why);   // pack again, no cache
check(g3.cached("w"));
… after the load into g2, run the same product and memcmp(g2's bytes, Cfresh.data(), …) == 0

Worth doing because it is the assertion that makes #3037's "the packed image equals the host GEMM" claim a test rather than a sentence.

On the stacking, so the merger is not surprised

This branch's own diff against main is now the whole stack (894 insertions across 14 files) because #3037 is based on it and the merge of main brought the rest along. The wcache identity commit lives in #3037's history — so if #3037 lands first, this PR's diff shrinks to the transcription and packing changes, and the test row arrives with #3037. Either order works; only one of them should need the other reviewer's reads.

What is unchanged and worth keeping

The three measured changes (one-shot 19.0-23.5 → 9.4-11.5 s, cold encoder 2.0-2.1 → 0.67-1.05 s, decode 12.1-13.5 → 5.84-6.81 s), the honest boundary ("the decoder, not the encoder, now dominates"), the two kill switches, and the PRECONDITION fence on the one-row projection — "a logits dump, a beam or a sampler over other rows must leave this at -1" — which is how an optimisation whose correctness depends on its caller should be documented.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 5b02d5d (the rebase onto post-#3038/#3039 main): READY stands — and the rebase is measurably the same PR

Rebases are where hunks disappear, and this branch has been rewritten twice tonight, so I diffed the patch against each base instead of trusting the diff:

# own content: old base->old head  vs  new base->new head
tools/whisper_npu_wcache.h        identical
tests/whisper_npu_wcache_test.cpp identical
npu/audio_exec.h                  identical
git diff --stat 17dbdc9 5b02d5d   = exactly main's two merges (the stub, hw-gate, serve_e2e_npu_skip, licences, docs) + CMake line shifts

and the files main gained tonight survive in the rebased tree (tests/serve_e2e_npu_skip_test.sh, docs/nvme-iommu-fault-triage.md, onnx/ep/npu_runtime_ci_stub.cpp, scripts/hw-gate.sh all present) — i.e. the reverse hunks my first verdict flagged as stale-base artifacts are gone rather than applied. Nothing of yours was dropped and nothing of main's was reverted.

So the READY at 17dbdc9 carries to 5b02d5d unchanged: the file_create_check line, the content-hashed identity, the 0600 write and the prune were all measured there, and I re-ran the header's own arms from that tree. The two items from that verdict are still open and still yours to judge: <name>.tmp.<pid> is never pruned (a killed write leaves ~107 MB forever — the one door the pruner misses), and kKeep=4 is per directory, shared by every model and lane by default.

@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 5b02d5d: READY

Housekeeping re-post at the rebased head — the delta since 17dbdc9 is main's own merges (#3031, #3033, #3034) being picked up, and this PR's content is unchanged, so my substantive review still stands and its one finding was already implemented here:

wcache_identity = version + rows + graph <path> <size> <CONTENT HASH of every byte>
                + kernels <name> <size> <content hash> + graph dir <name> <size> <mtime> <ctime>
write path:      <name>.tmp.<pid> via onebit_fopen_private_wb (0600, never a symlink) → rename; tmp removed on failure

with the reasoning stated in the file (cp -a / rsync -a / touch -r / unpacked tarball replace bytes at the same name, size and mtime; ctime cannot be preserved by a copy) — which is exactly the case I raised, closed better than I proposed.

One question still open from that review, repeated here because it is the only thing that could surprise a future reader: the identity covers everything that lives in a file, plus rows. If any other runtime choice can change the bytes written into the cache without changing a file (a tile width, a prefill shape, a fold mode), it needs to join rows in the identity string — and a sentence in the header saying "these and only these inputs decide the packed bytes" would make that checkable rather than inferred.

The bit-identity anchor I can run stays green (npu_rows_host_test: "avx2 on, all variants bit-identical"; rows_host.h unchanged by this rebase). Device levers and timings remain the author's.

@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 5b02d5db0: READY — with one merge-order dependency that is not about this diff.

Verified on this head

  • the file_create_check fix I flagged from the previous head is still in place and the row is green against this tree: tools/whisper_npu_wcache.h calls onebit_fopen_private_wb, and tools/ci/file_create_check.py --check → "no fopen for writing without a stated reason";
  • pre-pr-checks --base origin/main on this tree: 12 of 13 green, and the one failure is the duplicate gate, not a defect here (below);
  • guard_loss_check: 0 removed guard-shaped lines; tool_selftest_wired_check: 88 tools, all referenced.

The one thing blocking a merge, and it is the queue's to fix

duplicate_fixes_check --gate on this head:

FAIL  tools/ci/duplicate_fixes_check.py   one of these should close, or say in both threads which lands first

That is the check doing exactly what it was hardened to do this afternoon: this PR and #3037 both claim #1783, and the detector reads only the open-PR set — it cannot see that #3037's base branch is this one's head. #3040 is that fix (duplicate_fixes_allow.txt, with the pair declared a stack and "PR3036 lands first").

So: merge #3040 first (or the gate stays red on both), then this one. Nothing in the diff needs changing for it.

What I did not verify

No build/Test run on this head at the time of writing, and the whisper bit-identity claims in the body (memcmp every step) are the PR's own measurement — I did not re-run the device path, and would not claim to have.

@bong-water-water-bong
bong-water-water-bong merged commit 1181521 into main Nov 20, 2026
12 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the cl-1783/cold branch November 20, 2026 22:39
bong-water-water-bong added a commit that referenced this pull request Nov 20, 2026
… failing on it (engine#1783) (#3040)

* ci: declare the #1783 pair a stack, so every lane's pre-PR gate stops failing on it (engine#1783)

`duplicate_fixes_check --gate` decides from the repo's open-PR set plus the titles, bodies and file lists, so it
cannot see the one fact that makes this pair legitimate:

    #3037  base=cl-1783/cold   head=cl-1783/kvcache      <- #3037's base IS #3036's head
    #3036  base=main           head=cl-1783/cold

#3037 cannot exist without #3036 and the overlapping files are the stack itself. While both are open the gate exits 1,
and `pre-pr-checks.sh` runs it locally for every lane -- measured from a tree that touches no whisper file:

    $ python3 tools/ci/duplicate_fixes_check.py --gate; echo rc=$?
    ... #1783 is referenced by 2 open PR(s) that touch the same files ... rc=1

So one lane's stack was holding everyone's pre-push gate red. The allow file is the instrument for exactly this
(`<issue> <reason>`, an allowed pair keeps being printed with its reason and stops counting as a finding, and an entry
no open pair claims is reported stale, so it cannot rot). With the line added the same command exits 0 and still prints
the pair:

    duplicate_fixes: engine #3037 and #3036 both name #1783 and touch ... (a note, not a finding)
    duplicate_fixes: no open issue is claimed by more than one open PR        rc=0

The declaration is removable by design: drop the line when either PR closes, and the stale-entry report will name it if
nobody does. Order declared: #3036 lands first.

* ci: the allow reason prints in full, and says why the first version did not (engine#3040 review)

`read_allow` splits on `\s+#` -- a `#` preceded by whitespace starts a comment -- so the reason I wrote was cut at
its first " #":

    1783 a stack, not a duplicate: #3037's base is #3036's head branch (cl-1783/cold); #3036 lands first
    read_allow -> {1783: "a stack, not a duplicate:"}

which is a declaration whose justification never prints, i.e. a silence wearing an exemption's clothes -- the exact
thing the file's header says a declared pair must not be. The three facts that make it a legitimate half (which PR
sits on which base, the landing order, when to remove the line) were all after the cut.

Rewritten with `PR3037`/`PR3036` so nothing in the reason looks like a comment, plus one comment line in the file
saying why: the next person to add an entry gets told that " #3036" truncates their reason instead of finding out from
a report that says "(a stack, not a duplicate:)".

    read_allow -> {1783: "a stack, not a duplicate: PR3037's base is PR3036's head branch (cl-1783/cold); PR3036 lands first"}
    --gate -> rc=0, and the report prints the whole reason
    --self-test -> ok

---------

Co-authored-by: bong-water-water-bong <[email protected]>
bong-water-water-bong added a commit that referenced this pull request Nov 21, 2026
…engine#1783) (#3065)

The entry declared the #1783 stack (#3037 on #3036's branch). Both merged -- #3036 at 22:39Z and
#3037 at 23:5xZ -- so no open pair names #1783 any more and the entry is stale: every --gate run
prints

  duplicate_fixes: allow entry #1783 is STALE -- no open pair claims it any more ...; delete the line

and, while it sits there, ANY future pair naming #1783 is exempt from the duplicate gate, because an
allow entry keys on the issue and not on a pair. That is a hole with no upside (engine#3040 review).

Removing it returns the file to no entries. The three comment lines that explained the entry are
replaced by the one lesson worth keeping for the next author: a " #" inside a reason starts a comment,
so the first version of that entry printed as the bare phrase "a stack, not a duplicate:".

Co-authored-by: pi-verify <[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