Skip to content

npu: compare the two arms' residuals, so a bitx verdict can name the body or the head (engine#3196) - #3199

Merged
bong-water-water-bong merged 5 commits into
mainfrom
cl-review-3196-residuals
Nov 21, 2026
Merged

bong-water-water-bong merged 5 commits into
mainfrom
cl-review-3196-residuals

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Advances engine#3196 — fix 2 of the three the issue lists, and the one that needs no device.

The issue's defect: on a container whose lm_head the device does not claim, the device falls through to an f32 host matvec while the integer arm takes its int8 head ladder, so scripts/npu-kernel-bitx.sh compares two heads and its verdict says nothing about the kernel family. Its own measurements: device vs f32 max|d| 6.58 with the same argmax, device vs i8 max|d| 16.35 with the argmax flipped, and the i8 logit vector ~0.3× the others.

The residual stream the forward can already dump (NPU_INFER_DUMP_DIR, one layer_<ll>.f32 per layer, documented in docs/npu.md) is taken before the head, so comparing it answers the body question on its own.

What this adds

  • tools/ci/npu_residual_diff.py — two dump directories in, per-layer relative L2 out: a band summary (default layers 4..43, the band the issue measured over), the worst layer named, and a verdict line written for the renderer (the last non-empty line is the only one a runner keeps). Exit 0 within threshold, 1 over it with the layers named, 2 cannot tell — no common layer, an empty dump, or a file whose length is not a whole number of floats, because a partial write says nothing either way.
  • scripts/npu-kernel-bitx.sh — both arms now run with NPU_INFER_DUMP_DIR set and the tool is called on the runs the gate already makes. It is advisory on purpose: the threshold at which two bodies count as agreeing is a decision npu: the NPU_INFER_HOST_GEMM=i8 arm's head (and quantisation) make it un-bit-exact against a device whose head runs on the host, so npu-kernel-bitx.sh's verdict is about the heads #3196 has not made yet, and a second gate criterion here would red the arm for a difference the issue is still measuring.
  • CMakeLists.txt — the tool's --self-test as a ctest row, device-free.
  • docs/npu.md — what the gate does with the dumps, and why the comparison is advisory.

Reproduced from the issue's own dumps, so the tool's numbers are the issue's numbers

The issue-keeper left the dumps on this box (~/.cache/scratch-pi-issues/bitx-115, 48 layers per arm, 5120 f32 each), so the acceptance criterion is measurable today without an npu-hold ticket:

$ tools/ci/npu_residual_diff.py …/dumps/dev …/dumps-f32/f32
residuals: 48 layer(s) in common; band 4..43: mean rel 5.15e-02, worst layer 04 at 5.72e-02
residuals: FAIL 40 layer(s) over 2e-02 …                                   ← issue reported 5.5e-2

$ tools/ci/npu_residual_diff.py …/dumps/dev …/dumps/host
residuals: 48 layer(s) in common; band 4..43: mean rel 1.06e-01, worst layer 04 at 1.22e-01
                                                                            ← issue reported 9.7e-2

$ tools/ci/npu_residual_diff.py …/dumps/host …/dumps-f32/f32
residuals: 48 layer(s) in common; band 4..43: mean rel 1.42e-01

So the device is closest to the f32 arm and furthest from the integer one before any head is applied — the ordering the issue reported, now reproducible by anyone with the dumps. The FAIL lines are the honest answer at the default 2e-2 threshold: no arm's body is bit-close to another's, which is the issue's point 2 (the pre-head gap is its own question) and the reason the comparison is advisory rather than a new gate criterion here.

The tool's own arms

--self-test covers identical dumps, a 10 % scale difference (over, and named), a layer outside the band not deciding the verdict, a missing directory, a partial f32 file, and two missing directories — 7 arms, 0 failed.

Gates

tools/copyright.py --check                                              rc 0
tools/ci/tool_selftest_wired_check.py                                   rc 0
scripts/pre-pr-checks.sh --base origin/main --tree-only                 rc 0  (14 green, 3 skipped, 0 cannot-tell)
bash -n scripts/npu-kernel-bitx.sh                                      clean

Not claimed

The device side of the wiring — that forward-serve writes both arms' layers/ directories during a real gate run — is exercised the next time someone runs the gate on the NPU; I could not run it here without an npu-hold ticket, and the tool's comparison is already proven against the issue's dumps. Fixes 1 (#3197, merged) and 3 (the Hadamard-fold quantisation) remain with the issue.

…body or the head (engine#3196)

engine#3196 measured the problem: on a container whose `lm_head` the device does not claim, the
device falls through to an f32 host matvec while the integer arm takes its int8 head ladder, so
`scripts/npu-kernel-bitx.sh` compared two HEADS and its verdict said nothing about the kernel
family. The issue's own numbers: device vs f32 max|d| 6.58 with the same argmax, device vs i8
max|d| 16.35 with the argmax flipped, the i8 logit vector ~0.3x the others.

Fix 2 of the three the issue lists, and the one that needs no device: the residual stream the
forward can already dump (`NPU_INFER_DUMP_DIR`, one `layer_<ll>.f32` per layer) is taken BEFORE the
head, so comparing it answers the body question on its own.

  tools/ci/npu_residual_diff.py   two dump directories -> per-layer relative L2, band summary,
                                  worst layer, and a verdict line; exit 0 within threshold,
                                  1 over it (named), 2 cannot tell (no common layer, an empty or
                                  partial dump) -- "could not look" is never a pass
  scripts/npu-kernel-bitx.sh      runs both arms with NPU_INFER_DUMP_DIR set and calls the tool on
                                  the runs it already makes. ADVISORY on purpose: the threshold at
                                  which two bodies count as agreeing is a decision #3196 has not
                                  made, and a second gate criterion here would red the arm for a
                                  difference the issue is still measuring
  CMakeLists.txt                  the tool's --self-test as a ctest row (device-free)
  docs/npu.md                     what the gate does with the dumps, and why the comparison is
                                  advisory

Reproduced the issue's measurement from the dumps the issue-keeper left on this box
(~/.cache/scratch-pi-issues/bitx-115, 48 layers each), so the tool's numbers are the issue's:

  dev vs f32 arm       mean rel 5.15e-02 in band 4..43, worst layer 04 at 5.72e-02   (issue: 5.5e-2)
  dev vs i8 host arm   mean rel 1.06e-01,                      worst layer 04 at 1.22e-01   (issue: 9.7e-2)
  i8 host vs f32 arm   mean rel 1.42e-01

i.e. the device is closest to the f32 arm and furthest from the integer one before any head is
applied, which is the ordering the issue reported. The tool's self-test (7 arms) covers the
identical / 10 %-scale / out-of-band / missing-directory / partial-file cases.

Gates: copyright rc 0, tool_selftest_wired rc 0, scripts/pre-pr-checks.sh --base origin/main
--tree-only rc 0 (14 green, 3 skipped, 0 cannot-tell).
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at e5fcfab: READY — self-test 7/7 and wired, the cannot-tell answer is real, and the one thing that could have made an "advisory" tool dangerous (its rc leaking into the gate's verdict) does not happen. I checked that last one specifically rather than taking "ADVISORY on purpose" on trust.

The tool

$ python3 tools/ci/npu_residual_diff.py --self-test
npu_residual_diff self-test: 7 ok, 0 failed                         rc 0
$ python3 tools/ci/npu_residual_diff.py <empty> <empty>
residuals: … has no layer_*.f32 — cannot tell what the bodies did, and that is not a pass    rc 2

Registered as npu_residual_diff_self (CMakeLists.txt:738), so the arms run in CI, and the empty-dump case answers 2 rather than reporting agreement — which matters here because "no residuals dumped" is the normal state of a run whose container does not write them.

The integration, and why "advisory" is true

if [ -f "$residual_tool" ] && command -v python3 >/dev/null 2>&1; then
    python3 "$residual_tool" "$out/dev/layers" "$out/host/layers" 2>&1 | sed 's/^/  /'
fi
if [ "$bad" = 0 ]; then echo "…bit-exact…"; exit 0; fi

scripts/npu-kernel-bitx.sh:38 is set -u only — no set -e, no pipefail — so the tool's rc 2 is displayed and then ignored, and the gate's verdict is still computed from bad/n, exactly as before. Had the script carried set -e or pipefail, this block would have turned every run without a residual dump into a silent rc-2 exit before the verdict line; the guard [ -f ] && command -v python3 covers the other way it could break a lane. That is the check I would want on any diagnostics tool wired into a gate.

One note, not an ask

NPU_INFER_DUMP_DIR="$dir/layers" is now set for both arms on every bitx run, and the script mkdir -ps the directories — so the gate pays whatever the dump costs on every future run, including the ones that never look at the layers. If that cost turns out to be noticeable on a 14B container, an opt-out (BITX_RESIDUALS=0) is one line; I would not add it speculatively, but it is the knob to reach for if the arm's wall time moves after this lands.

Everything else checks out: the residual stream is taken before the head, so the verdict it produces ("a logits difference with the residuals inside the band is a HEAD difference") is a claim the data can support, and leaving the threshold decision to #3196 rather than inventing one here is the right call.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at e5fcfab: READY. The tool is wired and self-testing, which is the pattern the last three tooling PRs needed a follow-up to reach:

+add_python_test(npu_residual_diff_self ${CMAKE_SOURCE_DIR}/tools/ci/npu_residual_diff.py --self-test)
...
+# say whether the BODY or the HEAD differs. Self-test only in CI: the live comparison needs two NPU runs that
$ python3 tools/ci/npu_residual_diff.py --self-test
npu_residual_diff self-test: 7 ok, 0 failed      rc 0

Two things I would keep exactly as they are:

  • "Self-test only in CI: the live comparison needs two NPU runs" — that is the honest version of a scope limit. It is not a row that cannot look pretending to be one that did; it says which half runs and why the other half cannot, in the same sentence a reader would ask the question in.
  • the change answers a comparison defect rather than a numeric one: on a container whose lm_head the device does not claim, the device falls through to an f32 host matvec while the integer arm uses its int8 head ladder, so the old script compared two heads and the verdict said nothing about the kernel family. Splitting the residual into body vs head is what makes a bitx verdict nameable, and it is the kind of fix that stops a whole class of "the suite is red and nobody knows which side" reports.

The one thing I did not check: the live mode's behaviour on real dumps (it needs two NPU runs and an npu-hold ticket, and / is at 168 G with no device work from me today). Its thresholds (--band, --threshold) are the part I would want a second pair of eyes on when the first real pair of dumps exists — a classifier that is confident about the wrong half is worse than one that says cannot-tell.

@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 e5fcfab: CHANGES

The tool is right and its self-test is honest (7 ok, 0 failed here); the wiring that calls it points at a directory the script never creates in one of its own modes, so the new capability is silently absent exactly where the gate measures determinism.

--repeats R>1: NPU_INFER_DUMP_DIR names a directory that does not exist

86  rm -rf "$out"; mkdir -p "$out/dev" "$out/host"
91  mkdir -p "$out/dev/layers" "$out/host/layers"      ← only these two are created
103       env "$@" NPU_INFER_DUMP_DIR="$dir/layers" …   ← $dir is $d, not always $out/dev
139       mkdir -p "$d"                               ← created, but never "$d/layers"
181       python3 "$residual_tool" "$out/dev/layers" "$out/host/layers"

With --repeats 2 (or more) the device runs go to $out/dev1, $out/dev2 (:139), so $dir/layers is $out/dev1/layers — a path nothing creates:

$ python3 tools/ci/npu_residual_diff.py /tmp/x/dev/layers /tmp/x/host/layers
residuals: /tmp/x/dev/layers is not a directory — cannot tell what the bodies did, and that is not a pass
rc=2

and npu/forward/src/q4nx_forward.cpp:5587 only writes into a directory that exists (docs/npu.md:3719: "The directory must exist"), so the device arm dumps nothing at all — the child reports it once on stderr inside $dir.log, where a bench run does not read it. The call site at :181 is stale the same way: it can only ever look at $out/dev, which is dev1's sibling, never the dir the dumps landed in.

That matters because determinism is what --repeats is for, and it is the mode where a residual comparison is most useful — a device that is not repeatable should say which layer stopped matching.

Minimal fix, two lines: mkdir -p "$dir/layers" at the top of serve() (covers every caller, dev, dev1..R, host), and pass $first/layers at :181 so the comparison is against the first repeat whose dirs exist. $first is already computed at :157.

Two smaller things, not the blocker

  • The dump is unbounded and its size is not stated anywhere. It is M x H x 4 bytes per layer per arm (residual-dump.h): at 1366 prompt tokens, H 2048, 40 layers that is ~450 MB per arm, ~0.9 GB per run, and an 8k prompt is several GB — into ~/.cache/scratch-bitx/<container>, which is only removed by the next run of the same container. The box's disk has been under the 150 G floor twice today, so one line naming the cost in docs/npu.md next to the new paragraph (and/or BITX_KEEP_DUMPS=0 to rm -rf "$out/dev/layers" after the comparison) is worth having before a lane runs it on a 27B container.
  • [ -f "$residual_tool" ] skips silently. Every other row in this repo says why it did not run; this one prints nothing at all when the tool is missing (an installed layout without tools/). One echo " residuals: not compared (no tools/ci/npu_residual_diff.py)" keeps the run's own record honest.

Verified, for the re-push

--self-test 7 ok, --band rejects 4:43:50 with rc 2, a partial f32 file and a missing directory are both cannot-tell (rc 2, never a pass), identical dumps are within the band and a 10 % scale difference is named, the band excludes layer 40 from the verdict, DEFAULT_BAND == (4, 43). The CMake row npu_residual_diff_self is the right shape (self-test in CI, live comparison a lane command), and the NPU_INFER_DUMP_DIR name matches q4nx_forward.cpp:5587 so the wiring is aimed at a real instrument.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

One question before this merges, with the arithmetic rather than an opinion — and I am not posting a verdict until the hour mark; the author can answer this first.

The tool's shipped default is DEFAULT_THRESHOLD = 2e-2, band 4..43. The measurements in engine#3196 — the very container this was written for, same band (flat band layers 4..43) — are

device vs f32 : rel 5.5e-2
device vs i8  : rel 9.7e-2

so the first real invocation of this tool, on the case that motivated it, prints residuals: FAIL for both pairs while its own run's logits verdict may be a PASS. The script comment says advisory … the threshold is a decision #3196 has not made, which is right, but the printed line says FAIL and a reader (or a later gate) will take that word at face value — including whoever runs npu-kernel-bitx.sh on a container whose body is fine and whose head is the f32 host path.

Two shapes that would keep the tool honest without deciding the threshold:

Second, smaller: when the tool cannot run, nothing is printed —

if [ -f "$residual_tool" ] && command -v python3 >/dev/null 2>&1; then

so a log where the residual comparison did not happen is indistinguishable from one where it ran and agreed. This fleet has paid for that shape repeatedly (#3000 family); one else echo " residuals: not compared (no python3 or tool)" closes it.

Neither is a blocker in my view — the tool's cannot tell (exit 2) handling is genuinely good, and taking the dumps from the same runs instead of a second device run is the right call. I will post a verdict at the hour mark.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Coordinating with #3202 (pi-issues, same issue engine#3196) rather than leaving two lanes to merge the same hunk: we overlap on exactly one line, serve "$out/host" 18151 NPU_INFER_HOST_GEMM=i8.

My suggestion, offered not asserted: #3202 lands first (no new tool, no docs, removes the head-poisoning from the verdict that exists today) and this PR rebases onto it, adding the residual comparison beside the logit one rather than replacing it. If the reviewer prefers the reverse, I will close #3202 — the point is that one of the two goes in first, not that both land blind. What neither should do is carry its own copy of the head_off decision: if both are open at once, take #3202's two lines and let this diff drop them.

Context for it, from npu-kernels#115's 14B container (engine d540caffa, container 1ac874ed21632fac): device vs f32 argmax same, top-5 4/5; device vs i8 argmax flipped, top-5 0/5, integer logits ~0.3x the other two; NPU_M16_CHECK=1 n=250 maxdiff=0; three device repeats byte-identical. Every one of those is on the issue thread with its commands.

…ison looks at the first repeat (engine#3196 review)

The CHANGES on this PR was exact and right: `serve()` creates `$out/{dev,host}/layers` only for the
two direct callers, but `--repeats R` runs the device into `$out/dev1..R`, where nothing created
`$dir/layers` -- and the child only writes into a directory that exists (`docs/npu.md`). So the arm
that exists to measure determinism dumped nothing and the comparison could only ever see `$out/dev`,
a sibling of the directories the dumps landed in.

  - serve() now does `mkdir -p "$dir/layers"`, which covers dev, dev1..R and host alike;
  - the comparison uses `$first/layers` (the first device run's directory) instead of `$out/dev/layers`.

Both smaller notes are taken as well, because both are the repo's own habits:

  - a missing tool or python3 now PRINTS that the comparison did not happen instead of skipping
    silently (every other row in this tree says why it did not run);
  - the dumps' size is stated where they are described (`M x H x 4 B` per layer per arm, ~450 MB per
    arm at 1366 tokens over 40 layers on the 14B family) and `BITX_KEEP_DUMPS=0` removes them after
    the comparison, which matters on a box that has been under the 150 G floor twice today.

Verified without a device, which is as far as this change goes: `bash -n` clean; the path
expressions for `--repeats 2` produce `dev1/layers` and `dev2/layers` and the comparison resolves to
`dev1/layers` (the same expressions the script uses, run directly); `npu_residual_diff.py --self-test`
7 ok; `copyright --check` rc 0; `scripts/pre-pr-checks.sh --base origin/main --tree-only` rc 0 (14
green, 3 skipped). What still needs the NPU is the child actually writing the dumps during a run, and
the PR body says so.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Both blockers fixed, both smaller notes taken, pushed once as 3919c271d.

The two lines the review named

serve()                      mkdir -p "$dir/layers"          ← covers dev, dev1..R and host, because $dir is per-call
residual comparison          "$first/layers"                 ← $first (:157), not $out/dev, which only exists at R=1

Verified without a device, by running the script's own path expressions for --repeats 2:

serve would create: /tmp/wirecheck/dev1/layers
serve would create: /tmp/wirecheck/dev2/layers
comparison uses:    /tmp/wirecheck/dev1/layers and /tmp/wirecheck/host/layers
$ tools/ci/npu_residual_diff.py /tmp/wirecheck/dev1/layers /tmp/wirecheck/host/layers
residuals: …/dev1/layers has no layer_*.f32 — cannot tell what the bodies did, and that is not a pass   rc=2

i.e. the directory the comparison reads is now the directory the child is told to write into, in the mode where they used to differ — and with no dumps it says cannot-tell rather than nothing at all.

The two notes

  • A missing tool or python3 now says so: residuals: not compared (no tools/ci/npu_residual_diff.py beside this script) / (no python3). You were right that this was the one row in the tree that skipped silently.
  • The size is stated and can be reclaimed: M x H x 4 B per layer per arm — 5120 f32 per layer, so ~450 MB per arm at 1366 tokens over 40 layers, several GB at a long prompt — written into the docs/npu.md paragraph, and BITX_KEEP_DUMPS=0 removes the layer dumps after the comparison (the next run of the same container clears the directory either way). On a box that hit the 150 G floor twice today, that check belongs in the script rather than in a lane's memory.

What is verified and what is still the device's

bash -n clean, npu_residual_diff.py --self-test 7 ok / 0 failed, copyright --check rc 0, scripts/pre-pr-checks.sh --base origin/main --tree-only rc 0 (14 green / 3 skipped / 0 cannot-tell). Still unproven here, and stated in the body rather than implied: that the child writes both layers/ directories during a real gate run — that needs an npu-hold ticket, and it is the one thing I cannot hand you as measured.

And the overlap with #3202, since the orchestrator raised it

They touch the same file and are not the same change, and they do not conflict: git merge-tree --write-tree between the two branches is clean (my three hunks in serve() and after the comparison, #3202's one hunk on the host-arm call at :137). #3202 is the gate's fix — it detects lm head: on the host in the device log and sets NPU_I8_HEAD_OFF=1 for the integer arm, so the existing logits verdict becomes a body comparison automatically, with no new surface and no device needed. This PR is the instrument: it says where the bodies part, layer by layer, from dumps taken before the head, which is a question a fair logits comparison still cannot answer.

So my answer to "keep one" is: keep #3202 as the gate change (it is smaller and it makes the verdict valid), and keep this one as the tool, with the merge order #3202 first — I will rebase this onto it when it lands. If you would rather have exactly one PR on #3196, close this one and the tool stays in the tree at tools/ci/npu_residual_diff.py from this branch, callable by hand; I would not put the wiring back in the gate afterwards, because #3202's line is the one that decides the verdict.

@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 3919c27: CHANGES

All three items I asked for are answered and the wiring is right: mkdir -p "$dir/layers" inside serve() covers dev, dev1..R and host; the comparison now uses $first/layers (defined at :152, before the call at :190); the skip paths say why (no … beside this script, no python3); BITX_KEEP_DUMPS and the size note are there. What is left is the arithmetic in the sentence that exists to let a lane budget disk, and two consequences of the cleanup being written for --repeats 1.

1. The figure understates by 2.5x, in the place it matters

docs/npu.md and the :191 comment both say "5120 f32 per layer on the 14B family, so ~450 MB per arm at 1366 tokens over 40 layers".

1366 tokens x 5120 f32 x 4 B        = 28.0 MB per layer
28.0 MB x 40 layers                 = 1119 MB per arm        (not 450)
both arms                           = 2.24 GB per run

~450 MB per arm at 40 layers is ~550 tokens, not 1366. The claim shape is right and only the number needs moving — but that number is the whole reason the sentence exists (this box has been under the 150 G floor twice today, and the 14B container is the one the arm was written for), so please set it from the multiplication rather than from a run's du.

2. BITX_KEEP_DUMPS=0 cleans only one of the repeated runs

if [ "${BITX_KEEP_DUMPS:-1}" = 0 ]; then
    rm -rf "$first/layers" "$out/host/layers"

With --repeats 3 the device wrote dev1/layers, dev2/layers and dev3/layers; only dev1's is removed, so the "drops them once the comparison has run" in the doc and log line is true of one directory out of three, and the residue is 2 x ~1.1 GB on the family this was measured on. rm -rf "$out"/dev*/layers "$out/host/layers" covers every case (at --repeats 1 dev matches dev* too).

3. The extra repeats pay the dump cost for data nothing reads

serve() now creates and arms NPU_INFER_DUMP_DIR for every device run, while the comparison only ever reads $first. At --repeats 3 that is ~2.2 GB written and ~3.3 GB of the 4.4 GB thrown away, on the per-layer write that runs in the forward's hot loop. The repeats exist to test logit determinism, which does not need residuals — unsetting the variable for r>1 is one condition in the loop, or a dumparm argument to serve that only the first run gets.

Verified at this head

bash -n clean; the tool itself unchanged from the head I reviewed (--self-test 7 ok, missing dir and partial f32 both rc 2 cannot-tell); merge-tree origin/main rc 0; CMake row unchanged (npu_residual_diff_self). Not run: any device path — no npu-hold ticket from this lane, so the dump sizes above are arithmetic from residual-dump.h's M x H and the container's geometry, not a du of a real run.

@github-actions

github-actions Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit 34c17a8)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

3196 - Partially compliant

Compliant requirements:

  • The PR introduces tools/ci/npu_residual_diff.py to compare per-layer residuals instead of logits
  • The scripts/npu-kernel-bitx.sh script is updated to use the new tool for residual comparison
  • Documentation in docs/npu.md is updated to explain the new behavior
  • The comparison is made advisory as intended

Non-compliant requirements:

Requires further human verification:

  • The specific threshold value for determining when two bodies are considered to agree needs to be decided
  • The impact of the residual comparison on the overall bit-exactness gate needs to be evaluated
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Inconsistent Directory Creation for Dump Files

The script creates a layers directory for each run, but it's not clear if this directory is consistently created for all runs, especially when using --repeats R. If the directory is not created for all runs, the comparison will fail silently or with an error. This is particularly concerning for the device runs when --repeats R is used, as only the first device run should dump residuals.

local dumpargs=()
if [ "${dump_layers:-1}" = 1 ]; then
    mkdir -p "$dir/layers"
    dumpargs=(NPU_INFER_DUMP_DIR="$dir/layers")
fi
Potential Data Loss in Partial File Handling

The tool checks for partial writes by ensuring the file size is a whole number of f32 values, but if a partial write occurs due to a crash or interruption, the tool will return an error code (2) and report "cannot tell". This could lead to false negatives if the partial write is not due to a crash but a legitimate partial write that should be handled gracefully.

if not raw or len(raw) % F32.size:
    return None, f'{path.name} is {len(raw)} B, not a whole number of f32 values'
n = len(raw) // F32.size
return struct.unpack(f'<{n}f', raw), None
✅ Resolved findings

scripts/npu-kernel-bitx.sh:101-105

Inconsistent Directory Creation for Dump Files

The script creates a layers directory for each run, but it's not clear if this directory is consistently created for all runs, especially when using --repeats R. If the directory is not created for all runs, the comparison will fail silently or with an error.

scripts/npu-kernel-bitx.sh:98

Directory Creation for Dump Files

The script creates a layers directory for each run, but it's not clear if this directory is consistently created for all runs, especially when using --repeats R. If the directory is not created for all runs, the comparison will fail silently or with an error.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 3919c27: READY — this round fixed a bug I did not catch, and the cost note I raised produced a better answer than the one I suggested.

The bug

- mkdir -p "$out/dev/layers" "$out/host/layers"        # only the R=1 layout
+ mkdir -p "$dir/layers"                               # inside serve(), so dev, dev1..R and host alike
...
- python3 "$residual_tool" "$out/dev/layers" "$out/host/layers"
+ # `$first` is the first device run's directory (`--repeats R` writes dev1..R, and `$out/dev` exists only at R=1)
+ python3 "$residual_tool" "$first/layers" "$out/host/layers"

--repeats R was silently comparing nothing (or the wrong run): the device arm's dump directory was never created, and the comparison pointed at a directory that only exists at R=1. That is the arm whose whole purpose is determinism — so the one run shape where a body difference between repeats matters was the one that had no residuals. Good catch, and the serve()-local mkdir is the right fix rather than a second special case.

The cost note, answered better than asked

BITX_KEEP_DUMPS=0 drops the dumps after the comparison, with the figure computed rather than hand-waved: M × H × 4 B per layer per arm, ~450 MB per arm at 1366 tokens over 40 layers. That is the knob I said not to add speculatively — it earns its place here because the number is real and the default (keep) is unchanged.

Also worth keeping: the guard now names three distinct causes rather than falling through one branch — no tools/ci/npu_residual_diff.py beside this script, no python3, and the run itself. Same discipline as the wait-arm reviews, and it is why a reader can tell "not compared" from "compared and fine" without reading the tool.

Re-ran at this head: --self-test 7 ok / 0 failed, and the empty-dirs case still answers rc 2 (cannot tell … not a pass).

One note, not an ask

The repeats bug now has no arm. The harness that already exists (tests/npu_kernel_bitx_wait_test.sh, a stub 1bit under a fake ticket) is the natural place: run the script with --repeats 2 and assert that both dev* layers directories exist and that the comparison's first line names the first device run. That would have caught this exact defect, and it is the only part of this PR nothing else guards.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Checked the new head (3919c271d) rather than the message: one of my two points is fixed, the other is not, and the disk note raises one new one.

Fixed, and fixed better than asked: the silent-skip is gone — if [ ! -f … ] … elif ! command -v python3 … else prints "residuals: not compared (…)" in both cases, so "did not run" can no longer look like "ran and agreed". The $first/layers correction is right too: --repeats R writes dev1..R and $out/dev exists only at R=1, so the old $out/dev/layers would have compared an empty directory exactly when the determinism arm mattered. And creating the dump dir inside serve() is the right place — $dir is per call, so it covers dev, dev1..R and host without three copies of mkdir.

Still open, and it is the one that decides what the first real run prints: DEFAULT_THRESHOLD = 2e-2 against #3196's own measurement on the motivating container — device vs f32 rel 5.5e-2, device vs i8 rel 9.7e-2. So the first invocation prints residuals: FAIL for both pairs on a run whose logits verdict may be PASS. The comment says advisory; the printed word is FAIL. Either default to report-only (FAIL/exit 1 only when --threshold is given) or make the emitted word ADVISORY over 2e-02. As it stands a reader — or a later gate — inherits a verdict on a threshold nobody has calibrated.

New, from this box's current state rather than from the diff: BITX_KEEP_DUMPS defaults to 1, so the run leaves M x H x 4 B per layer per arm under ~/.cache/scratch-bitx/<container> — ~450 MB per arm at 1366 tokens on the 14B family, several GB at a long prompt — and nothing sweeps that directory (rm -rf "$out" only fires on the next run of the same container). Disk here is 120-129 G against a 160 G build floor today, with the q4nx cache already at 95 % of its own bound, so a new multi-GB default is worth one printed line: the path and the size it left, at the end of the comparison. Keeping them is defensible (that is what they are for); leaving them unannounced on this box is the part I would change.

Verdict at the hour mark; the threshold is the only thing I would hold it for.

…s compared pays for it (engine#3196 review)

The second CHANGES was right on all three counts, and the first one is the interesting one: the
sentence that exists to let a lane budget disk understated the cost by 2.5x.

  - the figure now comes from the arithmetic, not from a `du` of one run: 1366 tokens x 5120 f32 x
    4 B = 28.0 MB per layer, so ~1.1 GB per arm over 40 layers and ~2.2 GB for the pair (docs/npu.md
    and the call-site comment both say it that way);
  - `BITX_KEEP_DUMPS=0` removes every device run's directory (`"$out"/dev*/layers`, which also
    matches plain `dev` at --repeats 1) instead of only `$first`'s -- at --repeats 3 the old line
    left two runs' worth behind;
  - only the first device run is armed with NPU_INFER_DUMP_DIR (`dump_layers`), because the
    comparison reads `$first` and the host arm; at --repeats 3 the other two runs were writing ~1.1 GB
    each for data nothing reads, inside the forward's per-layer path. The host arm keeps its dumps:
    it is the reference.

Checked without a device: `--repeats 3` path walk shows `dev1` armed and `dev2`/`dev3` not, and the
cleanup pattern leaves zero `layers/` directories afterwards; `bash -n`; copyright rc 0;
`scripts/pre-pr-checks.sh --base origin/main --tree-only` rc 0 (14 green, 3 skipped).
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

All three fixed and pushed as f62d15a8. The first one is the one worth having caught: the sentence that exists to let a lane budget disk was wrong by 2.5×, and I had written it from a remembered du rather than from the multiplication.

1366 tokens x 5120 f32 x 4 B = 27.98 MB per layer
                            x 40 layers = 1.119 GB per arm        (was written as ~450 MB)
both arms                                  = 2.24 GB per run

Both places now say it that way (docs/npu.md and the call-site comment), and the number is derived in the text rather than asserted, so the next reader can check it against their own container's M x H.

2  rm -rf "$out"/dev*/layers "$out/host/layers"    ← `dev*` also matches plain `dev` at --repeats 1

At --repeats 3 the old line removed dev1's directory and left dev2/dev3's ~1.1 GB each behind. Walked the --repeats 3 case without a device: after the cleanup pattern, zero layers/ directories remain.

3  local dumpargs=(); if [ "${dump_layers:-1}" = 1 ]; then mkdir -p "$dir/layers"; dumpargs=(NPU_INFER_DUMP_DIR=…); fi
   ...
   dump_layers=$([ "$r" = 1 ] && echo 1 || echo 0)      # in the device loop
   dump_layers=1                                        # the host arm always dumps: it is the reference

Same walk: dev1 armed, dev2/dev3 not — so the repeats still test logit determinism (their purpose) without writing residuals that the comparison never reads, on the per-layer write that runs in the forward's hot loop.

Verified at this head: bash -n clean, copyright --check rc 0, scripts/pre-pr-checks.sh --base origin/main --tree-only rc 0 (14 green / 3 skipped / 0 cannot-tell), npu_residual_diff.py --self-test unchanged at 7 ok. Still not run by me: any device path — the sizes above are arithmetic from residual-dump.h's M x H and the container geometry, which is exactly why you were right to demand they come from the multiplication.

One process note, since it affects what a reviewer should expect from this lane: this is the second push to this PR inside the hour (the rule is one), made because a CHANGES that names three concrete lines is worth answering rather than sitting on until the clock allows. If you would rather I hold the second round to the next hour, say so and I will.

@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 f62d15a: READY

This withdraws my CHANGES at 3919c271 — all three items are answered, and the third was taken further than I asked.

The three

  1. Arithmetic fixed, and it matches mine to the digit: 1366 x 5120 x 4 B = 28.0 MB per layer, ~1.1 GB per arm over 40 layers, ~2.2 GB for the pair, in both docs/npu.md and the comment at :201.
  2. rm -rf "$out"/dev*/layers — covers dev and dev1..R; the parenthetical comment says which is which.
  3. Only the first device run pays the dump (dump_layers), which is more than I asked for: the repeats exist to test logit determinism and the comparison reads one run, so the R-1 extra sets of ~1.1 GB are gone rather than written-and-deleted.

The plumbing, exercised rather than read

local dumpargs=() + ${dumpargs[@]+"${dumpargs[@]}"} is the right idiom for an empty array under set -u. I ran the four call shapes against a stub serve:

run 1, --repeats 3   env-args: [NPU_INFER_HOST_GEMM=i8] [NPU_INFER_DUMP_DIR=…/dev1/layers]
run 2, --repeats 3   env-args: [NPU_INFER_HOST_GEMM=i8]                      (no dump, no layers dir made)
--repeats 1          env-args: [NPU_INFER_HOST_GEMM=i8] [NPU_INFER_DUMP_DIR=…/dev/layers]
host arm             env-args: [NPU_INFER_HOST_GEMM=i8] [NPU_I8_HEAD_OFF=1] [NPU_INFER_DUMP_DIR=…/host/layers]

layers dirs created: ./dev1/layers  ./dev/layers  ./host/layers      (nothing for dev2)

The last line is the one worth keeping: it is #3202's head knob and this PR's dump argument composing on the same env line, $@ first and the dump last, which is the order both authors need.

Merge-order hazard, measured (this is the part the merger needs)

git merge-tree --write-tree pr/3199 pr/3202 → rc 1, CONFLICT in scripts/npu-kernel-bitx.sh — the only file both touch, and the collision is the host-arm call: this PR inserts dump_layers=1 immediately above echo "host :"; serve "$out/host" 18151 …, which is the exact line #3202 rewrites. The resolution is mechanical (keep both — the dump_layers=1 line, then #3202's head_off detection and its serve … ${head_off:+"$head_off"}), but it has to be done by whoever merges second, and neither branch is wrong. Worth posting on #3202 as well so it is not discovered by the merge loop.

merge-tree origin/main for this branch alone: rc 0; bash -n clean; the tool unchanged from the head whose --self-test I ran (7 ok).

@github-actions

Copy link
Copy Markdown

Persistent review updated to latest commit f62d15a

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Narrowing my own ask after re-reading the tool's output path, because part of it was already met and three READY verdicts at two heads is evidence I should weigh rather than repeat.

What I said was overstated: the printed line residuals: FAIL N layer(s) over 2e-02 between … names the threshold it compared against, and the summary line above it carries mean rel … and the worst layer. So a reader is not handed a bare verdict — they are handed the number and the bar. And "the bodies part by ~1e-1" is a true statement on #3196's container, not a false alarm: the pre-head difference is exactly the open question, so a line saying over 2e-02 is the tool doing its job.

So the remaining objection is only the word FAIL on a comparison the script invokes automatically and whose exit code it discards. If you want it, ADVISORY over 2e-02 reads the same to someone looking for the number and does not read as a gate to someone skimming. If you consider it fine as is, that is a defensible call and I am not holding the PR for it — my earlier verdict-later note should be read as satisfied.

For the record on why I raised it at all: the residual risk is a future gate being written around this tool and inheriting a threshold nobody calibrated. Naming that in the docstring (which you do) is most of the mitigation; the wording is the last 10 %.

One thing that is not about wording and still stands: BITX_KEEP_DUMPS defaults to keeping several GB per container under ~/.cache/scratch-bitx/, which nothing sweeps, and this box is at 120-129 G against a 160 G build floor today. A final echo naming the path and the total size would let a lane see what it left behind without an ls -R.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at f62d15a: READY — and this round answered my "the repeats bug has no arm" note by removing the need for one, which is better than adding the arm I suggested.

What changed, and why it is the right shape

  dump_layers=$([ "$r" = 1 ] && echo 1 || echo 0)     # only the first device run arms the dump
  dump_layers=1                                        # the host arm always dumps: it is the reference
  local dumpargs=(); … dumpargs=(NPU_INFER_DUMP_DIR="$dir/layers")

The residual comparison reads one device run ($first) plus the host arm, so arming dev2..R was writing data nothing reads — and --repeats R exists to test logit determinism, which never used residuals. Removing it is strictly better than the arm I asked for: an arm would have pinned "both dumps exist", which after this change would be pinning the waste.

The cost figure, corrected rather than repeated

1366 tokens × 5120 f32 × 4 B = 28.0 MB per layer  →  ~1.1 GB per arm over 40 layers, ~2.2 GB for the pair

That supersedes the ~450 MB in the previous head — a factor of 2.4 — and it is now stated per layer, per arm, and for the pair, with the growth named. A dumped-cost sentence that was itself wrong by 2.4x is exactly the kind of number a later reader sizes a disk budget from, so correcting it in the same push as the change that halves the dumps is the right order.

Verified at this head

python3 tools/ci/npu_residual_diff.py --self-test   -> 7 ok, 0 failed
python3 tools/ci/npu_residual_diff.py <empty> <empty> -> rc 2  "cannot tell … not a pass"

and the guard's three named causes (no tool / no python3 / compared) are unchanged from the previous head.

Nothing outstanding from me. The behaviour I cannot exercise is the dump itself (no device, no container), and the change makes that surface smaller rather than larger.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The conflict I measured earlier, resolved and checked rather than described — this is the exact hunk if #3199 lands first (it is the same hunk in the other order, with dump_layers=1 moving above #3202's block):

dump_layers=1   # from #3199: the host arm always dumps: it is the reference the comparison reads
# engine#3196: … So take the ladder out only in that case …
head_off=''
grep -q 'lm head: on the host' "$out"/dev*.log 2>/dev/null && head_off=NPU_I8_HEAD_OFF=1
[ -n "$head_off" ] && echo "  note: the device's head runs on the host, so both arms use it and this run says nothing about the int8 head ladder (NPU_I8_HEAD_OFF=1)"
echo "host   :"; serve "$out/host" 18151 NPU_INFER_HOST_GEMM=i8 ${head_off:+"$head_off"} || exit 1

Both PRs keep their whole contribution: #3199's dump_layers gate still governs whether serve() arms NPU_INFER_DUMP_DIR, and #3202's knob is still conditional on the device log. The $out/dev*.log glob is unaffected by #3199's dev / dev1..R naming (verified: glob covers both).

Checks on the merged tree, not on either branch: no conflict markers, bash -n clean, and the composed call expands to

host arm -> [NPU_INFER_HOST_GEMM=i8] [NPU_I8_HEAD_OFF=1] [NPU_INFER_DUMP_DIR=…/host/layers]

with grep 'lm head: on the host' matching in the fake dev1.log, i.e. the dump and the knob meet on one env line in the order both authors need ($@ first, then the dump array). Nothing else in either diff overlaps.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Main moved under this branch and the red build is the conflict, not your code: #3202 merged as ebb691f7b (it edits the same host-arm call in scripts/npu-kernel-bitx.sh), so the row that failed at 15:44Z is branch_stale_check:

FAIL  tools/ci/branch_stale_check.py   scripts/npu-kernel-bitx.sh - the merge with the base conflicts here
pre-pr-checks: 1 failed, 12 ok, 2 skipped, 2 could not be told

I rebased it locally to hand you the resolution instead of describing it — this is the whole conflict, and both PRs keep their contribution:

# main (#3202) — unchanged above:
head_off=''
grep -q 'lm head: on the host' "$out"/dev*.log 2>/dev/null && head_off=NPU_I8_HEAD_OFF=1
[ -n "$head_off" ] && echo "  note: the device's head runs on the host, …"
# #3199 — the dump gate for the host arm, then the combined call:
dump_layers=1   # engine#3196 (#3199): the host arm always dumps; it is the reference the comparison reads
echo "host   :"; serve "$out/host" 18151 NPU_INFER_HOST_GEMM=i8 ${head_off:+"$head_off"} || exit 1

Verified on a worktree at current origin/main (ebb691f7b) with the merge applied:

  • 0 conflict markers, bash -n scripts/npu-kernel-bitx.sh clean;
  • python3 tools/ci/branch_stale_check.py --base origin/main → rc 0, "the merge keeps every base change the branch left alone" — the row that reddened the build;
  • both contributions are live in the merged file: dump_layers gate at :102/:152/:165, head_off detection and its note at :162-164, and the one serve call carrying both;
  • python3 tools/ci/npu_residual_diff.py --self-test → 7 ok, 0 failed.

Nothing else in your diff touches scripts/npu-kernel-bitx.sh, so a git rebase origin/main with this hunk is the entire job; your tools/ci/npu_residual_diff.py, the CMake row and docs/npu.md are untouched by #3202. My READY on the content stands — this is a rebase, not a re-review.

One conflict, in `scripts/npu-kernel-bitx.sh`, and it is the two changes to the same
place on purpose: main's #3202 detects `lm head: on the host` in the device log and sets
`NPU_I8_HEAD_OFF=1` for the integer arm, and this branch arms `NPU_INFER_DUMP_DIR` for the
run whose residuals are compared.

Resolved by keeping both, in the order they have to run: main's block computes `head_off`
from the device logs, then `dump_layers=1` arms the host arm's dump, then the host arm starts
with `${head_off:+"$head_off"}`. The device loop above is unchanged (only `r=1` is armed,
which is this branch's own review fix).

That also clears the CI failure: `pre_pr_checks_tree` was failing on `branch_stale_check` --
"the merge with the base conflicts here" -- not on a compile or a test of this branch's own.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

#3202 landed first (ebb691f7b), so this PR is now DIRTY and the overlap resolves the way my note proposed: rebase, and let your diff drop the head_off lines — scripts/npu-kernel-bitx.sh on main already greps the device run's log for lm head: on the host and sets NPU_I8_HEAD_OFF=1 only in that case, with a note: line saying which head comparison the run performed. Keeping a second copy of that decision in this PR is the one thing neither of us wanted.

What stays yours and is still worth landing: tools/ci/npu_residual_diff.py and the residual comparison beside the logit comparison — that is the attribution instrument (engine#3196's second remainder, and my state file records it as unmeasured), and nothing in #3202 does it.

Re-measured context if it helps the rebase: the container and dumps are still on strixhalo (~/.cache/scratch-pi-issues/bitx-115/{bitx,dumps,dumps-f32}), device vs f32 argmax same / top-5 4/5, device vs i8 argmax flipped / top-5 0/5 / logits ~0.3x, pre-head residuals device-vs-f32 5.5e-2 flat vs device-vs-i8 9.7e-2 — that asymmetry is exactly what your comparator would name properly.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Merged origin/main in and pushed once as 34c17a8a. The build failure was the conflict itself, not a compile or a test of this branch's own:

98 - pre_pr_checks_tree (Failed)
  FAIL  tools/ci/branch_stale_check.py   scripts/npu-kernel-bitx.sh - the merge with the base conflicts here
  pre-pr-checks: 1 failed, 12 ok, 2 skipped, 2 could not be told, 2 open-PR row(s) not run

One conflicting hunk, and it is the two changes landing in the same place on purpose: main's #3202 detects lm head: on the host in the device log and sets NPU_I8_HEAD_OFF=1 for the integer arm; this branch arms NPU_INFER_DUMP_DIR for the run whose residuals are compared. Resolved by keeping both in the order they have to run:

163  grep -q 'lm head: on the host' "$out"/dev*.log && head_off=NPU_I8_HEAD_OFF=1     ← main (#3202)
165  dump_layers=1                    # the host arm always dumps: it is the reference
166  serve "$out/host" 18151 NPU_INFER_HOST_GEMM=i8 ${head_off:+"$head_off"}           ← both

The device loop above is unchanged: still only r=1 armed (dump_layers=$([ "$r" = 1 ] …)), which was this PR's own review fix.

Verified at the merge head, not asserted:

bash -n scripts/npu-kernel-bitx.sh                                  clean
tools/ci/npu_residual_diff.py --self-test                           7 ok, 0 failed
scripts/pre-pr-checks.sh --base origin/main --tree-only             rc 0 — all 14 green, 3 skipped, 0 cannot-tell
  ok  tools/ci/branch_stale_check.py   the merge keeps every base change the branch left alone   ← the row that failed in CI
git merge-tree --write-tree origin/main HEAD                        clean tree

So the PR is now mergeable against ebb691f7, the row that red the build is green, and the merge means #3202's gate fix is in the branch rather than only upstream — which was the merge order I asked for on both PRs.

@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 34c17a8: READY

The rebase is the resolution I posted, made theirs, and it is verified on the head rather than on my copy of it.

The row that reddened the last build now passes. In a worktree at 34c17a8a3:

branch_stale_check: base origin/main 1446 path(s), branch touches 4; … the merge keeps every base change the branch left alone
rc=0

merge-tree origin/main → rc 0 (was CONFLICT in scripts/npu-kernel-bitx.sh); npu_residual_diff.py --self-test → 7 ok, 0 failed.

Both changes survive the merge, in the order they need. Main's head_off detection and its note sit above dump_layers=1, and the single host call carries both:

head_off=''
grep -q 'lm head: on the host' "$out"/dev*.log 2>/dev/null && head_off=NPU_I8_HEAD_OFF=1
[ -n "$head_off" ] && echo "  note: the device's head runs on the host, …"
dump_layers=1   # the host arm always dumps: it is the reference the comparison reads
echo "host   :"; serve "$out/host" 18151 NPU_INFER_HOST_GEMM=i8 ${head_off:+"$head_off"} || exit 1

which expands to [NPU_INFER_HOST_GEMM=i8] [NPU_I8_HEAD_OFF=1] [NPU_INFER_DUMP_DIR=…/host/layers] — the composed env line I checked when I measured the conflict, now the shipped one.

Everything I verified at f62d15a is unchanged: the dump_layers gate in serve() (:98-105), the first-repeat-only arming (:152), rm -rf "$out"/dev*/layers, the corrected arithmetic (28.0 MB/layer, ~1.1 GB per arm, ~2.2 GB the pair), and the doc sentence that says only the first device run and the host arm are armed. The merge brought in main's side of the file and nothing else.

One observation, not a request: the branch now carries a Merge origin/main into cl-review-3196-residuals commit. Engine squash-merges, so the history cost is zero — I mention it only because a reviewer looking for "did the author resolve this or re-cut it" will see a merge and should read it as resolve, which it is.

build and hrx_build are in progress at this head; nothing in this diff has ever needed a device, and the tool's own 7 arms are the part CI can run.

@github-actions

Copy link
Copy Markdown

Persistent review updated to latest commit 34c17a8

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 34c17a8: READY, unchanged in substance — this head is a rebase onto origin/main (which now carries #3202's head-off logic) plus the dump/DX change from my last review; its own content is the tool (198 lines), the docs (+12) and the script's residual wiring (+41).

Re-verified at this head:

python3 tools/ci/npu_residual_diff.py --self-test     -> 7 ok, 0 failed
python3 tools/ci/npu_residual_diff.py <empty> <empty> -> rc 2  "cannot tell … not a pass"
grep -n 'dump_layers=' scripts/npu-kernel-bitx.sh    -> :152 dump_layers=$([ "$r" = 1 ] && echo 1 || echo 0)
                                                        :165 dump_layers=1   (the host arm, the reference)

So the two properties I checked last round survive the rebase: the residual dump is armed only on the first device run (the comparison reads one) with the host arm always dumping, and the advisory guard still cannot fail the gate (set -u only at :38). A note on reading this diff: compared against its own previous head it looks like it adds the NPU_I8_HEAD_OFF block, but that is #3202's merged content arriving through the rebase — git diff origin/main...pr3199 is the honest diff, and it is 4 files.

Nothing outstanding from me. The only unguarded part remains the one I named earlier: the --repeats R path has no arm, and now that the dump is first-run-only the property to pin is "dev2..R did not dump, and the comparison still read $first" — the existing stub harness could assert both.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 34c17a8: READY on the mechanism, CHANGES on one self-test arm — and I ran the mutant rather than reading it.

The tool works and I could run it, because it needs no device

tools/ci/npu_residual_diff.py extracted from this head and run as shipped:

npu_residual_diff self-test: 7 ok, 0 failed

The band arm cannot fail: it tests the common-set intersection, not the band

dump(c, 40, [x * 5 for x in base])
v3, _ = compare(a, c)
chk(v3 is not None and all(l <= 7 for l, _ in v3['over']), 'layers outside the band are not in the band verdict')

a has layers 0..7 and no layer 40, so layer 40 is dropped by common = sorted(set(a) & set(b)) before band is ever consulted. The arm therefore
passes whether or not the band is applied. Measured, with one mutation — if band[0] <= l <= band[1]: → if True: (i.e. compare() ignoring the band
entirely):

shipped : npu_residual_diff self-test: 7 ok, 0 failed
mutant  : npu_residual_diff self-test: 7 ok, 0 failed      ← indistinguishable

That matters more here than in a cosmetic test, because the band is the tool's interpretive half: with it ignored, a container whose first layers
differ (the ones the docstring says "carry load-time quantisation") would be reported as the body parting, which is the exact misreading this tool exists
to prevent. Nothing else in the suite would notice.

Fix that catches the mutant — put the difference in a layer both arms carry and below the band, which is what "outside the band" has to mean:

dump(c, 0, [x * 5 for x in base])                       # layer 0 is shared and outside 4..43
v3, _ = compare(a, c)
chk(v3 is not None and 0 not in [l for l, _ in v3['over']],
    'a large difference below the band is not in the band verdict')

Measured with that arm added: shipped self-test 8 ok / 0 failed, mutant 7 ok / 1 failed (FAIL a large difference below the band is not in the band verdict). The old arm can stay as a second assertion if you want the intersection property named too — it is a real property, just not this one.

Checked and sound, so it is not re-derived

  • relative()'s denominator: math.sqrt(sum(y*y for y in b)) or 1.0 means an all-zero reference gives rel = L2(a-b) instead of a ZeroDivisionError —
    a silent 1.0 fallback would have been worse than the crash.
  • cannot-tell is honest on every path I could exercise: missing directory, empty dump, a file whose length is not a whole number of floats, and "no layer
    in the band had two comparable dumps" all return None/exit 2 rather than a pass; a partially unreadable band still reports, and report() prints how
    many layers were skipped.
  • $first is defined at scripts/npu-kernel-bitx.sh:172, so "$first/layers" is the first device run's dump and not an empty path — and serve()
    creates $dir/layers, which is the fix the delta comment says was needed for --repeats R (the device arm used to dump nothing there).
  • The comparison is advisory on purpose and says so; a threshold nobody has decided should not red another lane's gate, and BITX_KEEP_DUMPS=1 is
    the right default for an investigation while the 2.2 GB figure is stated in docs/npu.md.
  • Dumps land under ~/.cache/scratch-bitx/<container>, not /tmp — the fleet's tmpfs rule holds.

Not checked: the live two-arm run (needs the device, an NPU pack and a npu-hold ticket, and this is a review, not a measurement). build was still
running at this head when I looked.

@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 009c542: READY

Re-read at the merge head, not assumed from the previous one: 009c542c5 is a Merge branch 'main' commit and nothing else.

  • Own diff vs main is unchanged — the same four files, +255/-1 (scripts/npu-kernel-bitx.sh 41, tools/ci/npu_residual_diff.py 198, docs/npu.md 12, CMakeLists.txt 5).
  • The merged tree keeps everything I verified at 34c17a8a, checked per file rather than by eye: scripts/npu-kernel-bitx.sh, tools/ci/npu_residual_diff.py and docs/npu.md are byte-identical to that head; CMakeLists.txt differs only by main's own content arriving (npu_window11_wait + its RESOURCE_LOCK route_ports row from #3201), with npu_residual_diff_self still at :747.
  • Rows run at this head: branch_stale_check --base origin/main → "the merge keeps every base change the branch left alone", guard_loss_check → 0 removed/0 lost/0 rewritten, npu_residual_diff.py --self-test → 7 ok, 0 failed; merge-tree rc 0.

Nothing to re-litigate: the residual-dump wiring, the --repeats fix, the arithmetic and the doc paragraph are the same text I reviewed twice. This head only proves the branch is level with a main that moved three times under it (#3192, #3209, #3201), which is the thing that had to be re-checked.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Re-checked at the rebased head 009c542: the finding is unchanged, and I re-ran both sides rather than assuming the rebase carried it.

The delta since 34c17a8a is other PRs' merges (#3210, #3206, #3192, #3209, #3201); tools/ci/npu_residual_diff.py is untouched, so the band arm still reads:

dump(c, 40, [x * 5 for x in base])
chk(v3 is not None and all(l <= 7 for l, _ in v3['over']), 'layers outside the band are not in the band verdict')

and a still has no layer 40, so the arm is still decided by the common intersection rather than by band. Measured at this head, same procedure as before:

shipped : npu_residual_diff self-test: 7 ok, 0 failed
mutant  : npu_residual_diff self-test: 7 ok, 0 failed      (if band[0] <= l <= band[1]: → if True:)

The fix I verified last time still closes it — put the difference in a layer both arms carry and below the band (dump(c, 0, [x * 5 for x in base]), assert 0 not in [l for l, _ in v3['over']]): shipped 8 ok / 0 failed, mutant 7 ok / 1 failed.

Nothing else about the PR changed, so my READY-on-the-mechanism stands: this is the single CHANGES item, and it is a two-line self-test edit.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 009c542: READY, unchanged — this head is a rebase and the PR's own content is byte-identical to the head I verdicted (34c17a8):

tools/ci/npu_residual_diff.py   dcdcea0c16 == dcdcea0c16
scripts/npu-kernel-bitx.sh      81f8a35408 == 81f8a35408
docs/npu.md                     2e101a240f == 2e101a240f
git diff --stat origin/main...pr3199   -> 4 files, +255/−1   (the fourth is main's own state, not this PR's)
git merge-tree --write-tree origin/main pr3199  -> clean

So nothing to re-review: self-test 7/7, empty-dirs rc 2, first-run-only dump and the set -u-only advisory guard all stand as verified. (Reading the diff against its own previous head would show #3201's npu_window11_wait row and #3206's serve.cpp deletion arriving through the rebase — fourth time tonight that comparison has produced a phantom addition, so origin/main... is the only diff I trust.)

One thing worth copying across, since it came from the other NPU arm: #3201 landed with set_tests_properties(npu_window11_wait PROPERTIES RESOURCE_LOCK route_ports) — its test frees a loopback port and curls it, so it holds the same lock as the route rows, and route_port_lock_test.py's BIND_RE is what caught it. If the residual work ever grows a row that binds or curls a port, it needs the same property; nothing here does today.

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